Debian Codegraph @

library/msgcat/msgcat.tcl

raw
1 # msgcat.tcl --
2 #
3 # This file defines various procedures which implement a
4 # message catalog facility for Tcl programs. It should be
5 # loaded with the command "package require msgcat".
6 #
7 # Copyright (c) 2010-2015 Harald Oehlmann.
8 # Copyright (c) 1998-2000 Ajuba Solutions.
9 # Copyright (c) 1998 Mark Harrison.
10 #
11 # See the file "license.terms" for information on usage and redistribution
12 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13
14 package require Tcl 8.5-
15 # When the version number changes, be sure to update the pkgIndex.tcl file,
16 # and the installation directory in the Makefiles.
17 package provide msgcat 1.6.1
18
19 namespace eval msgcat {
20 namespace export mc mcexists mcload mclocale mcmax mcmset mcpreferences mcset\
21 mcunknown mcflset mcflmset mcloadedlocales mcforgetpackage\
22 mcpackageconfig mcpackagelocale
23
24 # Records the list of locales to search
25 variable Loclist {}
26
27 # List of currently loaded locales
28 variable LoadedLocales {}
29
30 # Records the locale of the currently sourced message catalogue file
31 variable FileLocale
32
33 # Configuration values per Package (e.g. client namespace).
34 # The dict key is of the form "<option> <namespace>" and the value is the
35 # configuration option. A non-existing key is an unset option.
36 variable PackageConfig [dict create mcfolder {} loadcmd {} changecmd {}\
37 unknowncmd {} loadedlocales {} loclist {}]
38
39 # Records the mapping between source strings and translated strings. The
40 # dict key is of the form "<namespace> <locale> <src>", where locale and
41 # namespace should be themselves dict values and the value is
42 # the translated string.
43 variable Msgs [dict create]
44
45 # Map of language codes used in Windows registry to those of ISO-639
46 if {[info sharedlibextension] eq ".dll"} {
47 variable WinRegToISO639 [dict create {*}{
48 01 ar 0401 ar_SA 0801 ar_IQ 0c01 ar_EG 1001 ar_LY 1401 ar_DZ
49 1801 ar_MA 1c01 ar_TN 2001 ar_OM 2401 ar_YE 2801 ar_SY
50 2c01 ar_JO 3001 ar_LB 3401 ar_KW 3801 ar_AE 3c01 ar_BH
51 4001 ar_QA
52 02 bg 0402 bg_BG
53 03 ca 0403 ca_ES
54 04 zh 0404 zh_TW 0804 zh_CN 0c04 zh_HK 1004 zh_SG 1404 zh_MO
55 05 cs 0405 cs_CZ
56 06 da 0406 da_DK
57 07 de 0407 de_DE 0807 de_CH 0c07 de_AT 1007 de_LU 1407 de_LI
58 08 el 0408 el_GR
59 09 en 0409 en_US 0809 en_GB 0c09 en_AU 1009 en_CA 1409 en_NZ
60 1809 en_IE 1c09 en_ZA 2009 en_JM 2409 en_GD 2809 en_BZ
61 2c09 en_TT 3009 en_ZW 3409 en_PH
62 0a es 040a es_ES 080a es_MX 0c0a es_ES@modern 100a es_GT 140a es_CR
63 180a es_PA 1c0a es_DO 200a es_VE 240a es_CO 280a es_PE
64 2c0a es_AR 300a es_EC 340a es_CL 380a es_UY 3c0a es_PY
65 400a es_BO 440a es_SV 480a es_HN 4c0a es_NI 500a es_PR
66 0b fi 040b fi_FI
67 0c fr 040c fr_FR 080c fr_BE 0c0c fr_CA 100c fr_CH 140c fr_LU
68 180c fr_MC
69 0d he 040d he_IL
70 0e hu 040e hu_HU
71 0f is 040f is_IS
72 10 it 0410 it_IT 0810 it_CH
73 11 ja 0411 ja_JP
74 12 ko 0412 ko_KR
75 13 nl 0413 nl_NL 0813 nl_BE
76 14 no 0414 no_NO 0814 nn_NO
77 15 pl 0415 pl_PL
78 16 pt 0416 pt_BR 0816 pt_PT
79 17 rm 0417 rm_CH
80 18 ro 0418 ro_RO 0818 ro_MO
81 19 ru 0819 ru_MO
82 1a hr 041a hr_HR 081a sr_YU 0c1a sr_YU@cyrillic
83 1b sk 041b sk_SK
84 1c sq 041c sq_AL
85 1d sv 041d sv_SE 081d sv_FI
86 1e th 041e th_TH
87 1f tr 041f tr_TR
88 20 ur 0420 ur_PK 0820 ur_IN
89 21 id 0421 id_ID
90 22 uk 0422 uk_UA
91 23 be 0423 be_BY
92 24 sl 0424 sl_SI
93 25 et 0425 et_EE
94 26 lv 0426 lv_LV
95 27 lt 0427 lt_LT
96 28 tg 0428 tg_TJ
97 29 fa 0429 fa_IR
98 2a vi 042a vi_VN
99 2b hy 042b hy_AM
100 2c az 042c az_AZ@latin 082c az_AZ@cyrillic
101 2d eu
102 2e wen 042e wen_DE
103 2f mk 042f mk_MK
104 30 bnt 0430 bnt_TZ
105 31 ts 0431 ts_ZA
106 32 tn
107 33 ven 0433 ven_ZA
108 34 xh 0434 xh_ZA
109 35 zu 0435 zu_ZA
110 36 af 0436 af_ZA
111 37 ka 0437 ka_GE
112 38 fo 0438 fo_FO
113 39 hi 0439 hi_IN
114 3a mt 043a mt_MT
115 3b se 043b se_NO
116 043c gd_UK 083c ga_IE
117 3d yi 043d yi_IL
118 3e ms 043e ms_MY 083e ms_BN
119 3f kk 043f kk_KZ
120 40 ky 0440 ky_KG
121 41 sw 0441 sw_KE
122 42 tk 0442 tk_TM
123 43 uz 0443 uz_UZ@latin 0843 uz_UZ@cyrillic
124 44 tt 0444 tt_RU
125 45 bn 0445 bn_IN
126 46 pa 0446 pa_IN
127 47 gu 0447 gu_IN
128 48 or 0448 or_IN
129 49 ta
130 4a te 044a te_IN
131 4b kn 044b kn_IN
132 4c ml 044c ml_IN
133 4d as 044d as_IN
134 4e mr 044e mr_IN
135 4f sa 044f sa_IN
136 50 mn
137 51 bo 0451 bo_CN
138 52 cy 0452 cy_GB
139 53 km 0453 km_KH
140 54 lo 0454 lo_LA
141 55 my 0455 my_MM
142 56 gl 0456 gl_ES
143 57 kok 0457 kok_IN
144 58 mni 0458 mni_IN
145 59 sd
146 5a syr 045a syr_TR
147 5b si 045b si_LK
148 5c chr 045c chr_US
149 5d iu 045d iu_CA
150 5e am 045e am_ET
151 5f ber 045f ber_MA
152 60 ks 0460 ks_PK 0860 ks_IN
153 61 ne 0461 ne_NP 0861 ne_IN
154 62 fy 0462 fy_NL
155 63 ps
156 64 tl 0464 tl_PH
157 65 div 0465 div_MV
158 66 bin 0466 bin_NG
159 67 ful 0467 ful_NG
160 68 ha 0468 ha_NG
161 69 nic 0469 nic_NG
162 6a yo 046a yo_NG
163 70 ibo 0470 ibo_NG
164 71 kau 0471 kau_NG
165 72 om 0472 om_ET
166 73 ti 0473 ti_ET
167 74 gn 0474 gn_PY
168 75 cpe 0475 cpe_US
169 76 la 0476 la_VA
170 77 so 0477 so_SO
171 78 sit 0478 sit_CN
172 79 pap 0479 pap_AN
173 }]
174 }
175 }
176
177 # msgcat::mc --
178 #
179 # Find the translation for the given string based on the current
180 # locale setting. Check the local namespace first, then look in each
181 # parent namespace until the source is found. If additional args are
182 # specified, use the format command to work them into the translated
183 # string.
184 # If no catalog item is found, mcunknown is called in the caller frame
185 # and its result is returned.
186 #
187 # Arguments:
188 # src The string to translate.
189 # args Args to pass to the format command
190 #
191 # Results:
192 # Returns the translated string. Propagates errors thrown by the
193 # format command.
194
195 proc msgcat::mc {src args} {
196 # this may be replaced by:
197 # return [mcget -namespace [uplevel 1 [list ::namespace current]] --\
198 # $src {*}$args]
199
200 # Check for the src in each namespace starting from the local and
201 # ending in the global.
202
203 variable Msgs
204 variable Loclist
205
206 set ns [uplevel 1 [list ::namespace current]]
207 set loclist [PackagePreferences $ns]
208
209 set nscur $ns
210 while {$nscur != ""} {
211 foreach loc $loclist {
212 if {[dict exists $Msgs $nscur $loc $src]} {
213 return [DefaultUnknown "" [dict get $Msgs $nscur $loc $src]\
214 {*}$args]
215 }
216 }
217 set nscur [namespace parent $nscur]
218 }
219 # call package local or default unknown command
220 set args [linsert $args 0 [lindex $loclist 0] $src]
221 switch -exact -- [Invoke unknowncmd $args $ns result 1] {
222 0 { return [uplevel 1 [linsert $args 0 [namespace origin mcunknown]]] }
223 1 { return [DefaultUnknown {*}$args] }
224 default { return $result }
225 }
226 }
227
228 # msgcat::mcexists --
229 #
230 # Check if a catalog item is set or if mc would invoke mcunknown.
231 #
232 # Arguments:
233 # -exactnamespace Only check the exact namespace and no
234 # parent namespaces
235 # -exactlocale Only check the exact locale and not all members
236 # of the preferences list
237 # src Message catalog key
238 #
239 # Results:
240 # true if an adequate catalog key was found
241
242 proc msgcat::mcexists {args} {
243
244 variable Msgs
245 variable Loclist
246 variable PackageConfig
247
248 set ns [uplevel 1 [list ::namespace current]]
249 set loclist [PackagePreferences $ns]
250
251 while {[llength $args] != 1} {
252 set args [lassign $args option]
253 switch -glob -- $option {
254 -exactnamespace { set exactnamespace 1 }
255 -exactlocale { set loclist [lrange $loclist 0 0] }
256 -* { return -code error "unknown option \"$option\"" }
257 default {
258 return -code error "wrong # args: should be\
259 \"[lindex [info level 0] 0] ?-exactnamespace?\
260 ?-exactlocale? src\""
261 }
262 }
263 }
264 set src [lindex $args 0]
265
266 while {$ns ne ""} {
267 foreach loc $loclist {
268 if {[dict exists $Msgs $ns $loc $src]} {
269 return 1
270 }
271 }
272 if {[info exists exactnamespace]} {return 0}
273 set ns [namespace parent $ns]
274 }
275 return 0
276 }
277
278 # msgcat::mclocale --
279 #
280 # Query or set the current locale.
281 #
282 # Arguments:
283 # newLocale (Optional) The new locale string. Locale strings
284 # should be composed of one or more sublocale parts
285 # separated by underscores (e.g. en_US).
286 #
287 # Results:
288 # Returns the normalized set locale.
289
290 proc msgcat::mclocale {args} {
291 variable Loclist
292 variable LoadedLocales
293 set len [llength $args]
294
295 if {$len > 1} {
296 return -code error "wrong # args: should be\
297 \"[lindex [info level 0] 0] ?newLocale?\""
298 }
299
300 if {$len == 1} {
301 set newLocale [string tolower [lindex $args 0]]
302 if {$newLocale ne [file tail $newLocale]} {
303 return -code error "invalid newLocale value \"$newLocale\":\
304 could be path to unsafe code."
305 }
306 if {[lindex $Loclist 0] ne $newLocale} {
307 set Loclist [GetPreferences $newLocale]
308
309 # locale not loaded jet
310 LoadAll $Loclist
311 # Invoke callback
312 Invoke changecmd $Loclist
313 }
314 }
315 return [lindex $Loclist 0]
316 }
317
318 # msgcat::GetPreferences --
319 #
320 # Get list of locales from a locale.
321 # The first element is always the lowercase locale.
322 # Other elements have one component separated by "_" less.
323 # Multiple "_" are seen as one separator: de__ch_spec de__ch de {}
324 #
325 # Arguments:
326 # Locale.
327 #
328 # Results:
329 # Locale list
330
331 proc msgcat::GetPreferences {locale} {
332 set locale [string tolower $locale]
333 set loclist [list $locale]
334 while {-1 !=[set pos [string last "_" $locale]]} {
335 set locale [string range $locale 0 $pos-1]
336 if { "_" ne [string index $locale end] } {
337 lappend loclist $locale
338 }
339 }
340 if {"" ne [lindex $loclist end]} {
341 lappend loclist {}
342 }
343 return $loclist
344 }
345
346 # msgcat::mcpreferences --
347 #
348 # Fetch the list of locales used to look up strings, ordered from
349 # most preferred to least preferred.
350 #
351 # Arguments:
352 # None.
353 #
354 # Results:
355 # Returns an ordered list of the locales preferred by the user.
356
357 proc msgcat::mcpreferences {} {
358 variable Loclist
359 return $Loclist
360 }
361
362 # msgcat::mcloadedlocales --
363 #
364 # Get or change the list of currently loaded default locales
365 #
366 # The following subcommands are available:
367 # loaded
368 # Get the current list of loaded locales
369 # clear
370 # Remove all loaded locales not present in mcpreferences.
371 #
372 # Arguments:
373 # subcommand One of loaded or clear
374 #
375 # Results:
376 # Empty string, if not stated differently for the subcommand
377
378 proc msgcat::mcloadedlocales {subcommand} {
379 variable Loclist
380 variable LoadedLocales
381 variable Msgs
382 variable PackageConfig
383 switch -exact -- $subcommand {
384 clear {
385 # Remove all locales not contained in Loclist
386 # skip any packages with package locale
387 set LoadedLocales $Loclist
388 foreach ns [dict keys $Msgs] {
389 if {![dict exists $PackageConfig loclist $ns]} {
390 foreach locale [dict keys [dict get $Msgs $ns]] {
391 if {$locale ni $Loclist} {
392 dict unset Msgs $ns $locale
393 }
394 }
395 }
396 }
397 }
398 loaded { return $LoadedLocales }
399 default {
400 return -code error "unknown subcommand \"$subcommand\": must be\
401 clear, or loaded"
402 }
403 }
404 return
405 }
406
407 # msgcat::mcpackagelocale --
408 #
409 # Get or change the package locale of the calling package.
410 #
411 # The following subcommands are available:
412 # set
413 # Set a package locale.
414 # This may load message catalog files and may clear message catalog
415 # items, if the former locale was the default locale.
416 # Returns the normalized set locale.
417 # The default locale is taken, if locale is not given.
418 # get
419 # Get the locale valid for this package.
420 # isset
421 # Returns true, if a package locale is set
422 # unset
423 # Unset the package locale and activate the default locale.
424 # This loads message catalog file which where missing in the package
425 # locale.
426 # preferences
427 # Return locale preference list valid for the package.
428 # loaded
429 # Return loaded locale list valid for the current package.
430 # clear
431 # If the current package has a package locale, remove all package
432 # locales not containes in package mcpreferences.
433 # It is an error to call this without a package locale set.
434 #
435 # The subcommands get, preferences and loaded return the corresponding
436 # default data, if no package locale is set.
437 #
438 # Arguments:
439 # subcommand see list above
440 # locale package locale (only set subcommand)
441 #
442 # Results:
443 # Empty string, if not stated differently for the subcommand
444
445 proc msgcat::mcpackagelocale {subcommand {locale ""}} {
446 # todo: implement using an ensemble
447 variable Loclist
448 variable LoadedLocales
449 variable Msgs
450 variable PackageConfig
451 # Check option
452 # check if required item is exactly provided
453 if {[llength [info level 0]] == 2} {
454 # locale not given
455 unset locale
456 } else {
457 # locale given
458 if {$subcommand in
459 {"get" "isset" "unset" "preferences" "loaded" "clear"} } {
460 return -code error "wrong # args: should be\
461 \"[lrange [info level 0] 0 1]\""
462 }
463 set locale [string tolower $locale]
464 }
465 set ns [uplevel 1 {::namespace current}]
466
467 switch -exact -- $subcommand {
468 get { return [lindex [PackagePreferences $ns] 0] }
469 preferences { return [PackagePreferences $ns] }
470 loaded { return [PackageLocales $ns] }
471 present { return [expr {$locale in [PackageLocales $ns]} ]}
472 isset { return [dict exists $PackageConfig loclist $ns] }
473 set { # set a package locale or add a package locale
474
475 # Copy the default locale if no package locale set so far
476 if {![dict exists $PackageConfig loclist $ns]} {
477 dict set PackageConfig loclist $ns $Loclist
478 dict set PackageConfig loadedlocales $ns $LoadedLocales
479 }
480
481 # Check if changed
482 set loclist [dict get $PackageConfig loclist $ns]
483 if {! [info exists locale] || $locale eq [lindex $loclist 0] } {
484 return [lindex $loclist 0]
485 }
486
487 # Change loclist
488 set loclist [GetPreferences $locale]
489 set locale [lindex $loclist 0]
490 dict set PackageConfig loclist $ns $loclist
491
492 # load eventual missing locales
493 set loadedLocales [dict get $PackageConfig loadedlocales $ns]
494 if {$locale in $loadedLocales} { return $locale }
495 set loadLocales [ListComplement $loadedLocales $loclist]
496 dict set PackageConfig loadedlocales $ns\
497 [concat $loadedLocales $loadLocales]
498 Load $ns $loadLocales
499 return $locale
500 }
501 clear { # Remove all locales not contained in Loclist
502 if {![dict exists $PackageConfig loclist $ns]} {
503 return -code error "clear only when package locale set"
504 }
505 set loclist [dict get $PackageConfig loclist $ns]
506 dict set PackageConfig loadedlocales $ns $loclist
507 if {[dict exists $Msgs $ns]} {
508 foreach locale [dict keys [dict get $Msgs $ns]] {
509 if {$locale ni $loclist} {
510 dict unset Msgs $ns $locale
511 }
512 }
513 }
514 }
515 unset { # unset package locale and restore default locales
516
517 if { ![dict exists $PackageConfig loclist $ns] } { return }
518
519 # unset package locale
520 set loadLocales [ListComplement\
521 [dict get $PackageConfig loadedlocales $ns] $LoadedLocales]
522 dict unset PackageConfig loadedlocales $ns
523 dict unset PackageConfig loclist $ns
524
525 # unset keys not in global loaded locales
526 if {[dict exists $Msgs $ns]} {
527 foreach locale [dict keys [dict get $Msgs $ns]] {
528 if {$locale ni $LoadedLocales} {
529 dict unset Msgs $ns $locale
530 }
531 }
532 }
533
534 # Add missing locales
535 Load $ns $loadLocales
536 }
537 default {
538 return -code error "unknown subcommand \"$subcommand\": must be\
539 clear, get, isset, loaded, present, set, or unset"
540 }
541 }
542 return
543 }
544
545 # msgcat::mcforgetpackage --
546 #
547 # Remove any data of the calling package from msgcat
548 #
549
550 proc msgcat::mcforgetpackage {} {
551 # todo: this may be implemented using an ensemble
552 variable PackageConfig
553 variable Msgs
554 set ns [uplevel 1 {::namespace current}]
555 # Remove MC items
556 dict unset Msgs $ns
557 # Remove config items
558 foreach key [dict keys $PackageConfig] {
559 dict unset PackageConfig $key $ns
560 }
561 return
562 }
563
564 # msgcat::mcpackageconfig --
565 #
566 # Get or modify the per caller namespace (e.g. packages) config options.
567 #
568 # Available subcommands are:
569 #
570 # get get the current value or an error if not set.
571 # isset return true, if the option is set
572 # set set the value (see also distinct option).
573 # Returns the number of loaded message files.
574 # unset Clear option. return "".
575 #
576 # Available options are:
577 #
578 # mcfolder
579 # The message catalog folder of the package.
580 # This is automatically set by mcload.
581 # If the value is changed using the set subcommand, an eventual
582 # loadcmd is invoked and all message files of the package locale are
583 # loaded.
584 #
585 # loadcmd
586 # The command gets executed before a message file would be
587 # sourced for this module.
588 # The command is invoked with the expanded locale list to load.
589 # The command is not invoked if the registering package namespace
590 # is not present.
591 # This callback might also be used as an alternative to message
592 # files.
593 # If the value is changed using the set subcommand, the callback is
594 # directly invoked with the current file locale list. No file load is
595 # executed.
596 #
597 # changecmd
598 # The command is invoked, after an executed locale change.
599 # Appended argument is expanded mcpreferences.
600 #
601 # unknowncmd
602 # Use a package locale mcunknown procedure instead the global one.
603 # The appended arguments are identical to mcunknown.
604 # A default unknown handler is used if set to the empty string.
605 # This consists in returning the key if no arguments are given.
606 # With given arguments, format is used to process the arguments.
607 #
608 # Arguments:
609 # subcommand Operation on the package
610 # option The package option to get or set.
611 # ?value? Eventual value for the subcommand
612 #
613 # Results:
614 # Depends on the subcommand and option and is described there
615
616 proc msgcat::mcpackageconfig {subcommand option {value ""}} {
617 variable PackageConfig
618 # get namespace
619 set ns [uplevel 1 {::namespace current}]
620
621 if {$option ni {"mcfolder" "loadcmd" "changecmd" "unknowncmd"}} {
622 return -code error "bad option \"$option\": must be mcfolder, loadcmd,\
623 changecmd, or unknowncmd"
624 }
625
626 # check if value argument is exactly provided
627 if {[llength [info level 0]] == 4 } {
628 # value provided
629 if {$subcommand in {"get" "isset" "unset"}} {
630 return -code error "wrong # args: should be\
631 \"[lrange [info level 0] 0 2] value\""
632 }
633 } elseif {$subcommand eq "set"} {
634 return -code error\
635 "wrong # args: should be \"[lrange [info level 0] 0 2]\""
636 }
637
638 # Execute subcommands
639 switch -exact -- $subcommand {
640 get { # Operation get return current value
641 if {![dict exists $PackageConfig $option $ns]} {
642 return -code error "package option \"$option\" not set"
643 }
644 return [dict get $PackageConfig $option $ns]
645 }
646 isset { return [dict exists $PackageConfig $option $ns] }
647 unset { dict unset PackageConfig $option $ns }
648 set { # Set option
649
650 if {$option eq "mcfolder"} {
651 set value [file normalize $value]
652 }
653 # Check if changed
654 if { [dict exists $PackageConfig $option $ns]
655 && $value eq [dict get $PackageConfig $option $ns] } {
656 return 0
657 }
658
659 # set new value
660 dict set PackageConfig $option $ns $value
661
662 # Reload pending message catalogs
663 switch -exact -- $option {
664 mcfolder { return [Load $ns [PackageLocales $ns]] }
665 loadcmd { return [Load $ns [PackageLocales $ns] 1] }
666 }
667 return 0
668 }
669 default {
670 return -code error "unknown subcommand \"$subcommand\":\
671 must be get, isset, set, or unset"
672 }
673 }
674 return
675 }
676
677 # msgcat::PackagePreferences --
678 #
679 # Return eventual present package preferences or the default list if not
680 # present.
681 #
682 # Arguments:
683 # ns Package namespace
684 #
685 # Results:
686 # locale list
687
688 proc msgcat::PackagePreferences {ns} {
689 variable PackageConfig
690 if {[dict exists $PackageConfig loclist $ns]} {
691 return [dict get $PackageConfig loclist $ns]
692 }
693 variable Loclist
694 return $Loclist
695 }
696
697 # msgcat::PackageLocales --
698 #
699 # Return eventual present package locales or the default list if not
700 # present.
701 #
702 # Arguments:
703 # ns Package namespace
704 #
705 # Results:
706 # locale list
707
708 proc msgcat::PackageLocales {ns} {
709 variable PackageConfig
710 if {[dict exists $PackageConfig loadedlocales $ns]} {
711 return [dict get $PackageConfig loadedlocales $ns]
712 }
713 variable LoadedLocales
714 return $LoadedLocales
715 }
716
717 # msgcat::ListComplement --
718 #
719 # Build the complement of two lists.
720 # Return a list with all elements in list2 but not in list1.
721 # Optionally return the intersection.
722 #
723 # Arguments:
724 # list1 excluded list
725 # list2 included list
726 # inlistname If not "", write in this variable the intersection list
727 #
728 # Results:
729 # list with all elements in list2 but not in list1
730
731 proc msgcat::ListComplement {list1 list2 {inlistname ""}} {
732 if {"" ne $inlistname} {
733 upvar 1 $inlistname inlist
734 }
735 set inlist {}
736 set outlist {}
737 foreach item $list2 {
738 if {$item in $list1} {
739 lappend inlist $item
740 } else {
741 lappend outlist $item
742 }
743 }
744 return $outlist
745 }
746
747 # msgcat::mcload --
748 #
749 # Attempt to load message catalogs for each locale in the
750 # preference list from the specified directory.
751 #
752 # Arguments:
753 # langdir The directory to search.
754 #
755 # Results:
756 # Returns the number of message catalogs that were loaded.
757
758 proc msgcat::mcload {langdir} {
759 return [uplevel 1 [list\
760 [namespace origin mcpackageconfig] set mcfolder $langdir]]
761 }
762
763 # msgcat::LoadAll --
764 #
765 # Load a list of locales for all packages not having a package locale
766 # list.
767 #
768 # Arguments:
769 # langdir The directory to search.
770 #
771 # Results:
772 # Returns the number of message catalogs that were loaded.
773
774 proc msgcat::LoadAll {locales} {
775 variable PackageConfig
776 variable LoadedLocales
777 if {0 == [llength $locales]} { return {} }
778 # filter jet unloaded locales
779 set locales [ListComplement $LoadedLocales $locales]
780 if {0 == [llength $locales]} { return {} }
781 lappend LoadedLocales {*}$locales
782
783 set packages [lsort -unique [concat\
784 [dict keys [dict get $PackageConfig loadcmd]]\
785 [dict keys [dict get $PackageConfig mcfolder]]]]
786 foreach ns $packages {
787 if {! [dict exists $PackageConfig loclist $ns] } {
788 Load $ns $locales
789 }
790 }
791 return $locales
792 }
793
794 # msgcat::Load --
795 #
796 # Invoke message load callback and load message catalog files.
797 #
798 # Arguments:
799 # ns Namespace (equal package) to load the message catalog.
800 # locales List of locales to load.
801 # callbackonly true if only callback should be invoked
802 #
803 # Results:
804 # Returns the number of message catalogs that were loaded.
805
806 proc msgcat::Load {ns locales {callbackonly 0}} {
807 variable FileLocale
808 variable PackageConfig
809 variable LoadedLocals
810
811 if {0 == [llength $locales]} { return 0 }
812
813 # Invoke callback
814 Invoke loadcmd $locales $ns
815
816 if {$callbackonly || ![dict exists $PackageConfig mcfolder $ns]} {
817 return 0
818 }
819
820 # Invoke file load
821 set langdir [dict get $PackageConfig mcfolder $ns]
822
823 # Save the file locale if we are recursively called
824 if {[info exists FileLocale]} {
825 set nestedFileLocale $FileLocale
826 }
827 set x 0
828 foreach p $locales {
829 if {$p eq {}} {
830 set p ROOT
831 }
832 set langfile [file join $langdir $p.msg]
833 if {[file exists $langfile]} {
834 incr x
835 set FileLocale [string tolower\
836 [file tail [file rootname $langfile]]]
837 if {"root" eq $FileLocale} {
838 set FileLocale ""
839 }
840 namespace inscope $ns [list ::source -encoding utf-8 $langfile]
841 unset FileLocale
842 }
843 }
844 if {[info exists nestedFileLocale]} {
845 set FileLocale $nestedFileLocale
846 }
847 return $x
848 }
849
850 # msgcat::Invoke --
851 #
852 # Invoke a set of registered callbacks.
853 # The callback is only invoked, if its registered namespace exists.
854 #
855 # Arguments:
856 # index Index into PackageConfig to get callback command
857 # arglist parameters to the callback invocation
858 # ns (Optional) package to call.
859 # If not given or empty, check all registered packages.
860 # resultname Variable to save the callback result of the last called
861 # callback to. May be set to "" to discard the result.
862 # failerror (0) Fail on error if true. Otherwise call bgerror.
863 #
864 # Results:
865 # Possible values:
866 # - 0: no valid command registered
867 # - 1: registered command was the empty string
868 # - 2: registered command called, resultname is set
869 # - 3: registered command failed
870 # If multiple commands are called, the maximum of all results is returned.
871
872 proc msgcat::Invoke {index arglist {ns ""} {resultname ""} {failerror 0}} {
873 variable PackageConfig
874 variable Config
875 if {"" ne $resultname} {
876 upvar 1 $resultname result
877 }
878 if {"" eq $ns} {
879 set packageList [dict keys [dict get $PackageConfig $index]]
880 } else {
881 set packageList [list $ns]
882 }
883 set ret 0
884 foreach ns $packageList {
885 if {[dict exists $PackageConfig $index $ns] && [namespace exists $ns]} {
886 set cmd [dict get $PackageConfig $index $ns]
887 if {"" eq $cmd} {
888 if {$ret == 0} {set ret 1}
889 } else {
890 if {$failerror} {
891 set result [namespace inscope $ns $cmd {*}$arglist]
892 set ret 2
893 } elseif {1 == [catch {
894 set result [namespace inscope $ns $cmd {*}$arglist]
895 if {$ret < 2} {set ret 2}
896 } err derr]} {
897 after idle [concat [::interp bgerror ""]\
898 [list $err $derr]]
899 set ret 3
900 }
901 }
902 }
903 }
904 return $ret
905 }
906
907 # msgcat::mcset --
908 #
909 # Set the translation for a given string in a specified locale.
910 #
911 # Arguments:
912 # locale The locale to use.
913 # src The source string.
914 # dest (Optional) The translated string. If omitted,
915 # the source string is used.
916 #
917 # Results:
918 # Returns the new locale.
919
920 proc msgcat::mcset {locale src {dest ""}} {
921 variable Msgs
922 if {[llength [info level 0]] == 3} { ;# dest not specified
923 set dest $src
924 }
925
926 set ns [uplevel 1 [list ::namespace current]]
927
928 set locale [string tolower $locale]
929
930 dict set Msgs $ns $locale $src $dest
931 return $dest
932 }
933
934 # msgcat::mcflset --
935 #
936 # Set the translation for a given string in the current file locale.
937 #
938 # Arguments:
939 # src The source string.
940 # dest (Optional) The translated string. If omitted,
941 # the source string is used.
942 #
943 # Results:
944 # Returns the new locale.
945
946 proc msgcat::mcflset {src {dest ""}} {
947 variable FileLocale
948 variable Msgs
949
950 if {![info exists FileLocale]} {
951 return -code error "must only be used inside a message catalog loaded\
952 with ::msgcat::mcload"
953 }
954 return [uplevel 1 [list [namespace origin mcset] $FileLocale $src $dest]]
955 }
956
957 # msgcat::mcmset --
958 #
959 # Set the translation for multiple strings in a specified locale.
960 #
961 # Arguments:
962 # locale The locale to use.
963 # pairs One or more src/dest pairs (must be even length)
964 #
965 # Results:
966 # Returns the number of pairs processed
967
968 proc msgcat::mcmset {locale pairs} {
969 variable Msgs
970
971 set length [llength $pairs]
972 if {$length % 2} {
973 return -code error "bad translation list:\
974 should be \"[lindex [info level 0] 0] locale {src dest ...}\""
975 }
976
977 set locale [string tolower $locale]
978 set ns [uplevel 1 [list ::namespace current]]
979
980 foreach {src dest} $pairs {
981 dict set Msgs $ns $locale $src $dest
982 }
983
984 return [expr {$length / 2}]
985 }
986
987 # msgcat::mcflmset --
988 #
989 # Set the translation for multiple strings in the mc file locale.
990 #
991 # Arguments:
992 # pairs One or more src/dest pairs (must be even length)
993 #
994 # Results:
995 # Returns the number of pairs processed
996
997 proc msgcat::mcflmset {pairs} {
998 variable FileLocale
999 variable Msgs
1000
1001 if {![info exists FileLocale]} {
1002 return -code error "must only be used inside a message catalog loaded\
1003 with ::msgcat::mcload"
1004 }
1005 return [uplevel 1 [list [namespace origin mcmset] $FileLocale $pairs]]
1006 }
1007
1008 # msgcat::mcunknown --
1009 #
1010 # This routine is called by msgcat::mc if a translation cannot
1011 # be found for a string and no unknowncmd is set for the current
1012 # package. This routine is intended to be replaced
1013 # by an application specific routine for error reporting
1014 # purposes. The default behavior is to return the source string.
1015 # If additional args are specified, the format command will be used
1016 # to work them into the translated string.
1017 #
1018 # Arguments:
1019 # locale The current locale.
1020 # src The string to be translated.
1021 # args Args to pass to the format command
1022 #
1023 # Results:
1024 # Returns the translated value.
1025
1026 proc msgcat::mcunknown {args} {
1027 return [uplevel 1 [list [namespace origin DefaultUnknown] {*}$args]]
1028 }
1029
1030 # msgcat::DefaultUnknown --
1031 #
1032 # This routine is called by msgcat::mc if a translation cannot
1033 # be found for a string in the following circumstances:
1034 # - Default global handler, if mcunknown is not redefined.
1035 # - Per package handler, if the package sets unknowncmd to the empty
1036 # string.
1037 # It returns the source string if the argument list is empty.
1038 # If additional args are specified, the format command will be used
1039 # to work them into the translated string.
1040 #
1041 # Arguments:
1042 # locale (unused) The current locale.
1043 # src The string to be translated.
1044 # args Args to pass to the format command
1045 #
1046 # Results:
1047 # Returns the translated value.
1048
1049 proc msgcat::DefaultUnknown {locale src args} {
1050 if {[llength $args]} {
1051 return [format $src {*}$args]
1052 } else {
1053 return $src
1054 }
1055 }
1056
1057 # msgcat::mcmax --
1058 #
1059 # Calculates the maximum length of the translated strings of the given
1060 # list.
1061 #
1062 # Arguments:
1063 # args strings to translate.
1064 #
1065 # Results:
1066 # Returns the length of the longest translated string.
1067
1068 proc msgcat::mcmax {args} {
1069 set max 0
1070 foreach string $args {
1071 set translated [uplevel 1 [list [namespace origin mc] $string]]
1072 set len [string length $translated]
1073 if {$len>$max} {
1074 set max $len
1075 }
1076 }
1077 return $max
1078 }
1079
1080 # Convert the locale values stored in environment variables to a form
1081 # suitable for passing to [mclocale]
1082 proc msgcat::ConvertLocale {value} {
1083 # Assume $value is of form: $language[_$territory][.$codeset][@modifier]
1084 # Convert to form: $language[_$territory][_$modifier]
1085 #
1086 # Comment out expanded RE version -- bugs alleged
1087 # regexp -expanded {
1088 # ^ # Match all the way to the beginning
1089 # ([^_.@]*) # Match "lanugage"; ends with _, ., or @
1090 # (_([^.@]*))? # Match (optional) "territory"; starts with _
1091 # ([.]([^@]*))? # Match (optional) "codeset"; starts with .
1092 # (@(.*))? # Match (optional) "modifier"; starts with @
1093 # $ # Match all the way to the end
1094 # } $value -> language _ territory _ codeset _ modifier
1095 if {![regexp {^([^_.@]+)(_([^.@]*))?([.]([^@]*))?(@(.*))?$} $value \
1096 -> language _ territory _ codeset _ modifier]} {
1097 return -code error "invalid locale '$value': empty language part"
1098 }
1099 set ret $language
1100 if {[string length $territory]} {
1101 append ret _$territory
1102 }
1103 if {[string length $modifier]} {
1104 append ret _$modifier
1105 }
1106 return $ret
1107 }
1108
1109 # Initialize the default locale
1110 proc msgcat::Init {} {
1111 global env
1112
1113 #
1114 # set default locale, try to get from environment
1115 #
1116 foreach varName {LC_ALL LC_MESSAGES LANG} {
1117 if {[info exists env($varName)] && ("" ne $env($varName))} {
1118 if {![catch {
1119 mclocale [ConvertLocale $env($varName)]
1120 }]} {
1121 return
1122 }
1123 }
1124 }
1125 #
1126 # On Darwin, fallback to current CFLocale identifier if available.
1127 #
1128 if {[info exists ::tcl::mac::locale] && $::tcl::mac::locale ne ""} {
1129 if {![catch {
1130 mclocale [ConvertLocale $::tcl::mac::locale]
1131 }]} {
1132 return
1133 }
1134 }
1135 #
1136 # The rest of this routine is special processing for Windows or
1137 # Cygwin. All other platforms, get out now.
1138 #
1139 if {([info sharedlibextension] ne ".dll")
1140 || [catch {package require registry}]} {
1141 mclocale C
1142 return
1143 }
1144 #
1145 # On Windows or Cygwin, try to set locale depending on registry
1146 # settings, or fall back on locale of "C".
1147 #
1148
1149 # On Vista and later:
1150 # HCU/Control Panel/Desktop : PreferredUILanguages is for language packs,
1151 # HCU/Control Pannel/International : localName is the default locale.
1152 #
1153 # They contain the local string as RFC5646, composed of:
1154 # [a-z]{2,3} : language
1155 # -[a-z]{4} : script (optional, translated by table Latn->latin)
1156 # -[a-z]{2}|[0-9]{3} : territory (optional, numerical region codes not used)
1157 # (-.*)* : variant, extension, private use (optional, not used)
1158 # Those are translated to local strings.
1159 # Examples: de-CH -> de_ch, sr-Latn-CS -> sr_cs@latin, es-419 -> es
1160 #
1161 foreach key {{HKEY_CURRENT_USER\Control Panel\Desktop} {HKEY_CURRENT_USER\Control Panel\International}}\
1162 value {PreferredUILanguages localeName} {
1163 if {![catch {registry get $key $value} localeName]
1164 && [regexp {^([a-z]{2,3})(?:-([a-z]{4}))?(?:-([a-z]{2}))?(?:-.+)?$}\
1165 [string tolower $localeName] match locale script territory]} {
1166 if {"" ne $territory} {
1167 append locale _ $territory
1168 }
1169 set modifierDict [dict create latn latin cyrl cyrillic]
1170 if {[dict exists $modifierDict $script]} {
1171 append locale @ [dict get $modifierDict $script]
1172 }
1173 if {![catch {mclocale [ConvertLocale $locale]}]} {
1174 return
1175 }
1176 }
1177 }
1178
1179 # then check value locale which contains a numerical language ID
1180 if {[catch {
1181 set locale [registry get $key "locale"]
1182 }]} {
1183 mclocale C
1184 return
1185 }
1186 #
1187 # Keep trying to match against smaller and smaller suffixes
1188 # of the registry value, since the latter hexadigits appear
1189 # to determine general language and earlier hexadigits determine
1190 # more precise information, such as territory. For example,
1191 # 0409 - English - United States
1192 # 0809 - English - United Kingdom
1193 # Add more translations to the WinRegToISO639 array above.
1194 #
1195 variable WinRegToISO639
1196 set locale [string tolower $locale]
1197 while {[string length $locale]} {
1198 if {![catch {
1199 mclocale [ConvertLocale [dict get $WinRegToISO639 $locale]]
1200 }]} {
1201 return
1202 }
1203 set locale [string range $locale 1 end]
1204 }
1205 #
1206 # No translation known. Fall back on "C" locale
1207 #
1208 mclocale C
1209 }
1210 msgcat::Init