Run.pm untested

filter: Statementstmt 0.0% 0 / 584 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 161 MC/DCmcdc 0.0% 0 / 90 Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 1026 CC 29 SCAR 33.6
CC
29
Cov
0%
diag_ref_print
110.0
start_log
42.0
AUTOLOAD
30.0
CRAP 28.7
1 package Glade::Two::Run;
2 require 5.000; use strict 'vars', 'refs', 'subs';
3  
4 # Copyright (c) 1999 Dermot Musgrove <dermot.musgrove@virgin.net>
5 #
6 # This library is released under the same conditions as Perl, that
7 # is, either of the following:
8 #
9 # a) the GNU General Public License as published by the Free
10 # Software Foundation; either version 1, or (at your option) any
11 # later version.
12 #
13 # b) the Artistic License.
14 #
15 # If you use this library in a commercial enterprise, you are invited,
16 # but not required, to pay what you feel is a reasonable fee to perl.org
17 # to ensure that useful software is available now and in the future.
18 #
19 # (visit http://www.perl.org/ or email donors@perlmongers.org for details)
20  
21 BEGIN {
22 use Exporter qw( );
23 use POSIX qw( isdigit );
24 use Gtk2; # For message_box
25 use Gtk2::Window;
26 use Gtk2::HBox;
27 use Gtk2::VBox;
28 use Gtk2::HButtonBox;
29 use Gtk2::Entry;
30 use Gtk2::Button;
31 use Gtk2::Image;
32 use Gtk2::Label;
33 use Gtk2::Tooltips
34 eval "use Gtk2::Keysyms";
35 use Cwd qw( cwd getcwd chdir );
36 use File::Basename;
37 use Data::Dumper;
38 use Text::Wrap qw( wrap $columns ); # in options, diag_print
39 use vars qw( @ISA
40 $AUTOLOAD
41 %fields %stubs
42 @EXPORT @EXPORT_OK %EXPORT_TAGS
43 $PACKAGE $VERSION $AUTHOR $DATE
44 @VARS @METHODS
45  
46 $SAVE_MISSING
47 $MISSING_STRINGS
48 $C
49 $W
50 $WIDGET_INSTANCE
51 $CH
52 $WH
53 $MO_HEADER_INFO
54 $RUN_LANG
55 $SOURCE_LANG
56 $DIAG_LANG
57
58 $Glade_Perl
59 $I18N
60 $indent
61 $tab
62  
63 $all_forms
64 $widgets
65 $work
66 $forms
67 $pixmaps_directory
68  
69 @use_modules
70 %stat
71 $NOFILE
72 $permitted_fields
73 $convert
74 $Gtk
75 );
76 use subs qw (
77 );
78 # Tell interpreter who we are inheriting from
79 @ISA = qw(
80 Exporter
81 );
82  
83 $PACKAGE = __PACKAGE__;
84 $VERSION = q(0.01);
85 $AUTHOR = q(Dermot Musgrove <dermot.musgrove@virgin.net>);
86 $DATE = q(Sun Nov 17 06:02:01 GMT 2002 );
87  
88 $widgets = {};
89 $all_forms = {};
90 $indent = '';
91 $pixmaps_directory = "pixmaps";
92 $C = '__C';
93 $W = '__W';
94 $CH = '__CH';
95 $WH = '__WH';
96 $NOFILE = '__NOFILE';
97 $SAVE_MISSING = '__SAVE_MISSING';
98 $MISSING_STRINGS = '__MISSING_STRINGS';
99 $MO_HEADER_INFO = '__MO_HEADER_INFO';
100 $WIDGET_INSTANCE = '__W';
101 $RUN_LANG = '__RUN_LANG';
102 $SOURCE_LANG = '__SOURCE_LANG';
103 $DIAG_LANG = '__DIAG_LANG';
104 $permitted_fields = '_permitted_fields';
105  
106 # These vars are imported by all Glade-Perl modules for consistency
107 @VARS = qw(
108 $Glade_Perl
109 $I18N
110 $indent
111 $tab
112 @use_modules
113 $NOFILE
114 $SAVE_MISSING
115 $MISSING_STRINGS
116 $C
117 $W
118 $WIDGET_INSTANCE
119 $CH
120 $WH
121 $MO_HEADER_INFO
122 $RUN_LANG
123 $SOURCE_LANG
124 $DIAG_LANG
125 $permitted_fields
126 $convert
127 $Gtk
128 );
129 @METHODS = qw(
130 _
131 S_
132 D_
133 start_checking_gettext_strings
134 create_image
135 create_pixmap
136 missing_handler
137 message_box
138 message_box_close
139 show_skeleton_message
140 &typeKey
141 &keyFormat
142 &QuoteXMLChars
143 &UnQuoteXMLChars
144 reload_any_altered_modules
145 );
146 # These symbols (globals and functions) are always exported
147 @EXPORT = qw(
148 );
149 # Optionally exported package symbols (globals and functions)
150 @EXPORT_OK = ( @METHODS, @VARS );
151 # Tags (groups of symbols) to export
152 %EXPORT_TAGS = (
153 'METHODS' => [@METHODS] ,
154 'VARS' => [@VARS]
155 );
156 }
157  
158 %fields = (
159 # These are the data fields that you can set/get using the dynamic
160 # calls provided by AUTOLOAD (and their initial values).
161 # eg $class->FORMS($new_value); sets the value of FORMS
162 # $current_value = $class->FORMS; gets the current value of FORMS
163 'app' => {
164 'name' => undef,
165 'author' => undef,
166 'version' => '0.01',
167 'date' => undef,
168 'copying' => # Copying policy to appear in generated source
169 "# Unspecified copying policy, please contact the author
170 # ",
171 'description' => undef, # Description for About box etc.
172 # 'pixmaps_directory' => undef,
173 'logo' => 'Logo.xpm', # Use specified logo for project
174 },
175 'data' => {
176 'directory' => undef,
177 },
178 'diag' => {
179 'verbose' => undef, # Show errors and main diagnostics
180 'wrap_at' => 0, # Max diagnostic line length (approx)
181 'autoflush' => undef, # Dont change the policy
182 'indent' => ' ', # Diagnostics indent to lay out messages
183 'benchmark' => undef, # Dont add time to the diagnostic messages
184 'log' => undef, # Write diagnostics to STDOUT
185 # 'log' => "\&STDOUT",# Write diagnostics to STDOUT
186 # or Filename to write diagnostics to
187 'LANG' => ($ENV{'LANG'} || ''),
188 # Which language we want the diagnostics
189 },
190 'run_options' => {
191 'name' => __PACKAGE__,
192 'version' => $VERSION, # Version of Glade-Perl used
193 'author' => $AUTHOR,
194 'date' => $DATE,
195 'logo' => 'glade2perl_logo.xpm', # Our logo
196 'start_time' => undef, # Time that this run started
197 'mru' => undef,
198 'prune' => undef,
199 'proto' => {
200 'site' => undef,
201 'user' => undef,
202 'project' => undef,
203 'params' => undef,
204 'app_defaults' => undef,
205 'base_defaults' => undef,
206 },
207 'xml' => {
208 'site' => undef,
209 'user' => undef,
210 'project' => undef,
211 'params' => undef,
212 'app_defaults' => "Application defaults",
213 'base_defaults' => __PACKAGE__." defaults",
214 'set_by' => 'DEFAULT', # Who set the options
215 'encoding' => undef, # Character encoding eg ('ISO-8859-1')
216 },
217 },
218 );
219  
220  
221 %stubs = (
222 );
223  
224 my $option_hashes = " ".
225 join(" ",
226 'app',
227 'diag',
228 'glade',
229 'glade2perl',
230 'glade2perl-1',
231 'glade2perl-2',
232 'glade_helper',
233 'source',
234 'xml',
235 'dist',
236 'helper',
237 'test',
238 'run_options',
239 )." ";
240  
241 sub DESTROY {
242 # This sub will be called on object destruction
243 } # End of sub DESTROY
244  
245 =pod
246  
247 =head1 NAME
248  
249 Glade::Two::Run - Utility methods for Glade-Perl (and generated applications).
250  
251 =head1 SYNOPSIS
252  
253 use vars qw(@ISA);
254 use Glade::Two::Run qw(:METHODS :VARS);
255 @ISA = qw( Glade::Two::Run );
256  
257 # 1) CLASS methods
258 my $Object = Glade::Two::Run->new(%params);
259 $Object->glade->file($supplied_path);
260 $widget = $window->lookup_widget('clist1');
261  
262 # 2) OPTIONS handling
263 $options = Glade::Two::Run->options(%params);
264 $normalised_value = Glade::Two::Run->normalise('True');
265 $new_hash_ref = Glade::Two::Run->merge_into_hash_from(
266 $to_hash_ref, # Hash to be updated
267 $from_hash_ref, # Input data to be merged
268 'set accessors'); # Any value will add AUTOLOAD() accessors
269 # for these keys.
270 $Object->save_app_options($mru_filename);
271 $Object->save_options;
272  
273 my $string = Glade::Two::Run->string_from_file('/path/to/file');
274 Glade::Two::Run->save_file_from_string('/path/to/file', $string);
275  
276 # 3) Diagnostic message printing
277 $Object->start_log('log_filename');
278 $Object->diag_print(2, "This is a diagnostics message");
279 $Object->diag_print(2, $hashref, "Prefix to message");
280 $Object->stop_log;
281  
282 # 4) I18N
283 Glade::Two::Run->load_translations('MyApp', 'fr', '/usr/local/share/locale/',
284 undef, $SOURCE_LANG, 'Merge with already loaded translations');
285 sprintf(_("A message '%s'"), $value);
286 sprintf(gettext($SOURCE_LANG, "A message '%s'"), $value);
287 Glade::Two::Run->start_checking_gettext_strings($SOURCE_LANG);
288 Glade::Two::Run->stop_checking_gettext_strings($SOURCE_LANG);
289 Glade::Two::Run->write_missing_gettext_strings($SOURCE_LANG);
290  
291 # 5) UI methods
292 my $image = Glade::Two::Run->create_image('new.xpm', ['dir1', 'dir2']);
293 my $pixmap = Glade::Two::Run->create_pixmap($form, 'new.xpm', ['dir1', 'dir2']);
294  
295 Glade::Two::Run->show_skeleton_message(
296 $me, \@_, __PACKAGE__, "$Glade::Two::Run::pixmaps_directory/Logo.xpm");
297 Glade::Two::Run->message_box(
298 $message, # Message to display
299 $title, # Dialog title string
300 [_('Dismiss'), _("Quit")." Program"], # Buttons to show
301 1, # Default button is 1st
302 $pixmap, # pixmap filename
303 [&dismiss, &quit], # Button click handlers
304 $entry_needed); # Whether to show an entry
305 # widget for user data
306  
307 # 6) General methods
308 $path = $Object->full_Path($Object->glade->file, $dir);
309 $path = Glade::Two::Run->relative_Path($relative_path, $directory);
310  
311 $Object->reload_any_altered_modules;
312  
313 =head1 DESCRIPTION
314  
315 Glade::Two::Run provides some utility methods that Glade-Perl modules and
316 also the generated classes need to run. These methods can be inherited and
317 called in any app that use()s Glade::Two::Run and quotes Glade::Two::Run
318 in its @ISA array.
319  
320 Broadly, the utilities are of seven types.
321  
322 1) Class methods
323 2) Options handling
324 3) Diagnostic message printing
325 4) I18N
326 5) UI methods
327 6) General methods
328  
329 =head1 1) CLASS METHODS
330  
331 The class methods provide an object constructor and data accessors.
332  
333 =over 4
334  
335 =cut
336  
337 sub new {
338  
339 =item new(%params)
340  
341 Construct a Glade::Two::Run object
342  
343 e.g. my $Object = Glade::Two::Run->new(%params);
344  
345 =cut
346  
347 my $that = shift;
348 my %params = @_;
349 my $class = ref($that) || $that;
350 # Call our super-class constructor to get an object and reconsecrate it
351 my $self = bless {}, $class;
352  
353 $self->merge_into_hash_from($self, \%fields, (__PACKAGE__." defaults"));
354 $self->run_options->proto->base_defaults(\%fields);
355 $self->merge_into_hash_from($self, \%params, ("$class app defaults"));
356 $self->run_options->proto->app_defaults(\%params);
357  
358 return $self;
359 }
360  
361 sub AUTOLOAD {
362  
363 =item AUTOLOAD()
364  
365 Accesses all class data
366  
367 e.g. my $glade_filename = $Object->glade->file;
368 or $Object->glade->file('path/to/glade/file');
369  
370 =cut
371 my $self = shift;
372 my $class = ref($self)
373 or die "$self is not an object so we cannot '$AUTOLOAD'\n",
374 "We were called from ".join(", ", caller),"\n\n";
375 my $name = $AUTOLOAD;
376 $name =~ s/.*://; # strip fully-qualified portion
377  
378 if (exists $self->{$permitted_fields}->{$name} ) {
379 # This allows dynamic data methods - see %fields above
380 # eg $class->UI('new_value');
381 # or $current_value = $class->UI;
382 if (@_) {
383 return $self->{$name} = shift;
384 } else {
385 return $self->{$name};
386 }
387  
388 } elsif (exists $stubs{$name} ) {
389 # This shows dynamic signal handler stub message_box - see %stubs above
390 __PACKAGE__->show_skeleton_message(
391 $AUTOLOAD."\n ("._("AUTOLOADED by")." ".__PACKAGE__.")",
392 (ref $self), @_,
393 __PACKAGE__,
394 'pixmaps/Logo.xpm');
395
396 } elsif ($name ne 'DESTROY'){
397 die "Can't access method `$name' in class $class\n",
398 "We were called from ",join(", ", caller),"\n\n";
399  
400 }
401 }
402  
403 sub lookup_widget {
404  
405 =item lookup_widget($widgetname)
406  
407 Accesses a window or a form's widget by name
408  
409 e.g. my $widget = $window->lookup_widget('clist1');
410  
411 OR my $form = $window->FORM; # or use $form in signal handlers
412 my $widget = $form->lookup_widget('clist1');
413  
414 =cut
415  
416 my $self = shift;
417 my $name = shift;
418 my $hash = {};
419
420 my $class = ref($self)
421 or die "$self is not an object so we cannot lookup_widget '$name'\n",
422 "We were called from ".join(", ", caller),"\n\n";
423
424 if (exists $self->{$permitted_fields}->{FORM}) {
425 $hash = $self->FORM;
426  
427 } elsif (exists $self->{TOPLEVEL}) {
428 $hash = $self;
429
430 } else {
431 print "$self is not a window or form object so we cannot lookup_widget '$name'\n",
432 "We were called from ".join(", ", caller),"\n\n";
433 }
434  
435 if (exists $hash->{$name} ) {
436 return $hash->{$name};
437  
438 } else {
439 print "There is no widget `$name' in class $class\n",
440 "We were called from ",join(", ", caller),"\n\n";
441 return undef;
442 }
443 }
444  
445 sub fix_name {
446  
447 =item fix_name($name)
448  
449 Substitutes illegal characters in a perl name and returns it
450  
451 e.g. my $name = Glade::Two::Run->fix_name($name);
452 OR my $name = Glade::Two::Run->fix_name($name, 'TRANSLATE');
453  
454 =cut
455  
456 my ($class, $name, $translate) = @_;
457 my $illegals = '- ./+*!';
458 my $replaced = 0;
459 my $new_name = $name;
460 if ($name =~ /[$illegals]/) {
461 if ($translate) {
462 my %ents=('-'=>'MINUS', ' '=>'SPACE', '.'=>'DOT',
463 '/'=>'SLASH', '+'=>'PLUS', '*'=>'STAR', '!'=>'BANG');
464 $replaced = $new_name =~ s/([$illegals])/_$ents{$1}_/g;
465  
466 } else {
467 $replaced = $new_name =~ s/([$illegals])//g;
468  
469 }
470 $Glade_Perl->diag_print (1, "warn new name '%s' generated as ".
471 "original name '%s' contained %s chars [$illegals]".
472 "which are illegal in a Perl name.",
473 $new_name, $name, $replaced);
474 }
475 return $new_name;
476 }
477 sub save_file_from_string {
478 my ($class, $filename, $string) = @_;
479 my $me = __PACKAGE__."->save_file_from_string";
480  
481 =item save_file_from_string($filename, $string)
482  
483 Write a string to a file.
484  
485 e.g. Glade::Two::Run->save_file_from_string('/path/to/file', $string);
486  
487 =cut
488 $class->diag_print(5, $string, 'DONT_TRANSLATE');
489  
490 open OUTPUT, ">".($filename) or
491 die sprintf("error %s - can't open file '%s' for output",
492 $me, $filename);
493 print OUTPUT $string || '';
494 close OUTPUT or
495 die sprintf("error %s - can't close file '%s'",
496 $me, $filename);
497 $class->diag_print(3, "%s- %s string saved to %s",
498 $class->diag->indent, $me, $filename);
499 }
500  
501 #===============================================================================
502 #=========== Diagnostics utilities ============
503 #===============================================================================
504  
505 =back
506  
507 =head1 3) DIAGNOSTIC MESSAGE METHODS
508  
509 These methods will start logging diagnostic messages, produce standardised
510 I18N messages and then stop logging and close any open files.
511  
512 =over
513  
514 =cut
515  
516 sub verbosity { shift->diag->verbose }
517 sub Writing_to_File { shift->source->write }
518 sub Building_UI_only {!defined shift->source->write }
519  
520 sub diagnostics {
521 ($_[1] || 1) <= (shift->diag->verbose);
522 }
523  
524 sub diag_print {
525 my $class = shift;
526 my $level = shift;
527 my $message = shift;
528  
529 =item diag_print()
530  
531 Prints diagnostics message (I18N translated) if verbosity is >= level specified
532  
533 e.g. $Object->diag_print(2, "This is a diagnostics message");
534 $Object->diag_print(2, $hashref, "Prefix to message");
535  
536 =cut
537 return unless $class->diagnostics($level);
538 my $time='';
539 if ($class->diag->benchmark) {
540 my @times = times;
541 $time = int( $times[0] + $times[1] );
542 }
543 unless (ref $message) {
544 # Make up message from all remaining args
545 $message = sprintf(D_($message, 2), @_) unless
546 $_[0] && $_[0] eq 'DONT_TRANSLATE';
547 print STDOUT wrap($time,
548 $class->diag->indent.$class->diag->indent, "$message\n");
549  
550 } else {
551 my $prefix = shift || '';
552 print $class->diag->indent."- $prefix ", Dumper($message);
553 # $class->diag_ref_print($level, $message, @_);
554 }
555 }
556  
557 sub diag_ref_print {
558 my ($class, $level, $message, $desc, $pad) = @_;
559  
560 return unless $class->diagnostics($level);
561 my ($key, $val, $ref);
562 my $padkey = $pad || 17;
563 my $title = D_($desc || "");
564 my @times = times;
565 my $time='';
566 $ref = ref $message;
567 if ($class->diag->benchmark) {
568 $time = int( $times[0] + $times[1] );
569 }
570 unless ($ref) {
571 print STDOUT wrap($time,
572 $time.$class->diag->indent.$class->diag->indent, "$message\n");
573  
574 } elsif (($ref eq 'HASH') or ( $ref =~ /Glade::/)) {
575 print STDOUT "$title $ref ",D_("contains"), ":\n";
576 foreach $key (sort keys %$message) {
577 my $ref = ref $message->{$key};
578 if (ref $message->{$key}) {
579 print STDOUT " {'$key'}".
580 (' ' x ($padkey-length($key))).
581 " => ", D_("is a reference to a"), " $ref\n";
582 } elsif (defined $message->{$key}) {
583 print STDOUT " {'$key'}".
584 (' ' x ($padkey-length($key))).
585 " => '$message->{$key}'\n";
586 } else {
587 print STDOUT " {'$key'}\n";
588 }
589 $val = (ref ) || $message->{$key} || 'undef';
590 }
591  
592 } elsif ($ref eq 'ARRAY') {
593 print STDOUT "$title $ref ", D_("contains"), ":\n";
594 my $im_count = 0;
595 foreach $val (@$message) {
596 $key = sprintf "[%d]", $im_count;
597 $ref = ref $val;
598 if ($ref) {
599 print STDOUT " $key".(' ' x ($padkey-length($key))).
600 " = ", D_("is a reference to a"), " $ref\n";
601 } elsif (defined $message->[$im_count]) {
602 print STDOUT " $key".(' ' x ($padkey-length($key))).
603 " = '$message->[$im_count]'\n";
604 } else {
605 print STDOUT " $key\n";
606 }
607 $im_count++;
608 }
609  
610 } else {
611 # Unknown ref type
612 print STDOUT wrap($time, $time.$class->diag->indent.$class->diag->indent,
613 D_("Unknown reference type"), " '$ref'\n");
614 }
615 }
616  
617 sub start_log {
618 my ($class, $filename) = @_;
619 my $me = (ref $class || $class)."->start_log";
620  
621 =item start_log()
622  
623 Opens the log files and starts writing diagnostics
624  
625 e.g. $Object->start_log('log_filename');
626  
627 =cut
628 my $type = $class->type;
629 # Check for log file names
630 $filename ||=
631 $class->diag->log ||
632 $class->{$type}->proto->{params}{$type}{diag}{log} ||
633 $class->{$type}->proto->{project}{$type}{diag}{log} ||
634 $class->{$type}->proto->{user}{$type}{diag}{log} ||
635 $class->{$type}->proto->{site}{$type}{diag}{log} ||
636 "STDOUT";
637 $filename = $class->normalise($filename);
638  
639 if ($class->diag->autoflush) {
640 select STDOUT;
641 $|=1;
642 }
643 if ('*STDOUT*1*' =~ /\*$filename\*/) {
644 $filename = '&STDOUT';
645 } else {
646 $class->diag->log($filename);
647 }
648 if ($class->diag->verbose == 0 ) {
649 $class->diag_print (2, "Redirecting output to /dev/null");
650 open STDOUT, ">/dev/null";
651  
652 } elsif ($class->diag->log) {
653 unless ('*&STDOUT*STDOUT*1*' =~ /\*$filename\*/) {
654 # Set full paths
655 $class->diag->log($class->full_Path($class->diag->log, `pwd`));
656 $class->diag_print (3, "%s- Opening log file '%s'",
657 $class->diag->indent, $class->diag->log);
658 open STDOUT, ">".$class->diag->log or
659 die sprintf("error %s - can't open file '%s' for output",
660 $me, $class->diag->log);
661 }
662 open STDERR, ">&1" or
663 die sprintf("error %s - can't redirect STDERR to file '%s'",
664 $me, $class->diag->log);
665 }
666 $class->diag_print (2,
667 "--------------------------------------------------------");
668 $class->diag_print (2,
669 "%s DIAGNOSTICS - %s (locale <%s> verbosity %s) ".
670 "started by %s (version %s)",
671 $class->diag->indent, $class->{$type}->start_time,
672 $class->diag->LANG, $class->diag->verbose,
673 $class->{$type}->name, $class->{$type}->version,
674 );
675 }
676  
677 sub stop_log {
678 my ($class, $type) = @_;
679 my $me = (ref $class || $class)."->stop_log";
680  
681 =item stop_log()
682  
683 Loads site/user/project/params options
684  
685 e.g. $Object->stop_log;
686  
687 =cut
688 $type ||= $class->type;
689 if ($class->diag->log and $class->diagnostics(2)) {
690 $class->diag_print (2,
691 "%s RUN COMPLETED - %s diagnostics stopped by %s (version %s)",
692 $class->diag->indent, $class->get_time,
693 $class->{$type}->name, $class->{$type}->version);
694 $class->diag_print (2,
695 "-----------------------------------------------------------------------------");
696 close(STDERR) || die "can't close stderr: $!";
697 close(STDOUT) || die "can't close stdout: $!" ;
698 }
699 }
700  
701 #===============================================================================
702 #=========== Gettext Utilities ====
703 #=========== 'borrowed' from the gettext dist and recoded to house style ====
704 #===============================================================================
705  
706 =back
707  
708 =head1 4) INTERNATIONALISATION (I18N) METHODS
709  
710 These methods will load translations, translate messages, check for any
711 missing translations and write a .pot file containing these missing messages.
712  
713 =over
714  
715 =cut
716  
717 =item _()
718  
719 Translate a string into our current language
720  
721 e.g. sprintf(_("A message '%s'"), $value);
722  
723 =cut
724 sub _ {gettext(@_)}
725  
726 =item gettext()
727  
728 Translate into a preloaded language (eg $SOURCE_LANG or $DIAG_LANG)
729  
730 e.g. C<sprintf(gettext($SOURCE_LANG, "A message '%s'"), $value);>
731  
732 =cut
733 sub gettext {
734 defined $I18N->{$RUN_LANG}{$_[0]} ? $I18N->{$RUN_LANG}{$_[0]} : $_[0];
735 }
736  
737 # These are defined within a no-warning block to avoid warnings about redefining
738 # They override the subs in Glade::Two::Run during your development
739 {
740 local $^W = 0;
741 eval "sub x_ {_check_gettext('__', \@_);}";
742 }
743  
744 # Translate string into source language
745 sub S_ { _check_gettext($SOURCE_LANG, @_)}
746  
747 # Translate string into diagnostics language
748 sub D_ { _check_gettext($DIAG_LANG, @_)}
749  
750 # Internal utility to note any untranslated strings
751 sub _check_gettext {
752 # If check_gettext_strings() has been called and there is no translation
753 # we store the original string for later output by write_gettext_strings
754 my ($key, $text, $depth) = @_;
755  
756 $depth ||= 1;
757 if (defined $I18N->{$key}{$text}) {
758 return $I18N->{$key}{$text};
759 } else {
760 if ($I18N->{$key}{$SAVE_MISSING}) {
761 my $called_at =
762 basename((caller $depth)[1]). ":".(caller $depth)[2];
763 unless ($I18N->{$key}{$MISSING_STRINGS}{$text} &&
764 $I18N->{$key}{$MISSING_STRINGS}{$text} =~ / $called_at /) {
765 $I18N->{$key}{$MISSING_STRINGS}{$text} .= " $called_at ";
766 }
767 }
768 return $text;
769 }
770 }
771  
772 sub start_checking_gettext_strings {
773 my ($class, $key, $file) = @_;
774  
775 =item start_checking_gettext_strings()
776  
777 Start checking and storing missing translations in language type
778  
779 eg. $class->start_checking_gettext_strings($SOURCE_LANG);
780  
781  
782 =cut
783 $I18N->{($key || $RUN_LANG)}{$SAVE_MISSING} = ($file || "&STDOUT");
784 }
785  
786 sub stop_checking_gettext_strings {
787 my ($class, $key) = @_;
788  
789 =item stop_checking_gettext_strings()
790  
791 Stop checking for missing translations in language type
792  
793 eg. $class->stop_checking_gettext_strings($SOURCE_LANG);
794  
795 =cut
796 undef $I18N->{($key || $RUN_LANG)}{$SAVE_MISSING};
797 }
798  
799 sub write_missing_gettext_strings {
800 # Write out the strings that need to be translated in .pot format
801 my ($class, $key, $file, $no_header, $copy_to) = @_;
802  
803 =item write_missing_gettext_strings()
804  
805 Write a .pot file containing any untranslated strings in language type
806  
807 eg. $object->write_missing_gettext_strings($SOURCE_LANG);
808  
809 =cut
810 my ($string, $called_at);
811 my $me = __PACKAGE__."->write_translatable_strings";
812 my $saved = $I18N->{$key}{$MISSING_STRINGS};
813 $key ||= $RUN_LANG;
814 $file ||= $I18N->{$key}{$SAVE_MISSING};
815 return unless keys %$saved;
816 open POT, ">$file" or
817 die sprintf(("error %s - can't open file '%s' for output"),
818 $me, $file);
819 my $date = `date +"%Y-%m-%d %H:%M%z"`; chomp $date;
820 my $year = `date +"%Y"`; chomp $year;
821 # Print header
822 print POT "# ".sprintf(S_("These are strings that had no gettext translation in '%s'"), $key)."\n";
823 print POT "# ".sprintf(S_("Automatically generated by %s"),__PACKAGE__)."\n";
824 print POT "# ".S_("Date")." ".`date`;
825 print POT "# ".sprintf(S_("Run from class %s in file %s"), $class->PACKAGE, (caller 0)[1])."\n";
826 unless ($no_header && $no_header eq "NO_HEADER") {
827 print POT "
828 # SOME DESCRIPTIVE TITLE.
829 # Copyright (C) $year ORGANISATION
830 # ".$class->AUTHOR.",
831 #
832 # , fuzzy
833 msgid \"\"
834 msgstr \"\"
835 \"Project-Id-Version: ".$class->PACKAGE." ".$class->VERSION."\\n\"
836 \"POT-Creation-Date: $date\\n\"
837 \"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"
838 \"Last-Translator: ".$class->AUTHOR."\\n\"
839 \"Language-Team: LANGUAGE \<LL".'@li.org'."\>\\n\"
840 \"MIME-Version: 1.0\\n\"
841 \"Content-Type: text/plain; charset=CHARSET\\n\"
842 \"Content-Transfer-Encoding: ENCODING\\n\"
843  
844 #: Generic replacement
845 msgid \"\%s\"
846 msgstr \"\%s\"
847  
848 "; }
849  
850 # Print definition for each string
851 foreach $string (%$saved) {
852 next unless $string and $saved->{$string};
853 print POT wrap("#", "#",$saved->{$string}), "\n";
854 if ($string =~ s/\n/\\n\"\n\"/g) {$string = "\"\n\"".$string}
855 print POT "msgid \"$string\"\n";
856 if ($copy_to && $copy_to eq 'COPY_TO') {
857 print POT "msgstr \"$string\"\n\n";
858 } else {
859 print POT "msgstr \"\"\n\n";
860 }
861 }
862 close POT;
863 }
864  
865 sub load_translations {
866 my ($class, $domain, $language, $locale_dir, $file, $key, $merge) = @_;
867  
868 =item load_translations()
869  
870 Load a translation file (.mo) for later use as language type
871  
872 e.g. To load translations in current LANG from default locations
873 $class->load_translations('MyApp');
874
875 OR $class->load_translations('MyApp', 'test', undef,
876 '/home/dermot/Devel/Glade-Perl/ppo/en.mo');
877  
878 OR $class->load_translations('MyApp', 'fr', '/usr/local/share/locale/',
879 undef, $DIAG_LANG, 'Merge with already loaded translations');
880  
881 =cut
882 my $catalog_filename = $file;
883 $key ||= $RUN_LANG;
884 $I18N->{$key} = {} unless $merge and $merge eq "MERGE";;
885  
886 $language ||= $ENV{"LANG"};
887 return unless $language;
888 $locale_dir ||= "/usr/local/share/locale";
889 $domain ||= "Glade-Perl";
890  
891 for $catalog_filename ( $file ||
892 ("/usr/local/share/locale/$language/LC_MESSAGES/$domain.mo",
893 "/usr/share/locale/$language/LC_MESSAGES/$domain.mo")) {
894 if ($catalog_filename and (-f $catalog_filename)) {
895 $class->load_mo($catalog_filename, $key);
896 last;
897 }
898 }
899 }
900  
901 sub load_mo {
902 my ($class, $catalog, $key) = @_;
903  
904 my ($reverse, $buffer);
905 my ($magic, $revision, $nstrings);
906 my ($orig_tab_offset, $orig_length, $orig_pointer);
907 my ($trans_length, $trans_pointer, $trans_tab_offset);
908  
909 # Slurp in the catalog
910 my $save = $/;
911 open CATALOG, $catalog or return;
912 undef $/;
913 $buffer = <CATALOG>;
914 close CATALOG;
915 $/ = $save;
916
917 # Check magic order
918 $magic = unpack ("I", $buffer);
919 if (sprintf ("%x", $magic) eq "de120495") {
920 $reverse = 1;
921  
922 } elsif (sprintf ("%x", $magic) ne "950412de") {
923 print STDERR "'$catalog' "._("is not a catalog file")."\n";
924 return;
925 }
926  
927 $revision = &mo_format_value (4, $reverse, $buffer);
928 $nstrings = &mo_format_value (8, $reverse, $buffer);
929 $orig_tab_offset = &mo_format_value (12, $reverse, $buffer);
930 $trans_tab_offset = &mo_format_value (16, $reverse, $buffer);
931  
932 while ($nstrings-- > 0) {
933 $orig_length = &mo_format_value ($orig_tab_offset, $reverse, $buffer);
934 $orig_pointer = &mo_format_value ($orig_tab_offset + 4, $reverse, $buffer);
935 $orig_tab_offset += 8;
936  
937 $trans_length = &mo_format_value ($trans_tab_offset, $reverse, $buffer);
938 $trans_pointer = &mo_format_value ($trans_tab_offset + 4,$reverse, $buffer);
939 $trans_tab_offset += 8;
940  
941 $I18N->{$key}{substr ($buffer, $orig_pointer, $orig_length)}
942 = substr ($buffer, $trans_pointer, $trans_length);
943 }
944  
945 # Allow for translation of really empty strings
946 $I18N->{$key}{$MO_HEADER_INFO} = $I18N->{$key}{''};
947 $I18N->{$key}{''} = '';
948 }
949  
950 sub mo_format_value {
951 my ($string, $reverse, $buffer) = @_;
952  
953 unpack ("i",
954 $reverse
955 ? pack ("c4", reverse unpack ("c4", substr ($buffer, $string, 4)))
956 : substr ($buffer, $string, 4));
957 }
958  
959 #===============================================================================
960 #=========== Widget hierarchy Utilities ====
961 #===============================================================================
962 sub WH {
963 my ($class, $new) = @_;
964 if ($new) {
965 return $class->FORM->{$WH} = $new;
966 } else {
967 return $class->FORM->{$WH};
968 }
969 }
970  
971 sub CH {
972 my ($class, $new) = @_;
973 if ($new) {
974 return $class->FORM->{$CH} = $new;
975 } else {
976 return $class->FORM->{$CH};
977 }
978 }
979  
980 sub W {
981 my ($class, $proto, $new) = @_;
982 if ($new) {
983 return $proto->{$W} = $new;
984 } else {
985 return $proto->{$W};
986 }
987 }
988  
989 sub C {
990 my ($class, $proto, @new) = @_;
991 if ($#new) {
992 return push @{$proto->{$C}}, @new;
993 } else {
994 return $proto->{$C};
995 }
996 }
997  
998 #===============================================================================
999 #=========== UI utilities
1000 #===============================================================================
1001  
1002 =back
1003  
1004 =head1 5) UI METHODS
1005  
1006 These methods will provide some useful UI methods to load pixmaps and
1007 images and show message boxes of various types.
1008  
1009 =over
1010  
1011 =cut
1012  
1013 sub create_pixmap {
1014 my ($class, $widget, $filename, $pixmap_dirs) = @_;
1015 my $me = "$class->create_pixmap";
1016  
1017 =item create_pixmap()
1018  
1019 Create a gdk_pixmap and return it
1020  
1021 e.g. my $pixmap = Glade::Two::Run->create_pixmap(
1022 $form, 'new.xpm', ['dir1', 'dir2']);
1023  
1024 =cut
1025  
1026 # First look for a sub
1027 if (ref $filename eq 'CODE') {
1028 return new Gtk2::Pixmap(
1029 Gtk2::Gdk::Pixmap->create_from_xpm_d(
1030 $work->{'window'}, $work->{'style'}, &filename ));
1031 } else {
1032 my $found_filename = $class->find_file_in_dirs(
1033 $filename,
1034 @{$pixmap_dirs}, $Glade::Two::Run::pixmaps_directory, getcwd);
1035  
1036 return Gtk::Pixmap->create_from_xpm($found_filename);
1037 }
1038 }
1039  
1040 sub create_image {
1041 my ($class, $filename, $pixmap_dirs) = @_;
1042 my $me = "$class->create_image";
1043  
1044 =item create_image()
1045  
1046 Create and load a gdk_imlibimage and return it
1047  
1048 e.g. my $image = Glade::Two::Run->create_image(
1049 'new.xpm', ['dir1', 'dir2']);
1050  
1051 =cut
1052 my $found_filename = $class->find_file_in_dirs(
1053 $filename,
1054 @{$pixmap_dirs}, $Glade::Two::Run::pixmaps_directory, getcwd);
1055 return Gtk2::Image->new_from_file($found_filename);
1056 }
1057  
1058 sub create_pixbuf {
1059 my ($class, $filename, $pixmap_dirs) = @_;
1060 my $me = "$class->create_pixbuf";
1061  
1062 =item create_image()
1063  
1064 Create and load a gdk_pixbuf and return it
1065  
1066 e.g. my $image = Glade::Two::Run->create_pixbuf(
1067 'new.xpm', ['dir1', 'dir2']);
1068  
1069 =cut
1070 my $found_filename = $class->find_file_in_dirs(
1071 $filename,
1072 @{$pixmap_dirs}, $Glade::Two::Run::pixmaps_directory, getcwd);
1073 return Gtk2::Gdk::Pixbuf->new_from_file($found_filename);
1074 }
1075  
1076 sub find_file_in_dirs {
1077 my ($class, $filename, @dirs) = @_;
1078 my $me = "$class->find_file_in_dirs";
1079 my ($work, $testfile, $found_filename, $dir);
1080 if (-f $filename) {
1081 $found_filename = $filename;
1082  
1083 } else {
1084 foreach $dir (@dirs) {
1085 # Make up full path name and test
1086 $testfile = $class->full_Path($filename, $dir);
1087 if (-f $testfile) {
1088 $found_filename = $testfile;
1089 last;
1090 }
1091 }
1092 }
1093 if ($found_filename) {
1094 return $found_filename;
1095 } else {
1096 print STDERR sprintf(_(
1097 "error file '%s' does not exist in %s\n"),
1098 $filename, $me);
1099 return undef;
1100 }
1101 }
1102  
1103 sub missing_handler {
1104 my ($class, $dataref, $eventref) = @_;
1105 my ($widgetname, $signal, $handler, $pixmap) = @$dataref;
1106 my $me = __PACKAGE__."->missing_handler";
1107  
1108 #=item missing_handler()
1109 #
1110 #This method pops up a message while the source code is being generated
1111 #if there is no signal handler to call.
1112 #It shows a pixmap (logo) and buttons to dismiss the box or quit the app
1113 #
1114 # $widgetname the widget that triggered the event
1115 # $signal the signal that was triggered
1116 # $handler the name of the signal handler that is missing
1117 # $pixmap pixmap to show
1118 #
1119 #e.g. Glade::Two::Run->missing_handler(
1120 # $widgetname,
1121 # $signal,
1122 # $handler,
1123 # $pixmap);
1124 #
1125 #=cut
1126 print STDOUT sprintf(_("%s- %s - called with args ('%s')"),
1127 $indent, $me, join("', '", @_)), "\n";
1128 my $message = sprintf("\n"._("%s has been called because\n".
1129 "a signal (%s) was caused by widget (%s).\n".
1130 "When Glade::Two::Generate writes the Perl source to a file \n".
1131 "a skeleton signal handler sub called '%s'\n".
1132 "will be generated in the ProjectSIGS class file. You can write a sub with\n".
1133 "the same name in another module and it will automatically be called instead.\n"),
1134 $me, $signal, $widgetname, $handler) ;
1135 my $widget = __PACKAGE__->message_box($message,
1136 _("Missing handler")." '$handler' "._("called"),
1137 [_("Dismiss"), _("Quit")." Glade::Two::Generate"], 1, $pixmap);
1138
1139 # Stop the signal before it triggers the missing one
1140 #FIXME $class->signal_stop_emission($signal);
1141 # $class->signal_emit_stop($signal);
1142 return $widget;
1143 }
1144  
1145 sub show_skeleton_message {
1146 my ($class, $caller, $data, $package, $pixmap) = @_;
1147 #print Dumper(\@_);
1148 =item show_skeleton_message($class, $caller, $data, $package, $pixmap)
1149  
1150 This method pops up a message_box to prove that a stub has been called.
1151 It shows a pixmap (logo) and buttons to dismiss the box or quit the app
1152  
1153 $caller where we were called
1154 $data the args that were supplied to the caller
1155 $package
1156 $pixmap pixmap to show
1157  
1158 e.g. Glade::Two::Run->show_skeleton_message(
1159 $me, \@_, __PACKAGE__, "$Glade::Two::Run::pixmaps_directory/Logo.xpm");
1160  
1161 =cut
1162 $pixmap ||= "$Glade::Two::Run::pixmaps_directory/Logo.xpm";
1163 $package ||= (caller);
1164 $data ||= ['unknown args'];
1165  
1166 my $args = (ref $data->[0]);
1167 if (ref $data->[1] and ref $data->[1] eq 'ARRAY') {
1168 $args .= ", ['".join("', '", @{$data->[1]})."']".
1169 (ref $data->[2] && ', '.(ref $data->[2]).')');
1170 }
1171 $class->message_box(sprintf(_("
1172 A signal handler has just been triggered.
1173  
1174 %s
1175 was called with parameters (%s)
1176  
1177 Until the sub is written, I will show you
1178 this box to prove that I have been called
1179 "),
1180 $caller,
1181 $args),
1182 $caller,
1183 [_('Dismiss'), _("Quit")." Program"],
1184 1,
1185 $pixmap);
1186 }
1187  
1188 sub message_box {
1189 my ($class, $text, $title, $buttons, $default,
1190 $pixmapfile, $just, $handlers, $entry) = @_;
1191  
1192 =item message_box()
1193  
1194 Show a message box with optional pixmap and entry widget.
1195 After the dialog is closed, the data entered will be in
1196 global $Glade::Two::Run::data.
1197  
1198 e.g. Glade::Two::Run->message_box(
1199 $message, # Message to display
1200 $title, # Dialog title string
1201 [_('Dismiss'), _("Quit")." Program"],
1202 # Buttons to show
1203 1, # Default button is 1st
1204 $pixmap, # pixmap filename
1205 [&dismiss, &quit], # Button click handlers
1206 $entry_needed); # Whether to show an entry
1207 # widget for user data
1208  
1209 =cut
1210 #use Data::Dumper;print Dumper(\@_);
1211 my ($i, $ilimit);
1212 my $justify = $just || 'center';
1213 my $mbno = 1;
1214 # Get a unique toplevel widget structure
1215 while (defined $widgets->{"MessageBox-$mbno"}) {$mbno++;}
1216 #
1217 # Create a GtkDialog called MessageBox
1218 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE} = new Gtk2::Window('toplevel');
1219 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->set_title($title);
1220 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->set_position('mouse');
1221 # $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->set_policy('1', '1', '0');
1222 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->set_border_width('6');
1223 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->modal('1');
1224 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->realize;
1225 #print Dumper($widgets);
1226 # $widgets->{"MessageBox-$mbno"}{'tooltips'} = new Gtk2::Tooltips;
1227 #
1228 # Create a GtkVBox called MessageBox-vbox1
1229 #use Data::Dumper;print Dumper($widgets);
1230 $widgets->{"MessageBox-$mbno"}{'vbox1'} = new Gtk2::VBox(0, 0);
1231 $widgets->{"MessageBox-$mbno"}{'vbox1'}->set_border_width(0);
1232 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->add($widgets->{"MessageBox-$mbno"}{'vbox1'});
1233 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->show();
1234 #
1235 # Create a GtkHBox called MessageBox-hbox1
1236 $widgets->{"MessageBox-$mbno"}{'hbox1'} = new Gtk2::HBox('0', '0');
1237 $widgets->{"MessageBox-$mbno"}{'hbox1'}->set_border_width('0');
1238 $widgets->{"MessageBox-$mbno"}{'vbox1'}->add($widgets->{"MessageBox-$mbno"}{'hbox1'});
1239 $widgets->{"MessageBox-$mbno"}{'hbox1'}->show();
1240  
1241 if ($pixmapfile) {
1242 #
1243 # Create a GtkPixmap called pixmap1
1244 $widgets->{"MessageBox-$mbno"}{'pixmap1'} = $class->create_image($pixmapfile);
1245 if ($widgets->{"MessageBox-$mbno"}{'pixmap1'}) {
1246 $widgets->{"MessageBox-$mbno"}{'pixmap1'}->set_alignment('0.5', '0.5');
1247 # $widgets->{"MessageBox-$mbno"}{'pixmap1'}->set_padding('0', '0');
1248 $widgets->{"MessageBox-$mbno"}{'hbox1'}->add($widgets->{"MessageBox-$mbno"}{'pixmap1'});
1249 $widgets->{"MessageBox-$mbno"}{'pixmap1'}->show();
1250 # $widgets->{"MessageBox-$mbno"}{'hbox1'}->set_child_packing($widgets->{"MessageBox-$mbno"}{'pixmap1'}, '0', '0', '0', 'start');
1251 }
1252 }
1253  
1254 #
1255 # Create a GtkLabel called MessageBox-label1
1256 $widgets->{"MessageBox-$mbno"}{'label1'} = new Gtk2::Label($text);
1257 $widgets->{"MessageBox-$mbno"}{'label1'}->set_justify($justify);
1258 $widgets->{"MessageBox-$mbno"}{'label1'}->set_alignment('0.5', '0.5');
1259 # $widgets->{"MessageBox-$mbno"}{'label1'}->set_padding('0', '0');
1260 $widgets->{"MessageBox-$mbno"}{'hbox1'}->add($widgets->{"MessageBox-$mbno"}{'label1'});
1261 $widgets->{"MessageBox-$mbno"}{'label1'}->show();
1262 # $widgets->{"MessageBox-$mbno"}{'hbox1'}->set_child_packing($widgets->{"MessageBox-$mbno"}{'label1'}, '1', '1', '10', 'start');
1263 # $widgets->{"MessageBox-$mbno"}{'vbox1'}->set_child_packing($widgets->{"MessageBox-$mbno"}{'hbox1'}, '1', '1', '0', 'start');
1264 #
1265 # Create a GtkHBox called MessageBox-action_area1
1266 $widgets->{"MessageBox-$mbno"}{'action_area1'} = new Gtk2::HBox('1', '5');
1267 $widgets->{"MessageBox-$mbno"}{'action_area1'}->set_border_width('10');
1268 $widgets->{"MessageBox-$mbno"}{'vbox1'}->add($widgets->{"MessageBox-$mbno"}{'action_area1'});
1269 $widgets->{"MessageBox-$mbno"}{'action_area1'}->show();
1270 if ($entry) {
1271 #
1272 # Create a GtkEntry called MessageBox-entry
1273 $widgets->{"MessageBox-$mbno"}{'entry'} = new Gtk2::Entry;
1274 $widgets->{"MessageBox-$mbno"}{'vbox1'}->add($widgets->{"MessageBox-$mbno"}{'entry'});
1275 $widgets->{"MessageBox-$mbno"}{'entry'}->show( );
1276 $widgets->{"MessageBox-$mbno"}{'entry'}->set_usize('160', '0' );
1277 $widgets->{"MessageBox-$mbno"}{'entry'}->can_focus('1' );
1278 $widgets->{"MessageBox-$mbno"}{'entry'}->set_text('' );
1279 $widgets->{"MessageBox-$mbno"}{'entry'}->set_max_length('0' );
1280 $widgets->{"MessageBox-$mbno"}{'entry'}->set_visibility('1' );
1281 $widgets->{"MessageBox-$mbno"}{'entry'}->set_editable('1' );
1282 $widgets->{"MessageBox-$mbno"}{'entry'}->grab_focus();
1283 }
1284 #
1285 # Create a GtkHButtonBox called MessageBox-hbuttonbox1
1286 $widgets->{"MessageBox-$mbno"}{'hbuttonbox1'} = new Gtk2::HButtonBox;
1287 $widgets->{"MessageBox-$mbno"}{'hbuttonbox1'}->set_layout('default_style');
1288 $widgets->{"MessageBox-$mbno"}{'hbuttonbox1'}->set_spacing('10');
1289 $widgets->{"MessageBox-$mbno"}{'action_area1'}->add($widgets->{"MessageBox-$mbno"}{'hbuttonbox1'});
1290 $widgets->{"MessageBox-$mbno"}{'hbuttonbox1'}->show();
1291 #
1292 # Now add all the buttons that were requested (and check for default)
1293 $ilimit = scalar(@$buttons);
1294 for ($i = 0; $i < $ilimit; $i++) {
1295 #
1296 # Create a GtkButton called MessageBox-button2
1297 $widgets->{"MessageBox-$mbno"}{'button'.$i} = new_with_label Gtk2::Button($buttons->[$i]);
1298 # $widgets->{"MessageBox-$mbno"}{'button'.$i}->can_focus('1');
1299 if ($handlers->[$i]) {
1300 $widgets->{"MessageBox-$mbno"}{'button'.$i}->signal_connect('clicked', $handlers->[$i], [$mbno, $buttons->[$i]]);
1301 } else {
1302 $widgets->{"MessageBox-$mbno"}{'button'.$i}->signal_connect('clicked', __PACKAGE__."::message_box_close", [$mbno, $buttons->[$i]]);
1303 }
1304 $widgets->{"MessageBox-$mbno"}{'button'.$i}->set_border_width('0');
1305 $widgets->{"MessageBox-$mbno"}{'hbuttonbox1'}->add($widgets->{"MessageBox-$mbno"}{'button'.$i});
1306 if ($i == ($default-1)) {
1307 $widgets->{"MessageBox-$mbno"}{'button'.$i}->SET_FLAGS('can-default');
1308 # $widgets->{"MessageBox-$mbno"}{'button'.$i}->can_default('1');
1309 $widgets->{"MessageBox-$mbno"}{'button'.$i}->grab_default();
1310 }
1311 $widgets->{"MessageBox-$mbno"}{'button'.$i}->show();
1312 }
1313 # $widgets->{"MessageBox-$mbno"}{'action_area1'}->set_child_packing($widgets->{"MessageBox-$mbno"}{'hbuttonbox1'}, '1', '1', '0', 'start');
1314 # $widgets->{"MessageBox-$mbno"}{'vbox1'}->set_child_packing($widgets->{"MessageBox-$mbno"}{'action_area1'}, '0', '1', '0', 'end');
1315 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->show_all();
1316 #print Dumper($widgets);
1317 return $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE};
1318 }
1319  
1320 sub message_box_close {
1321 my ($class, $dataref) = @_;
1322 my ($mbno, $button_label) = @$dataref;
1323 # Close this message_box and tidy up
1324 $widgets->{"MessageBox-$mbno"}{$WIDGET_INSTANCE}->destroy;
1325 undef $widgets->{"MessageBox-$mbno"};
1326 my $quit_string = _("Quit")." Program*"._("Quit")." Glade::Two::Generate*";
1327 if (_("*$quit_string*Quit Generate*Quit UI Build*Close Form*") =~ m/\*$button_label\*/) {
1328 Gtk2->quit;
1329 }
1330 return $dataref;
1331 }
1332  
1333 sub destroy_all_forms {
1334 my $class = shift;
1335 my $hashref = shift || $__PACKAGE__::all_forms;
1336 my $myform;
1337 foreach $myform (keys %$hashref) {
1338 $hashref->{$myform}->get_toplevel->destroy;
1339 undef $hashref->{$myform};
1340 }
1341 }
1342  
1343 #===============================================================================
1344 #=========== Utilities ============
1345 #===============================================================================
1346  
1347 =back
1348  
1349 =head1 6) GENERAL METHODS
1350  
1351 These are some general purpose methods that are useful to Glade::Two::Generate
1352 and generated apps.
1353  
1354 =over
1355  
1356 =cut
1357  
1358 sub get_time {
1359 # FIXME check that this is portable and always works
1360 # why does it give BST interactively but UTC from Glade??
1361 # $key = sprintf(" (%+03d00)", (localtime)[8]);
1362 # $key = (localtime).$key;
1363 my $time = `date`;
1364 chomp $time;
1365 return $time
1366 }
1367  
1368 sub full_Path {
1369 my ($class, $rel_path, $directory, $default) = @_;
1370 my $me = "$class->full_Path";
1371 #shift;print Dumper(\@_);
1372 =item full_Path()
1373  
1374 Turn a relative path name into an absolute path
1375  
1376 e.g. my $path = Glade::Two::Run->full_Path($relative_path, $directory);
1377  
1378 =cut
1379 my $basename;
1380 my $slash = '/';
1381 my $updir = '/\.\./';
1382 # set to $default if not defined
1383 my $fullname = $rel_path || $default || '';
1384 # add $base unless we are absolute already
1385 if ($fullname !~ /^$slash/ && defined $directory) {
1386 # We are supposed to be relative to a directory so use Cwd->chdir to
1387 # change to specified directory and Cwd->getcwd to get full path names
1388 my $save_dir = getcwd;
1389 chdir($directory);
1390 #print "cd to ".getcwd."\n";
1391 my $fulldir = getcwd;
1392 #print "getcwd thinks it is '$fulldir'\n";
1393 $fullname = "$fulldir$slash$fullname";
1394 # Now change directory to where we were on entry
1395 chdir($save_dir);
1396 #print "and back to ".getcwd."\n";
1397 } else {
1398 # Get the real path (not symlinks)
1399 my $dirname = dirname($fullname);
1400 my $basename = basename($fullname);
1401 my $save_dir = getcwd;
1402 chdir($dirname);
1403 #print "cd2 to ".getcwd."\n";
1404 my $fulldir = getcwd;
1405 #print "getcwd2 thinks it is '$fulldir'\n";
1406 $fullname = "$fulldir$slash$basename";
1407 # Now change directory to where we were on entry
1408 chdir($save_dir);
1409 #print "and back2 to ".getcwd."\n";
1410 }
1411 # Remove double //s and /./s
1412 $fullname =~ s/$slash\.?$slash/$slash/g;
1413 # Remove /../ relative directories
1414 while ($fullname =~ /$updir/) {
1415 $fullname =~ s/(.+)(?!$updir)$slash.+?$updir/$1$slash/;
1416 }
1417 # Remove trailing /s
1418 $fullname =~ s/$slash$//;
1419 #print "Converted to '$fullname'\n\n------------------------------------\n";
1420 return $fullname;
1421 }
1422  
1423 sub relative_path {
1424 my ($class, $basepath, $path, $root) = @_;
1425 my $me = __PACKAGE__."::relative_path";
1426  
1427 =item relative_Path($basepath, $path, $root)
1428  
1429 Turn an absolute path name into a relative path
1430  
1431 e.g. my $path = Glade::Two::Run->relative_Path($relative_path, $directory);
1432  
1433 =cut
1434 return $path if $path =~ /:/;
1435 my $rel;
1436 # This loop is based on code from Nicolai Langfeldt <janl@ifi.uio.no>.
1437 # First we calculate common initial path components length ($li).
1438 my $li = 1;
1439 while (1) {
1440 my $i = index($path, '/', $li);
1441 last if $i < 0 ||
1442 $i != index($basepath, '/', $li) ||
1443 substr($path,$li,$i-$li) ne substr($basepath,$li,$i-$li);
1444 $li=$i+1;
1445 }
1446 # then we nuke it from both paths
1447 substr($path, 0,$li) = '';
1448 substr($basepath,0,$li) = '';
1449  
1450 $rel = "";
1451  
1452 # Add one "../" for each path component left in the base path
1453 $path = ('../' x $basepath =~ tr|/|/|) . $path;
1454 $path = "./" if $path eq "";
1455 $rel = $path;
1456  
1457 return $rel;
1458 }
1459  
1460 sub string_from_file {&string_from_File(@_);}
1461 sub string_from_File {
1462 my ($class, $filename) = @_;
1463 my $me = __PACKAGE__."->string_from_File";
1464  
1465 =item string_from_File()
1466  
1467 Reads (slurps) a file into a string
1468  
1469 e.g. my $string = Glade::Two::Run->string_from_file('/path/to/file');
1470  
1471 =cut
1472 my $save = $/;
1473 undef $/;
1474 open INFILE, $filename or
1475 die sprintf((
1476 "error %s - can't open file '%s' for input"),
1477 $me, $filename);
1478 undef $/;
1479 my $string = <INFILE>;
1480 close INFILE;
1481 $/ = $save;
1482  
1483 return $string;
1484 }
1485  
1486 sub typeKey { return ' type'; }
1487 #sub keyFormat { if (shift) {return '%04u-%s' } else {return '%04u' } }
1488 sub keyFormat { return '%04u' }
1489  
1490 sub QuoteXMLChars {
1491 my $text = shift;
1492 # Suggested by Eric Bohlman <ebohlman@netcom.com> on perl-xml mailling list
1493 my %ents=('&'=>'amp','<'=>'lt','>'=>'gt',"'"=>'apos','"'=>'quot');
1494 $text =~ s/([&<>'"])/&$ents{$1};/g;
1495 # Uncomment the line below if you don't want to use European characters in
1496 # your project options
1497 # $text =~ s/([\x80-\xFF])/&XmlUtf8Encode(ord($1))/ge;
1498 return $text;
1499 }
1500  
1501 sub UnQuoteXMLChars {
1502 my $text = shift;
1503 my %ents=('&lt;'=>'<','&gt;'=>'>','&apos;'=>"'",'&quot;'=>'"', '&amp;'=>'&');
1504 $text =~ s/(&lt;|&gt;|&apos;|&quot;|&amp;)/$ents{$1}/g;
1505 return $text;
1506 }
1507  
1508 sub XmlUtf8Encode {
1509 # This was ripped from XML::DOM - thanks to
1510 # Enno Derksen (official maintainer), enno@att.com
1511 # and Clark Cooper, coopercl@sch.ge.com
1512 my $n = shift;
1513 my $me = "XmlUtf8Encode";
1514 if ($n < 0x80) {
1515 return chr ($n);
1516  
1517 } elsif ($n < 0x800) {
1518 return pack ("CC", (($n >> 6) | 0xc0),
1519 (($n & 0x3f) | 0x80));
1520  
1521 } elsif ($n < 0x10000) {
1522 return pack ("CCC", (($n >> 12) | 0xe0),
1523 ((($n >> 6) & 0x3f) | 0x80),
1524 (($n & 0x3f) | 0x80));
1525  
1526 } elsif ($n < 0x110000) {
1527 return pack ("CCCC", (($n >> 18) | 0xf0),
1528 ((($n >> 12) & 0x3f) | 0x80),
1529 ((($n >> 6) & 0x3f) | 0x80),
1530 (($n & 0x3f) | 0x80));
1531 }
1532 __PACKAGE__->diag_print(1,
1533 "error Number is too large for Unicode [%s] in %s ", $n, $me);
1534 return "#";
1535 }
1536  
1537 sub reload_any_altered_modules {
1538 my ($class) = @_;
1539 my $me = __PACKAGE__."->reload_any_altered_modules";
1540  
1541 =item reload_any_altered_modules()
1542  
1543 Check all loaded modules and reload any that have been altered since the
1544 app started. This saves restarting the app for every change to the signal
1545 handlers or support modules.
1546  
1547 It is impossible to reload the UI module (called something like ProjectUI.pm)
1548 while the app is running without crashing it so don't run glade2perl and then
1549 call this method.
1550 Similarly, any modules that construct objects in their
1551 own namespace will cause unpredictable failures.
1552  
1553 I usually call this in a button's signal handler so that I can edit the
1554 modules and easily reload the edited versions of modules.
1555  
1556 e.g. Glade::Two::Run->reload_any_altered_modules;
1557  
1558 =cut
1559 my $stat = \%stat;
1560 my $reloaded = 0;
1561 my ($prefix, $msg);
1562 if (ref $class) {
1563 $prefix = ($class->{diag}{indent} || $indent);
1564 } else {
1565 $prefix = $indent;
1566 }
1567 $prefix .= "- $me";
1568 while(my($key,$file) = each %INC) {
1569 local $^W = 0;
1570 my $mtime = (stat $file)[9];
1571 # warn and skip the files with relative paths which can't be
1572 # located by applying @INC;
1573 unless (defined $mtime and $mtime) {
1574 print "$prefix - Can't locate $file\n",next
1575 }
1576 unless(defined $stat->{$file}) {
1577 # First time through so log process start time
1578 $stat->{$file} = $^T;
1579 }
1580  
1581 if($mtime > $stat->{$file}) {
1582 delete $INC{$key};
1583 require $key;
1584 $reloaded++;
1585 print "$prefix - Reloading $key in process $$\n";
1586 }
1587 # Log actual stat/checked time
1588 $stat->{$file} = $mtime;
1589 }
1590 return "Reloaded $reloaded module(s) in process $$";
1591 }
1592  
1593 =back
1594  
1595 =head1 SEE ALSO
1596  
1597 Glade::Two::Generate(3) glade2perl-2(1)
1598  
1599 =head1 AUTHOR
1600  
1601 Dermot Musgrove <dermot.musgrove@virgin.net>
1602  
1603 =cut
1604  
1605 1;
1606  
1607 __END__