home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _aaa230225ef36981674c640524482b08 < prev    next >
Text File  |  2004-06-01  |  18KB  |  563 lines

  1.  
  2. # Time-stamp: "2004-01-19 15:11:14 AST"
  3.  
  4. require 5;
  5. package Locale::Maketext;
  6. use strict;
  7. use vars qw( @ISA $VERSION $MATCH_SUPERS $USING_LANGUAGE_TAGS
  8.              $USE_LITERALS $MATCH_SUPERS_TIGHTLY);
  9. use Carp ();
  10. use I18N::LangTags 0.21 ();
  11.  
  12. #--------------------------------------------------------------------------
  13.  
  14. BEGIN { unless(defined &DEBUG) { *DEBUG = sub () {0} } }
  15.  # define the constant 'DEBUG' at compile-time
  16.  
  17. $VERSION = "1.08";
  18. @ISA = ();
  19.  
  20. $MATCH_SUPERS = 1;
  21. $MATCH_SUPERS_TIGHTLY = 1;
  22. $USING_LANGUAGE_TAGS  = 1;
  23.  # Turning this off is somewhat of a security risk in that little or no
  24.  # checking will be done on the legality of tokens passed to the
  25.  # eval("use $module_name") in _try_use.  If you turn this off, you have
  26.  # to do your own taint checking.
  27.  
  28. $USE_LITERALS = 1 unless defined $USE_LITERALS;
  29.  # a hint for compiling bracket-notation things.
  30.  
  31. my %isa_scan = ();
  32.  
  33. ###########################################################################
  34.  
  35. sub quant {
  36.   my($handle, $num, @forms) = @_;
  37.  
  38.   return $num if @forms == 0; # what should this mean?
  39.   return $forms[2] if @forms > 2 and $num == 0; # special zeroth case
  40.  
  41.   # Normal case:
  42.   # Note that the formatting of $num is preserved.
  43.   return( $handle->numf($num) . ' ' . $handle->numerate($num, @forms) );
  44.    # Most human languages put the number phrase before the qualified phrase.
  45. }
  46.  
  47.  
  48. sub numerate {
  49.  # return this lexical item in a form appropriate to this number
  50.   my($handle, $num, @forms) = @_;
  51.   my $s = ($num == 1);
  52.  
  53.   return '' unless @forms;
  54.   if(@forms == 1) { # only the headword form specified
  55.     return $s ? $forms[0] : ($forms[0] . 's'); # very cheap hack.
  56.   } else { # sing and plural were specified
  57.     return $s ? $forms[0] : $forms[1];
  58.   }
  59. }
  60.  
  61. #--------------------------------------------------------------------------
  62.  
  63. sub numf {
  64.   my($handle, $num) = @_[0,1];
  65.   if($num < 10_000_000_000 and $num > -10_000_000_000 and $num == int($num)) {
  66.     $num += 0;  # Just use normal integer stringification.
  67.          # Specifically, don't let %G turn ten million into 1E+007
  68.   } else {
  69.     $num = CORE::sprintf("%G", $num);
  70.      # "CORE::" is there to avoid confusion with the above sub sprintf.
  71.   }
  72.   while( $num =~ s/^([-+]?\d+)(\d{3})/$1,$2/s ) {1}  # right from perlfaq5
  73.    # The initial \d+ gobbles as many digits as it can, and then we
  74.    #  backtrack so it un-eats the rightmost three, and then we
  75.    #  insert the comma there.
  76.  
  77.   $num =~ tr<.,><,.> if ref($handle) and $handle->{'numf_comma'};
  78.    # This is just a lame hack instead of using Number::Format
  79.   return $num;
  80. }
  81.  
  82. sub sprintf {
  83.   no integer;
  84.   my($handle, $format, @params) = @_;
  85.   return CORE::sprintf($format, @params);
  86.     # "CORE::" is there to avoid confusion with myself!
  87. }
  88.  
  89. #=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
  90.  
  91. use integer; # vroom vroom... applies to the whole rest of the module
  92.  
  93. sub language_tag {
  94.   my $it = ref($_[0]) || $_[0];
  95.   return undef unless $it =~ m/([^':]+)(?:::)?$/s;
  96.   $it = lc($1);
  97.   $it =~ tr<_><->;
  98.   return $it;
  99. }
  100.  
  101. sub encoding {
  102.   my $it = $_[0];
  103.   return(
  104.    (ref($it) && $it->{'encoding'})
  105.    || "iso-8859-1"   # Latin-1
  106.   );
  107.  
  108. #--------------------------------------------------------------------------
  109.  
  110. sub fallback_languages { return('i-default', 'en', 'en-US') }
  111.  
  112. sub fallback_language_classes { return () }
  113.  
  114. #--------------------------------------------------------------------------
  115.  
  116. sub fail_with { # an actual attribute method!
  117.   my($handle, @params) = @_;
  118.   return unless ref($handle);
  119.   $handle->{'fail'} = $params[0] if @params;
  120.   return $handle->{'fail'};
  121. }
  122.  
  123. #--------------------------------------------------------------------------
  124.  
  125. sub failure_handler_auto {
  126.   # Meant to be used like:
  127.   #  $handle->fail_with('failure_handler_auto')
  128.  
  129.   my($handle, $phrase, @params) = @_;
  130.   $handle->{'failure_lex'} ||= {};
  131.   my $lex = $handle->{'failure_lex'};
  132.  
  133.   my $value;
  134.   $lex->{$phrase} ||= ($value = $handle->_compile($phrase));
  135.  
  136.   # Dumbly copied from sub maketext:
  137.   {
  138.     local $SIG{'__DIE__'};
  139.     eval { $value = &$value($handle, @_) };
  140.   }
  141.   # If we make it here, there was an exception thrown in the
  142.   #  call to $value, and so scream:
  143.   if($@) {
  144.     my $err = $@;
  145.     # pretty up the error message
  146.     $err =~ s<\s+at\s+\(eval\s+\d+\)\s+line\s+(\d+)\.?\n?>
  147.              <\n in bracket code [compiled line $1],>s;
  148.     #$err =~ s/\n?$/\n/s;
  149.     Carp::croak "Error in maketexting \"$phrase\":\n$err as used";
  150.     # Rather unexpected, but suppose that the sub tried calling
  151.     # a method that didn't exist.
  152.   } else {
  153.     return $value;
  154.   }
  155. }
  156.  
  157. #==========================================================================
  158.  
  159. sub new {
  160.   # Nothing fancy!
  161.   my $class = ref($_[0]) || $_[0];
  162.   my $handle = bless {}, $class;
  163.   $handle->init;
  164.   return $handle;
  165. }
  166.  
  167. sub init { return } # no-op
  168.  
  169. ###########################################################################
  170.  
  171. sub maketext {
  172.   # Remember, this can fail.  Failure is controllable many ways.
  173.   Carp::croak "maketext requires at least one parameter" unless @_ > 1;
  174.  
  175.   my($handle, $phrase) = splice(@_,0,2);
  176.  
  177.   # Look up the value:
  178.  
  179.   my $value;
  180.   foreach my $h_r (
  181.     @{  $isa_scan{ref($handle) || $handle} || $handle->_lex_refs  }
  182.   ) {
  183.     print "* Looking up \"$phrase\" in $h_r\n" if DEBUG;
  184.     if(exists $h_r->{$phrase}) {
  185.       print "  Found \"$phrase\" in $h_r\n" if DEBUG;
  186.       unless(ref($value = $h_r->{$phrase})) {
  187.         # Nonref means it's not yet compiled.  Compile and replace.
  188.         $value = $h_r->{$phrase} = $handle->_compile($value);
  189.       }
  190.       last;
  191.     } elsif($phrase !~ m/^_/s and $h_r->{'_AUTO'}) {
  192.       # it's an auto lex, and this is an autoable key!
  193.       print "  Automaking \"$phrase\" into $h_r\n" if DEBUG;
  194.       
  195.       $value = $h_r->{$phrase} = $handle->_compile($phrase);
  196.       last;
  197.     }
  198.     print "  Not found in $h_r, nor automakable\n" if DEBUG > 1;
  199.     # else keep looking
  200.   }
  201.  
  202.   unless(defined($value)) {
  203.     print "! Lookup of \"$phrase\" in/under ", ref($handle) || $handle,
  204.       " fails.\n" if DEBUG;
  205.     if(ref($handle) and $handle->{'fail'}) {
  206.       print "WARNING0: maketext fails looking for <$phrase>\n" if DEBUG;
  207.       my $fail;
  208.       if(ref($fail = $handle->{'fail'}) eq 'CODE') { # it's a sub reference
  209.         return &{$fail}($handle, $phrase, @_);
  210.          # If it ever returns, it should return a good value.
  211.       } else { # It's a method name
  212.         return $handle->$fail($phrase, @_);
  213.          # If it ever returns, it should return a good value.
  214.       }
  215.     } else {
  216.       # All we know how to do is this;
  217.       Carp::croak("maketext doesn't know how to say:\n$phrase\nas needed");
  218.     }
  219.   }
  220.  
  221.   return $$value if ref($value) eq 'SCALAR';
  222.   return $value unless ref($value) eq 'CODE';
  223.   
  224.   {
  225.     local $SIG{'__DIE__'};
  226.     eval { $value = &$value($handle, @_) };
  227.   }
  228.   # If we make it here, there was an exception thrown in the
  229.   #  call to $value, and so scream:
  230.   if($@) {
  231.     my $err = $@;
  232.     # pretty up the error message
  233.     $err =~ s<\s+at\s+\(eval\s+\d+\)\s+line\s+(\d+)\.?\n?>
  234.              <\n in bracket code [compiled line $1],>s;
  235.     #$err =~ s/\n?$/\n/s;
  236.     Carp::croak "Error in maketexting \"$phrase\":\n$err as used";
  237.     # Rather unexpected, but suppose that the sub tried calling
  238.     # a method that didn't exist.
  239.   } else {
  240.     return $value;
  241.   }
  242. }
  243.  
  244. ###########################################################################
  245.  
  246. sub get_handle {  # This is a constructor and, yes, it CAN FAIL.
  247.   # Its class argument has to be the base class for the current
  248.   # application's l10n files.
  249.  
  250.   my($base_class, @languages) = @_;
  251.   $base_class = ref($base_class) || $base_class;
  252.    # Complain if they use __PACKAGE__ as a project base class?
  253.  
  254.   @languages = $base_class->_ambient_langprefs() unless @languages;
  255.   @languages = $base_class->_langtag_munging(@languages);
  256.  
  257.   my %seen;
  258.   foreach my $module_name ( map { $base_class . "::" . $_ }  @languages ) {
  259.     next unless length $module_name; # sanity
  260.     next if $seen{$module_name}++        # Already been here, and it was no-go
  261.             || !&_try_use($module_name); # Try to use() it, but can't it.
  262.     return($module_name->new); # Make it!
  263.   }
  264.  
  265.   return undef; # Fail!
  266. }
  267.  
  268. ###########################################################################
  269.  
  270. sub _langtag_munging {
  271.   my($base_class, @languages) = @_;
  272.  
  273.   DEBUG and print "Lgs1: ", map("<$_>", @languages), "\n";
  274.  
  275.   if($USING_LANGUAGE_TAGS) {
  276.     @languages = map &I18N::LangTags::locale2language_tag($_), @languages;
  277.      # if it's a lg tag, fine, pass thru (untainted)
  278.      # if it's a locale ID, try converting to a lg tag (untainted),
  279.      # otherwise nix it.
  280.  
  281.     @languages = map {; $_, I18N::LangTags::alternate_language_tags($_) }
  282.                       @languages;    # catch alternation
  283.     DEBUG and print "Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  284.  
  285.     @languages     = $base_class->_add_supers( @languages );
  286.  
  287.     if( defined &I18N::LangTags::panic_languages ) {
  288.       push @languages, I18N::LangTags::panic_languages(@languages);
  289.       DEBUG and print "After adding panic languages:\n", 
  290.         " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  291.     }
  292.  
  293.     push @languages, $base_class->fallback_languages;
  294.      # You are free to override fallback_languages to return empty-list!
  295.     DEBUG and print "Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  296.  
  297.     @languages =  # final bit of processing:
  298.       map {
  299.         my $it = $_;  # copy
  300.         $it =~ tr<-A-Z><_a-z>; # lc, and turn - to _
  301.         $it =~ tr<_a-z0-9><>cd;  # remove all but a-z0-9_
  302.         $it;
  303.       } @languages
  304.     ;
  305.     DEBUG and print "Nearing end of munging:\n", 
  306.       " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  307.   } else {
  308.     DEBUG and print "Bypassing language-tags.\n", 
  309.       " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  310.   }
  311.  
  312.   DEBUG and print "Before adding fallback classes:\n", 
  313.     " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  314.  
  315.   push @languages, $base_class->fallback_language_classes;
  316.    # You are free to override that to return whatever.
  317.  
  318.   DEBUG and print "Finally:\n", 
  319.     " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  320.  
  321.   return @languages;
  322. }
  323.  
  324. ###########################################################################
  325.  
  326. sub _ambient_langprefs {
  327.   my $base_class = $_[0];
  328.   
  329.   return $base_class->_http_accept_langs
  330.    if length( $ENV{'REQUEST_METHOD'} || '' ); # I'm a CGI
  331.        # it's off in its own routine because it's complicated
  332.  
  333.   # Not running as a CGI: try to puzzle out from the environment
  334.   my @languages;
  335.  
  336.   if(length( $ENV{'LANG'} || '' )) {
  337.     push @languages, split m/[,:]/, $ENV{'LANG'};
  338.      # LANG can be only /one/ locale as far as I know, but what the hey.
  339.   }
  340.  
  341.   if(length( $ENV{'LANGUAGE'} || '' )) {
  342.     push @languages, split m/[,:]/, $ENV{'LANGUAGE'};
  343.   }
  344.  
  345.   print "Noting ENV LANG ", join(',', @languages),"\n" if DEBUG;
  346.   # Those are really locale IDs, but they get xlated a few lines down.
  347.   
  348.   if(&_try_use('Win32::Locale')) {
  349.     # If we have that module installed...
  350.     push @languages, Win32::Locale::get_language() || ''
  351.      if defined &Win32::Locale::get_language;
  352.   }
  353.  
  354.   return @languages;
  355. }
  356.  
  357. ###########################################################################
  358.  
  359. sub _add_supers {
  360.   my($base_class, @languages) = @_;
  361.  
  362.   if(!$MATCH_SUPERS) {
  363.     # Nothing
  364.     DEBUG and print "Bypassing any super-matching.\n", 
  365.       " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  366.  
  367.   } elsif( $MATCH_SUPERS_TIGHTLY ) {
  368.     DEBUG and print "Before adding new supers tightly:\n", 
  369.       " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  370.  
  371.     my %seen_encoded;
  372.     foreach my $lang (@languages) {
  373.       $seen_encoded{ I18N::LangTags::encode_language_tag($lang) } = 1
  374.     }
  375.  
  376.     my(@output_languages);
  377.     foreach my $lang (@languages) {
  378.       push @output_languages, $lang;
  379.       foreach my $s ( I18N::LangTags::super_languages($lang) ) {
  380.         # Note that super_languages returns the longest first.
  381.         last if $seen_encoded{ I18N::LangTags::encode_language_tag($s) };
  382.         push @output_languages, $s;
  383.       }
  384.     }
  385.     @languages = @output_languages;
  386.  
  387.     DEBUG and print "After adding new supers tightly:\n", 
  388.       " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  389.  
  390.   } else {
  391.  
  392.     push @languages,  map I18N::LangTags::super_languages($_), @languages;
  393.     DEBUG and print "After adding supers to end:\n", 
  394.       " Lgs\@", __LINE__, ": ", map("<$_>", @languages), "\n";
  395.   }
  396.   
  397.   return @languages;
  398. }
  399.  
  400. ###########################################################################
  401. #
  402. # This is where most people should stop reading.
  403. #
  404. ###########################################################################
  405.  
  406. use Locale::Maketext::GutsLoader;
  407.  
  408. sub _http_accept_langs {
  409.   # Deal with HTTP "Accept-Language:" stuff.  Hassle.
  410.   # This code is more lenient than RFC 3282, which you must read.
  411.   # Hm.  Should I just move this into I18N::LangTags at some point?
  412.   no integer;
  413.  
  414.   my $in = (@_ > 1) ? $_[1] : $ENV{'HTTP_ACCEPT_LANGUAGE'};
  415.   # (always ends up untainting)
  416.  
  417.   return() unless defined $in and length $in;
  418.  
  419.   $in =~ s/\([^\)]*\)//g; # nix just about any comment
  420.   
  421.   if( $in =~ m/^\s*([a-zA-Z][-a-zA-Z]+)\s*$/s ) {
  422.     # Very common case: just one language tag
  423.     return lc $1;
  424.   } elsif( $in =~ m/^\s*[a-zA-Z][-a-zA-Z]+(?:\s*,\s*[a-zA-Z][-a-zA-Z]+)*\s*$/s ) {
  425.     # Common case these days: just "foo, bar, baz"
  426.     return map lc($_), $in =~ m/([a-zA-Z][-a-zA-Z]+)/g;
  427.   }
  428.  
  429.   # Else it's complicated...
  430.  
  431.   $in =~ s/\s+//g;  # Yes, we can just do without the WS!
  432.   my @in = $in =~ m/([^,]+)/g;
  433.   my %pref;
  434.   
  435.   my $q;
  436.   foreach my $tag (@in) {
  437.     next unless $tag =~
  438.      m/^([a-zA-Z][-a-zA-Z]+)
  439.         (?:
  440.          ;q=
  441.          (
  442.           \d*   # a bit too broad of a RE, but so what.
  443.           (?:
  444.             \.\d+
  445.           )?
  446.          )
  447.         )?
  448.        $
  449.       /sx
  450.     ;
  451.     $q = (defined $2 and length $2) ? $2 : 1;
  452.     #print "$1 with q=$q\n";
  453.     push @{ $pref{$q} }, lc $1;
  454.   }
  455.  
  456.   return # Read off %pref, in descending key order...
  457.     map @{$pref{$_}},
  458.     sort {$b <=> $a}
  459.     keys %pref;
  460. }
  461.  
  462. ###########################################################################
  463.  
  464. my %tried = ();
  465.   # memoization of whether we've used this module, or found it unusable.
  466.  
  467. sub _try_use {   # Basically a wrapper around "require Modulename"
  468.   # "Many men have tried..."  "They tried and failed?"  "They tried and died."
  469.   return $tried{$_[0]} if exists $tried{$_[0]};  # memoization
  470.  
  471.   my $module = $_[0];   # ASSUME sane module name!
  472.   { no strict 'refs';
  473.     return($tried{$module} = 1)
  474.      if defined(%{$module . "::Lexicon"}) or defined(@{$module . "::ISA"});
  475.     # weird case: we never use'd it, but there it is!
  476.   }
  477.  
  478.   print " About to use $module ...\n" if DEBUG;
  479.   {
  480.     local $SIG{'__DIE__'};
  481.     eval "require $module"; # used to be "use $module", but no point in that.
  482.   }
  483.   if($@) {
  484.     print "Error using $module \: $@\n" if DEBUG > 1;
  485.     return $tried{$module} = 0;
  486.   } else {
  487.     print " OK, $module is used\n" if DEBUG;
  488.     return $tried{$module} = 1;
  489.   }
  490. }
  491.  
  492. #--------------------------------------------------------------------------
  493.  
  494. sub _lex_refs {  # report the lexicon references for this handle's class
  495.   # returns an arrayREF!
  496.   no strict 'refs';
  497.   my $class = ref($_[0]) || $_[0];
  498.   print "Lex refs lookup on $class\n" if DEBUG > 1;
  499.   return $isa_scan{$class} if exists $isa_scan{$class};  # memoization!
  500.  
  501.   my @lex_refs;
  502.   my $seen_r = ref($_[1]) ? $_[1] : {};
  503.  
  504.   if( defined( *{$class . '::Lexicon'}{'HASH'} )) {
  505.     push @lex_refs, *{$class . '::Lexicon'}{'HASH'};
  506.     print "%" . $class . "::Lexicon contains ",
  507.          scalar(keys %{$class . '::Lexicon'}), " entries\n" if DEBUG;
  508.   }
  509.  
  510.   # Implements depth(height?)-first recursive searching of superclasses.
  511.   # In hindsight, I suppose I could have just used Class::ISA!
  512.   foreach my $superclass (@{$class . "::ISA"}) {
  513.     print " Super-class search into $superclass\n" if DEBUG;
  514.     next if $seen_r->{$superclass}++;
  515.     push @lex_refs, @{&_lex_refs($superclass, $seen_r)};  # call myself
  516.   }
  517.  
  518.   $isa_scan{$class} = \@lex_refs; # save for next time
  519.   return \@lex_refs;
  520. }
  521.  
  522. sub clear_isa_scan { %isa_scan = (); return; } # end on a note of simplicity!
  523.  
  524. ###########################################################################
  525. 1;
  526.  
  527. __END__
  528.  
  529. HEY YOU!  You need some FOOD!
  530.  
  531.  
  532.   ~~ Tangy Moroccan Carrot Salad ~~
  533.  
  534. * 6 to 8 medium carrots, peeled and then sliced in 1/4-inch rounds
  535. * 1/4 teaspoon chile powder (cayenne, chipotle, ancho, or the like)
  536. * 1 tablespoon ground cumin
  537. * 1 tablespoon honey
  538. * The juice of about a half a big lemon, or of a whole smaller one
  539. * 1/3 cup olive oil
  540. * 1 tablespoon of fresh dill, washed and chopped fine
  541. * Pinch of salt, maybe a pinch of pepper
  542.  
  543. Cook the carrots in a pot of boiling water until just tender -- roughly
  544. six minutes.  (Just don't let them get mushy!)  Drain the carrots.
  545.  
  546. In a largish bowl, combine the lemon juice, the cumin, the chile
  547. powder, and the honey.  Mix well.
  548. Add the olive oil and whisk it together well.  Add the dill and stir.
  549.  
  550. Add the warm carrots to the bowl and toss it all to coat the carrots
  551. well.  Season with salt and pepper, to taste.
  552.  
  553. Serve warm or at room temperature.
  554.  
  555. The measurements here are very approximate, and you should feel free to
  556. improvise and experiment.  It's a very forgiving recipe.  For example,
  557. you could easily halve or double the amount of cumin, or use chopped mint
  558. leaves instead of dill, or lime juice instead of lemon, et cetera.
  559.  
  560. [end]
  561.  
  562.