Debian Codegraph @

Tk/Menu.pm

raw
1 # Converted from menu.tcl --
2 #
3 # This file defines the default bindings for Tk menus and menubuttons.
4 # It also implements keyboard traversal of menus and implements a few
5 # other utility procedures related to menus.
6 #
7 # @(#) menu.tcl 1.34 94/12/19 17:09:09
8 #
9 # Copyright (c) 1992-1994 The Regents of the University of California.
10 # Copyright (c) 1994 Sun Microsystems, Inc.
11 #
12 # See the file "license.terms" for information on usage and redistribution
13 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14
15 package Tk::Menu;
16 require Tk;
17 require Tk::Widget;
18 require Tk::Wm;
19 require Tk::Derived;
20 require Tk::Menu::Item;
21
22
23 use vars qw($VERSION);
24 $VERSION = '4.023'; # was: sprintf '4.%03d', q$Revision: #21 $ =~ /\D(\d+)\s*$/;
25
26 use strict;
27
28 use base qw(Tk::Wm Tk::Derived Tk::Widget);
29
30 Construct Tk::Widget 'Menu';
31
32 sub Tk_cmd { \&Tk::_menu }
33
34 Tk::Methods('activate','add','clone','delete','entrycget','entryconfigure',
35 'index','insert','invoke','post','postcascade','type',
36 'unpost','yposition');
37
38 import Tk qw(Ev);
39
40 sub CreateArgs
41 {
42 my ($package,$parent,$args) = @_;
43 # Remove from hash %$args any configure-like
44 # options which only apply at create time (e.g. -class for Frame)
45 # return these as a list of -key => value pairs
46 my @result = ();
47 my $opt;
48 foreach $opt (qw(-type -screen -visual -colormap))
49 {
50 my $val = delete $args->{$opt};
51 push(@result, $opt => $val) if (defined $val);
52 }
53 return @result;
54 }
55
56 sub InitObject
57 {
58 my ($menu,$args) = @_;
59 my $menuitems = delete $args->{-menuitems};
60 $menu->SUPER::InitObject($args);
61 $menu->ConfigSpecs(-foreground => ['SELF']);
62 if (defined $menuitems)
63 {
64 # If any other args do configure now
65 if (%$args)
66 {
67 $menu->configure(%$args);
68 %$args = ();
69 }
70 $menu->AddItems(@$menuitems)
71 }
72 }
73
74 sub AddItems
75 {
76 my $menu = shift;
77 ITEM:
78 while (@_)
79 {
80 my $item = shift;
81 if (!ref($item))
82 {
83 $menu->separator; # A separator
84 }
85 else
86 {
87 my ($kind,$name,%minfo) = ( @$item );
88 my $invoke = delete $minfo{'-invoke'};
89 if (defined $name)
90 {
91 $minfo{-label} = $name unless defined($minfo{-label});
92 $menu->$kind(%minfo);
93 }
94 else
95 {
96 $menu->BackTrace("Don't recognize " . join(' ',@$item));
97 }
98 } # A non-separator
99 }
100 }
101
102 #
103 #-------------------------------------------------------------------------
104 # Elements of tkPriv that are used in this file:
105 #
106 # cursor - Saves the -cursor option for the posted menubutton.
107 # focus - Saves the focus during a menu selection operation.
108 # Focus gets restored here when the menu is unposted.
109 # inMenubutton - The name of the menubutton widget containing
110 # the mouse, or an empty string if the mouse is
111 # not over any menubutton.
112 # popup - If a menu has been popped up via tk_popup, this
113 # gives the name of the menu. Otherwise this
114 # value is empty.
115 # postedMb - Name of the menubutton whose menu is currently
116 # posted, or an empty string if nothing is posted
117 # A grab is set on this widget.
118 # relief - Used to save the original relief of the current
119 # menubutton.
120 # window - When the mouse is over a menu, this holds the
121 # name of the menu; it's cleared when the mouse
122 # leaves the menu.
123 #-------------------------------------------------------------------------
124 #-------------------------------------------------------------------------
125 # Overall note:
126 # This file is tricky because there are four different ways that menus
127 # can be used:
128 #
129 # 1. As a pulldown from a menubutton. This is the most common usage.
130 # In this style, the variable tkPriv(postedMb) identifies the posted
131 # menubutton.
132 # 2. As a torn-off menu copied from some other menu. In this style
133 # tkPriv(postedMb) is empty, and the top-level menu is no
134 # override-redirect.
135 # 3. As an option menu, triggered from an option menubutton. In thi
136 # style tkPriv(postedMb) identifies the posted menubutton.
137 # 4. As a popup menu. In this style tkPriv(postedMb) is empty and
138 # the top-level menu is override-redirect.
139 #
140 # The various binding procedures use the state described above to
141 # distinguish the various cases and take different actions in each
142 # case.
143 #-------------------------------------------------------------------------
144 # Bind --
145 # This procedure is invoked the first time the mouse enters a menubutton
146 # widget or a menubutton widget receives the input focus. It creates
147 # all of the class bindings for both menubuttons and menus.
148 #
149 # Arguments:
150 # w - The widget that was just entered or just received
151 # the input focus.
152 # event - Indicates which event caused the procedure to be invoked
153 # (Enter or FocusIn). It is used so that we can carry out
154 # the functions of that event in addition to setting up
155 # bindings.
156 sub ClassInit
157 {
158 my ($class,$mw) = @_;
159 # Must set focus when mouse enters a menu, in order to allow
160 # mixed-mode processing using both the mouse and the keyboard.
161 $mw->bind($class,'<FocusIn>', 'NoOp');
162 $mw->bind($class,'<Enter>', 'Enter');
163 $mw->bind($class,'<Leave>', ['Leave',Ev('X'),Ev('Y'),Ev('s')]);
164 $mw->bind($class,'<Motion>', ['Motion',Ev('x'),Ev('y'),Ev('s')]);
165 $mw->bind($class,'<ButtonPress>','ButtonDown');
166 $mw->bind($class,'<ButtonRelease>',['Invoke',1]);
167 $mw->bind($class,'<space>',['Invoke',0]);
168 $mw->bind($class,'<Return>',['Invoke',0]);
169 $mw->bind($class,'<Escape>','Escape');
170 $mw->bind($class,'<Left>','LeftArrow');
171 $mw->bind($class,'<Right>','RightArrow');
172 $mw->bind($class,'<Up>','UpArrow');
173 $mw->bind($class,'<Down>','DownArrow');
174 $mw->bind($class,'<KeyPress>', ['TraverseWithinMenu',Ev('K')]);
175 $mw->bind($class,'<Alt-KeyPress>', ['TraverseWithinMenu',Ev('K')]);
176 return $class;
177 }
178
179 sub UpArrow
180 {
181 my $menu = shift;
182 if ($menu->cget('-type') eq 'menubar')
183 {
184 $menu->NextMenu('left');
185 }
186 else
187 {
188 $menu->NextEntry(-1);
189 }
190 }
191
192 sub DownArrow
193 {
194 my $menu = shift;
195 if ($menu->cget('-type') eq 'menubar')
196 {
197 $menu->NextMenu('right');
198 }
199 else
200 {
201 $menu->NextEntry(1);
202 }
203 }
204
205 sub LeftArrow
206 {
207 my $menu = shift;
208 if ($menu->cget('-type') eq 'menubar')
209 {
210 $menu->NextEntry(-1);
211 }
212 else
213 {
214 $menu->NextMenu('left');
215 }
216 }
217
218 sub RightArrow
219 {
220 my $menu = shift;
221 if ($menu->cget('-type') eq 'menubar')
222 {
223 $menu->NextEntry(1);
224 }
225 else
226 {
227 $menu->NextMenu('right');
228 }
229 }
230
231
232
233 # Unpost --
234 # This procedure unposts a given menu, plus all of its ancestors up
235 # to (and including) a menubutton, if any. It also restores various
236 # values to what they were before the menu was posted, and releases
237 # a grab if there's a menubutton involved. Special notes:
238 # 1. It's important to unpost all menus before releasing the grab, so
239 # that any Enter-Leave events (e.g. from menu back to main
240 # application) have mode NotifyGrab.
241 # 2. Be sure to enclose various groups of commands in "catch" so that
242 # the procedure will complete even if the menubutton or the menu
243 # or the grab window has been deleted.
244 #
245 # Arguments:
246 # menu - Name of a menu to unpost. Ignored if there
247 # is a posted menubutton.
248 sub Unpost
249 {
250 my $menu = shift;
251 my $mb = $Tk::postedMb;
252
253 # Restore focus right away (otherwise X will take focus away when
254 # the menu is unmapped and under some window managers (e.g. olvwm)
255 # we'll lose the focus completely).
256
257 eval {local $SIG{__DIE__}; $Tk::focus->focus() } if (defined $Tk::focus);
258 undef $Tk::focus;
259
260 # Unpost menu(s) and restore some stuff that's dependent on
261 # what was posted.
262 eval {local $SIG{__DIE__};
263 if (defined $mb)
264 {
265 $menu = $mb->cget('-menu');
266 $menu->unpost();
267 $Tk::postedMb = undef;
268 $mb->configure('-cursor',$Tk::cursor);
269 $mb->configure('-relief',$Tk::relief)
270 }
271 elsif (defined $Tk::popup)
272 {
273 $Tk::popup->unpost();
274 my $grab = $Tk::popup->grabCurrent;
275 $grab->grabRelease if (defined $grab);
276
277 undef $Tk::popup;
278 }
279 elsif (defined $menu && ref $menu &&
280 $menu->cget('-type') ne 'menubar' &&
281 $menu->cget('-type') ne 'tearoff'
282 )
283 {
284 # We're in a cascaded sub-menu from a torn-off menu or popup.
285 # Unpost all the menus up to the toplevel one (but not
286 # including the top-level torn-off one) and deactivate the
287 # top-level torn off menu if there is one.
288 while (1)
289 {
290 my $parent = $menu->parent;
291 last if (!$parent->IsMenu || !$parent->ismapped);
292 $parent->postcascade('none');
293 $parent->GenerateMenuSelect;
294 $parent->activate('none');
295 my $type = $parent->cget('-type');
296 last if ($type eq 'menubar' || $type eq 'tearoff');
297 $menu = $parent
298 }
299 $menu->unpost() if ($menu->cget('-type') ne 'menubar');
300 }
301 };
302 warn "$@" if ($@);
303 if ($Tk::tearoff || $Tk::menubar)
304 {
305 # Release grab, if any.
306 if (defined $menu && ref $menu)
307 {
308 my $grab = $menu->grabCurrent;
309 $grab->grabRelease if (defined $grab);
310 }
311 RestoreOldGrab();
312 if ($Tk::menubar)
313 {
314 $Tk::menubar->configure(-cursor => $Tk::cursor);
315 undef $Tk::menubar;
316 }
317 if ($Tk::platform ne 'unix')
318 {
319 undef $Tk::tearoff;
320 }
321 }
322 }
323
324 sub RestoreOldGrab
325 {
326 if (defined $Tk::oldGrab)
327 {
328 eval
329 {
330 local $SIG{__DIE__};
331 if ($Tk::grabStatus eq 'global')
332 {
333 $Tk::oldGrab->grabGlobal;
334 }
335 else
336 {
337 $Tk::oldGrab->grab;
338 }
339 };
340 undef $Tk::oldGrab;
341 }
342 }
343
344 sub typeIS
345 {my $w = shift;
346 my $type = $w->type(shift);
347 return defined $type && $type eq shift;
348 }
349
350 # Motion --
351 # This procedure is called to handle mouse motion events for menus.
352 # It does two things. First, it resets the active element in the
353 # menu, if the mouse is over the menu. Second, if a mouse button
354 # is down, it posts and unposts cascade entries to match the mouse
355 # position.
356 #
357 # Arguments:
358 # menu - The menu window.
359 # y - The y position of the mouse.
360 # state - Modifier state (tells whether buttons are down).
361 sub Motion
362 {
363 my $menu = shift;
364 my $x = shift;
365 my $y = shift;
366 my $state = shift;
367 my $t = $menu->cget('-type');
368
369 if ($menu->IS($Tk::window))
370 {
371 if ($menu->cget('-type') eq 'menubar')
372 {
373 # if (defined($Tk::focus) && $Tk::focus != $menu)
374 {
375 $menu->activate("\@$x,$y");
376 $menu->GenerateMenuSelect;
377 }
378 }
379 else
380 {
381 $menu->activate("\@$x,$y");
382 $menu->GenerateMenuSelect;
383 }
384 }
385 if (($state & 0x1f00) != 0)
386 {
387 $menu->postcascade('active')
388 }
389 }
390 # ButtonDown --
391 # Handles button presses in menus. There are a couple of tricky things
392 # here:
393 # 1. Change the posted cascade entry (if any) to match the mouse position.
394 # 2. If there is a posted menubutton, must grab to the menubutton so
395 # that it can track mouse motions over other menubuttons and change
396 # the posted menu.
397 # 3. If there's no posted menubutton (e.g. because we're a torn-off menu
398 # or one of its descendants) must grab to the top-level menu so that
399 # we can track mouse motions across the entire menu hierarchy.
400
401 #
402 # Arguments:
403 # menu - The menu window.
404 sub ButtonDown
405 {
406 my $menu = shift;
407 return if (!$menu->viewable);
408 $menu->postcascade('active');
409 if (defined $Tk::postedMb && $Tk::postedMb->viewable)
410 {
411 $Tk::postedMb->grabGlobal
412 }
413 else
414 {
415 while ($menu->cget('-type') eq 'normal'
416 && $menu->parent->IsMenu
417 && $menu->parent->ismapped
418 )
419 {
420 $menu = $menu->parent;
421 }
422
423 if (!defined $Tk::menuBar)
424 {
425 $Tk::menuBar = $menu;
426 $Tk::cursor = $menu->cget('-cursor');
427 $menu->configure(-cursor => 'arrow');
428 }
429
430 # Don't update grab information if the grab window isn't changing.
431 # Otherwise, we'll get an error when we unpost the menus and
432 # restore the grab, since the old grab window will not be viewable
433 # anymore.
434
435 $menu->SaveGrabInfo unless ($menu->IS($menu->grabCurrent));
436
437 # Must re-grab even if the grab window hasn't changed, in order
438 # to release the implicit grab from the button press.
439
440 $menu->grabGlobal if ($Tk::platform eq 'unix');
441 }
442 }
443
444 sub Enter
445 {
446 my $w = shift;
447 my $ev = $w->XEvent;
448 $Tk::window = $w;
449 if ($w->cget('-type') eq 'tearoff')
450 {
451 if ($ev->m ne 'NotifyUngrab')
452 {
453 $w->SetFocus if ($Tk::platform eq 'unix');
454 }
455 }
456 $w->Motion($ev->x, $ev->y, $ev->s);
457 }
458
459 # Leave --
460 # This procedure is invoked to handle Leave events for a menu. It
461 # deactivates everything unless the active element is a cascade element
462 # and the mouse is now over the submenu.
463 #
464 # Arguments:
465 # menu - The menu window.
466 # rootx, rooty - Root coordinates of mouse.
467 # state - Modifier state.
468 sub Leave
469 {
470 my $menu = shift;
471 my $rootx = shift;
472 my $rooty = shift;
473 my $state = shift;
474 undef $Tk::window;
475 return if ($menu->index('active') eq 'none');
476 if ($menu->typeIS('active','cascade'))
477 {
478 my $c = $menu->Containing($rootx,$rooty);
479 return if (defined $c && $menu->entrycget('active','-menu')->IS($c));
480 }
481 $menu->activate('none');
482 $menu->GenerateMenuSelect;
483 }
484
485 # Invoke --
486 # This procedure is invoked when button 1 is released over a menu.
487 # It invokes the appropriate menu action and unposts the menu if
488 # it came from a menubutton.
489 #
490 # Arguments:
491 # w - Name of the menu widget.
492 sub Invoke
493 {
494 my $w = shift;
495 my $release = shift;
496
497 if ($release && !defined($Tk::window))
498 {
499 # Mouse was pressed over a menu without a menu button, then
500 # dragged off the menu (possibly with a cascade posted) and
501 # released. Unpost everything and quit.
502
503 $w->postcascade('none');
504 $w->activate('none');
505 $w->eventGenerate('<<MenuSelect>>');
506 $w->Unpost;
507 return;
508 }
509
510 my $type = $w->type('active');
511 if ($w->typeIS('active','cascade'))
512 {
513 $w->postcascade('active');
514 my $menu = $w->entrycget('active','-menu');
515 $menu->FirstEntry() if (defined $menu);
516 }
517 elsif ($w->typeIS('active','tearoff'))
518 {
519 $w->tearOffMenu();
520 $w->Unpost();
521 }
522 elsif ($w->typeIS('active','menubar'))
523 {
524 $w->postcascade('none');
525 $w->activate('none');
526 $w->eventGenerate('<<MenuSelect>>');
527 $w->Unpost;
528 }
529 else
530 {
531 $w->Unpost();
532 $w->invoke('active')
533 }
534 }
535 # Escape --
536 # This procedure is invoked for the Cancel (or Escape) key. It unposts
537 # the given menu and, if it is the top-level menu for a menu button,
538 # unposts the menu button as well.
539 #
540 # Arguments:
541 # menu - Name of the menu window.
542 sub Escape
543 {
544 my $menu = shift;
545 my $parent = $menu->parent;
546 if (!$parent->IsMenu)
547 {
548 $menu->Unpost()
549 }
550 elsif ($parent->cget('-type') eq 'menubar')
551 {
552 $menu->Unpost;
553 RestoreOldGrab();
554 }
555 else
556 {
557 $menu->NextMenu(-1)
558 }
559 }
560 # LeftRight --
561 # This procedure is invoked to handle "left" and "right" traversal
562 # motions in menus. It traverses to the next menu in a menu bar,
563 # or into or out of a cascaded menu.
564 #
565 # Arguments:
566 # menu - The menu that received the keyboard
567 # event.
568 # direction - Direction in which to move: "left" or "right"
569 sub NextMenu
570 {
571 my $menu = shift;
572 my $direction = shift;
573 # First handle traversals into and out of cascaded menus.
574 my $count;
575 if ($direction eq 'right')
576 {
577 $count = 1;
578 if ($menu->typeIS('active','cascade'))
579 {
580 $menu->postcascade('active');
581 my $m2 = $menu->entrycget('active','-menu');
582 $m2->FirstEntry if (defined $m2);
583 return;
584 }
585 else
586 {
587 my $parent = $menu->parent;
588 while ($parent->PathName ne '.')
589 {
590 if ($parent->IsMenu && $parent->cget('-type') eq 'menubar')
591 {
592 $parent->SetFocus;
593 $parent->NextEntry(1);
594 return;
595 }
596 $parent = $parent->parent;
597 }
598 }
599 }
600 else
601 {
602 $count = -1;
603 my $m2 = $menu->parent;
604 if ($m2->IsMenu)
605 {
606 $menu->activate('none');
607 $menu->GenerateMenuSelect;
608 $m2->SetFocus;
609
610 $m2->postcascade('none');
611
612 if ($m2->cget('-type') ne 'menubar')
613 {
614 return;
615 }
616 }
617 }
618 # Can't traverse into or out of a cascaded menu. Go to the next
619 # or previous menubutton, if that makes sense.
620
621 my $m2 = $menu->parent;
622 if ($m2->IsMenu)
623 {
624 if ($m2->cget('-type') eq 'menubar')
625 {
626 $m2->SetFocus;
627 $m2->NextEntry(-1);
628 return;
629 }
630 }
631
632 my $w = $Tk::postedMb;
633 return unless defined $w;
634 my @buttons = $w->parent->children;
635 my $length = @buttons;
636 my $i = Tk::lsearch(\@buttons,$w)+$count;
637 my $mb;
638 while (1)
639 {
640 while ($i < 0)
641 {
642 $i += $length
643 }
644 while ($i >= $length)
645 {
646 $i += -$length
647 }
648 $mb = $buttons[$i];
649 last if ($mb->IsMenubutton && $mb->cget('-state') ne 'disabled'
650 && defined($mb->cget('-menu'))
651 && $mb->cget('-menu')->index('last') ne 'none'
652 );
653 return if ($mb == $w);
654 $i += $count
655 }
656 $mb->PostFirst();
657 }
658 # NextEntry --
659 # Activate the next higher or lower entry in the posted menu,
660 # wrapping around at the ends. Disabled entries are skipped.
661 #
662 # Arguments:
663 # menu - Menu window that received the keystroke.
664 # count - 1 means go to the next lower entry,
665 # -1 means go to the next higher entry.
666 sub NextEntry
667 {
668 my $menu = shift;
669 my $count = shift;
670 if ($menu->index('last') eq 'none')
671 {
672 return;
673 }
674 my $length = $menu->index('last')+1;
675 my $quitAfter = $length;
676 my $active = $menu->index('active');
677 my $i = ($active eq 'none') ? 0 : $active+$count;
678 while (1)
679 {
680 return if ($quitAfter <= 0);
681 while ($i < 0)
682 {
683 $i += $length
684 }
685 while ($i >= $length)
686 {
687 $i += -$length
688 }
689 my $state = eval {local $SIG{__DIE__}; $menu->entrycget($i,'-state') };
690 last if (defined($state) && $state ne 'disabled');
691 return if ($i == $active);
692 $i += $count;
693 $quitAfter -= 1;
694 }
695 $menu->activate($i);
696 $menu->GenerateMenuSelect;
697 if ($menu->cget('-type') eq 'menubar' && $menu->type($i) eq 'cascade')
698 {
699 my $cascade = $menu->entrycget($i, '-menu');
700 $menu->postcascade($i);
701 $cascade->FirstEntry if (defined $cascade);
702 }
703 }
704
705
706 # tkTraverseWithinMenu
707 # This procedure implements keyboard traversal within a menu. It
708 # searches for an entry in the menu that has "char" underlined. If
709 # such an entry is found, it is invoked and the menu is unposted.
710 #
711 # Arguments:
712 # w - The name of the menu widget.
713 # char - The character to look for; case is
714 # ignored. If the string is empty then
715 # nothing happens.
716 sub TraverseWithinMenu
717 {
718 my $w = shift;
719 my $char = shift;
720 return unless (defined $char);
721 $char = "\L$char";
722 my $last = $w->index('last');
723 return if ($last eq 'none');
724 for (my $i = 0;$i <= $last;$i += 1)
725 {
726 my $label = eval {local $SIG{__DIE__}; $w->entrycget($i,'-label') };
727 next unless defined($label);
728 my $ul = $w->entrycget($i,'-underline');
729 if (defined $ul && $ul >= 0)
730 {
731 $label = substr("\L$label",$ul,1);
732 if (defined($label) && $label eq $char)
733 {
734 if ($w->type($i) eq 'cascade')
735 {
736 $w->postcascade($i);
737 $w->activate($i);
738 my $m2 = $w->entrycget($i,'-menu');
739 $m2->FirstEntry if (defined $m2);
740 }
741 else
742 {
743 $w->Unpost();
744 $w->invoke($i);
745 }
746 return;
747 }
748 }
749 }
750 }
751
752 sub FindMenu
753 {
754 my ($menu,$char) = @_;
755 if ($menu->cget('-type') eq 'menubar')
756 {
757 if (!defined($char) || $char eq '')
758 {
759 $menu->FirstEntry;
760 }
761 else
762 {
763 $menu->TraverseWithinMenu($char);
764 }
765 return $menu;
766 }
767 return undef;
768 }
769
770
771 # FirstEntry --
772 # Given a menu, this procedure finds the first entry that isn't
773 # disabled or a tear-off or separator, and activates that entry.
774 # However, if there is already an active entry in the menu (e.g.,
775 # because of a previous call to tkPostOverPoint) then the active
776 # entry isn't changed. This procedure also sets the input focus
777 # to the menu.
778 #
779 # Arguments:
780 # menu - Name of the menu window (possibly empty).
781 sub FirstEntry
782 {
783 my $menu = shift;
784 return if (!defined($menu) || $menu eq '' || !ref($menu));
785 $menu->SetFocus;
786 return if ($menu->index('active') ne 'none');
787 my $last = $menu->index('last');
788 return if ($last eq 'none');
789 for (my $i = 0;$i <= $last;$i += 1)
790 {
791 my $state = eval {local $SIG{__DIE__}; $menu->entrycget($i,'-state') };
792 if (defined $state && $state ne 'disabled' && !$menu->typeIS($i,'tearoff'))
793 {
794 $menu->activate($i);
795 $menu->GenerateMenuSelect;
796 if ($menu->type($i) eq 'cascade')
797 {
798 my $cascade = $menu->entrycget($i,'-menu');
799 if (0 && defined $cascade)
800 {
801 $menu->postcascade($i);
802 $cascade->FirstEntry;
803 }
804 }
805 return;
806 }
807 }
808 }
809
810 # FindName --
811 # Given a menu and a text string, return the index of the menu entry
812 # that displays the string as its label. If there is no such entry,
813 # return an empty string. This procedure is tricky because some names
814 # like "active" have a special meaning in menu commands, so we can't
815 # always use the "index" widget command.
816 #
817 # Arguments:
818 # menu - Name of the menu widget.
819 # s - String to look for.
820 sub FindName
821 {
822 my $menu = shift;
823 my $s = shift;
824 my $i = undef;
825 if ($s !~ /^active$|^last$|^none$|^[0-9]|^@/)
826 {
827 $i = eval {local $SIG{__DIE__}; $menu->index($s) };
828 return $i;
829 }
830 my $last = $menu->index('last');
831 return if ($last eq 'none');
832 for ($i = 0;$i <= $last;$i += 1)
833 {
834 my $label = eval {local $SIG{__DIE__}; $menu->entrycget($i,'-label') };
835 return $i if (defined $label && $label eq $s);
836 }
837 return undef;
838 }
839 # PostOverPoint --
840 # This procedure posts a given menu such that a given entry in the
841 # menu is centered over a given point in the root window. It also
842 # activates the given entry.
843 #
844 # Arguments:
845 # menu - Menu to post.
846 # x, y - Root coordinates of point.
847 # entry - Index of entry within menu to center over (x,y).
848 # If omitted or specified as {}, then the menu's
849 # upper-left corner goes at (x,y).
850 sub PostOverPoint
851 {
852 my $menu = shift;
853 my $x = shift;
854 my $y = shift;
855 my $entry = shift;
856 if (defined $entry)
857 {
858 if ($entry == $menu->index('last'))
859 {
860 $y -= ($menu->yposition($entry)+$menu->height)/2;
861 }
862 else
863 {
864 $y -= ($menu->yposition($entry)+$menu->yposition($entry+1))/2;
865 }
866 $x -= $menu->reqwidth/2;
867 }
868 $menu->post($x,$y);
869 if (defined($entry) && $menu->entrycget($entry,'-state') ne 'disabled')
870 {
871 $menu->activate($entry);
872 $menu->GenerateMenuSelect;
873 }
874 }
875 # tk_popup --
876 # This procedure pops up a menu and sets things up for traversing
877 # the menu and its submenus.
878 #
879 # Arguments:
880 # menu - Name of the menu to be popped up.
881 # x, y - Root coordinates at which to pop up the
882 # menu.
883 # entry - Index of a menu entry to center over (x,y).
884 # If omitted or specified as {}, then menu's
885 # upper-left corner goes at (x,y).
886 sub Post
887 {
888 my $menu = shift;
889 return unless (defined $menu);
890 my $x = shift;
891 my $y = shift;
892 my $entry = shift;
893 Unpost(undef) if (defined($Tk::popup) || defined($Tk::postedMb));
894 $menu->PostOverPoint($x,$y,$entry);
895 if ($Tk::platform eq 'unix' && $menu->viewable)
896 {
897 $menu->grabGlobal;
898 $Tk::popup = $menu;
899 $Tk::focus = $menu->focusCurrent;
900 $menu->focus();
901 }
902 }
903
904 sub SetFocus
905 {
906 my $menu = shift;
907 $Tk::focus = $menu->focusCurrent if (!defined($Tk::focus));
908 $menu->focus;
909 }
910
911 sub GenerateMenuSelect
912 {
913 my $menu = shift;
914 $Tk::activeMenu = $menu;
915 $Tk::activeItem = $menu->index('active');
916 $menu->eventGenerate('<<MenuSelect>>'); # FIXME
917 }
918
919 # Converted from tearoff.tcl --
920 #
921 # This file contains procedures that implement tear-off menus.
922 #
923 # @(#) tearoff.tcl 1.3 94/12/17 16:05:25
924 #
925 # Copyright (c) 1994 The Regents of the University of California.
926 # Copyright (c) 1994 Sun Microsystems, Inc.
927 #
928 # See the file "license.terms" for information on usage and redistribution
929 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
930 #
931 # tkTearoffMenu --
932 # Given the name of a menu, this procedure creates a torn-off menu
933 # that is identical to the given menu (including nested submenus).
934 # The new torn-off menu exists as a toplevel window managed by the
935 # window manager. The return value is the name of the new menu.
936 #
937 # Arguments:
938 # w - The menu to be torn-off (duplicated).
939 sub tearOffMenu
940 {
941 my $w = shift;
942 my $x = (@_) ? shift : 0;
943 my $y = (@_) ? shift : 0;
944
945 $x = $w->rootx if $x == 0;
946 $y = $w->rooty if $y == 0;
947
948 # Find a unique name to use for the torn-off menu. Find the first
949 # ancestor of w that is a toplevel but not a menu, and use this as
950 # the parent of the new menu. This guarantees that the torn off
951 # menu will be on the same screen as the original menu. By making
952 # it a child of the ancestor, rather than a child of the menu, it
953 # can continue to live even if the menu is deleted; it will go
954 # away when the toplevel goes away.
955
956 my $parent = $w->parent;
957 while ($parent->toplevel != $parent || $parent->IsMenu)
958 {
959 $parent = $parent->parent;
960 }
961 my $menu = $w->clone($parent->PathName,'tearoff');
962
963 # Pick a title for the new menu by looking at the parent of the
964 # original: if the parent is a menu, then use the text of the active
965 # entry. If it's a menubutton then use its text.
966 my $title = $w->cget('-title');
967 # print ref($w),' ',$w->PathName," ",$menu->PathName," $w\n";
968 unless (defined $title && length($title))
969 {
970 $parent = $w->parent;
971 if ($parent)
972 {
973 if ($parent->IsMenubutton)
974 {
975 $title = $parent->cget('-text');
976 }
977 elsif ($parent->IsMenu)
978 {
979 $title = $parent->entrycget('active','-label');
980 }
981 }
982 }
983 $menu->title($title) if (defined $title && length($title));
984 $menu->post($x,$y);
985
986 if (!Tk::Exists($menu))
987 {
988 return;
989 }
990
991 # Set tkPriv(focus) on entry: otherwise the focus will get lost
992 # after keyboard invocation of a sub-menu (it will stay on the
993 # submenu).
994
995
996 # This seems to conflict with <Enter> class binding above
997 # if this fires before the class binding the wrong thing
998 # will get saved in $Tk::focus
999 # $menu->bind('<Enter>','EnterFocus');
1000 $menu->Callback('-tearoffcommand');
1001
1002 # Strangely tear-off menus do not work in tkpod and Tk804.027.
1003 # Explicitely setting normal state helps here - why?
1004 $menu->state("normal");
1005
1006 return $menu;
1007 }
1008
1009 # tkMenuDup --
1010 # Given a menu (hierarchy), create a duplicate menu (hierarchy)
1011 # in a given window.
1012 #
1013 # Arguments:
1014 # src - Source window. Must be a menu. It and its
1015 # menu descendants will be duplicated at path.
1016 # path - Name to use for topmost menu in duplicate
1017 # hierarchy.
1018
1019 sub tkMenuDup
1020 {
1021 my ($src,$path,$type) = @_;
1022 my ($pname,$name) = $path =~ /^(.*)\.([^\.]*)$/;
1023 ($name) = $src->PathName =~ /^.*\.([^\.]*)$/ unless $name;
1024 my $parent = ($pname) ? $src->Widget($pname) : $src->MainWindow;
1025 my %args = (Name => $name, -type => $type);
1026 foreach my $option ($src->configure())
1027 {
1028 next if (@$option == 2);
1029 $args{$$option[0]} = $$option[4] unless exists $args{$$option[0]};
1030 }
1031 my $dst = ref($src)->new($parent,%args);
1032 # print "MenuDup $src $path $name $type ->",$dst->PathName,"\n";
1033 $_[1] = $dst;
1034 if ($type eq 'tearoff')
1035 {
1036 $dst->transient($parent->toplevel);
1037 }
1038 my $last = $src->index('last');
1039 if ($last ne 'none')
1040 {
1041 for (my $i = $src->cget('-tearoff'); $i <= $last; $i++)
1042 {
1043 my $type = $src->type($i);
1044 if (defined $type)
1045 {
1046 my @args = ();
1047 foreach my $option ($src->entryconfigure($i))
1048 {
1049 next if (@$option == 2);
1050 push(@args,$$option[0],$$option[4]) if (defined $$option[4]);
1051 }
1052 $dst->add($type,@args);
1053 }
1054 }
1055 }
1056 # Duplicate the binding tags and bindings from the source menu.
1057 my @bindtags = $src->bindtags;
1058 $path = $src->PathName;
1059 foreach (@bindtags)
1060 {
1061 $_ = $dst if ($_ eq $path);
1062 }
1063 $dst->bindtags([@bindtags]);
1064 foreach my $event ($src->bind)
1065 {
1066 my $cb = $src->bind($event);
1067 # print "$event => $cb\n";
1068 $dst->bind($event,$cb->Substitute($src,$dst));
1069 }
1070 return $dst;
1071 }
1072
1073
1074
1075 # Some convenience methods
1076
1077 sub separator { require Tk::Menu::Item; shift->Separator(@_); }
1078 sub cascade { require Tk::Menu::Item; shift->Cascade(@_); }
1079 sub checkbutton { require Tk::Menu::Item; shift->Checkbutton(@_); }
1080 sub radiobutton { require Tk::Menu::Item; shift->Radiobutton(@_); }
1081
1082 sub command
1083 {
1084 my ($menu,%args) = @_;
1085 require Tk::Menu::Item;
1086 if (exists $args{-button})
1087 {
1088 # Backward compatible stuff from 'Menubar'
1089 my $button = delete $args{-button};
1090 $button = ['Misc', -underline => 0 ] unless (defined $button);
1091 my @bargs = ();
1092 ($button,@bargs) = @$button if (ref($button) && ref $button eq 'ARRAY');
1093 $menu = $menu->Menubutton(-label => $button, @bargs);
1094 }
1095 $menu->Command(%args);
1096 }
1097
1098 sub Menubutton
1099 {
1100 my ($menu,%args) = @_;
1101 my $name = delete($args{'-text'}) || $args{'-label'};;
1102 $args{'-label'} = $name if (defined $name);
1103 my $items = delete $args{'-menuitems'};
1104 foreach my $opt (qw(-pack -after -before -side -padx -ipadx -pady -ipady -fill))
1105 {
1106 delete $args{$opt};
1107 }
1108 if (defined($name) && !defined($args{-underline}))
1109 {
1110 my $underline = ($name =~ s/^(.*)~/$1/) ? length($1): undef;
1111 if (defined($underline) && ($underline >= 0))
1112 {
1113 $args{-underline} = $underline;
1114 $args{-label} = $name;
1115 }
1116 }
1117 my $hash = $menu->TkHash('MenuButtons');
1118 my $mb = $hash->{$name};
1119 if (defined $mb)
1120 {
1121 delete $args{'-tearoff'}; # too late!
1122 $mb->configure(%args) if %args;
1123 }
1124 else
1125 {
1126 $mb = $menu->cascade(%args);
1127 $hash->{$name} = $mb;
1128 }
1129 $mb->menu->AddItems(@$items) if defined($items) && @$items;
1130 return $mb;
1131 }
1132
1133 sub BalloonInfo
1134 {
1135 my ($menu,$balloon,$X,$Y,@opt) = @_;
1136 my $i = $menu->index('active');
1137 if ($i eq 'none')
1138 {
1139 my $y = $Y - $menu->rooty;
1140 $i = $menu->index("\@$y");
1141 }
1142 foreach my $opt (@opt)
1143 {
1144 my $info = $balloon->GetOption($opt,$menu);
1145 if ($opt =~ /^-(statusmsg|balloonmsg)$/ && UNIVERSAL::isa($info,'ARRAY'))
1146 {
1147 $balloon->Subclient($i);
1148 return '' if $i eq 'none';
1149 return ${$info}[$i] || '';
1150 }
1151 return $info;
1152 }
1153 }
1154
1155 sub MasterMenu
1156 {
1157 my ($menu) = @_;
1158 my $pathname = $menu->PathName;
1159 my $master_menu;
1160 if ($pathname =~ m{#})
1161 {
1162 my $master_pathname = (split m{\.}, $pathname)[-1];
1163 $master_pathname =~ s{#}{.}g;
1164 $master_menu = $menu->Widget($master_pathname);
1165 if (0 && !Tk::Exists($master_menu))
1166 {
1167 warn "Cannot find master menu <$master_pathname>";
1168 }
1169 }
1170 $master_menu;
1171 }
1172
1173
1174 # ::tk::AmpMenuArgs --
1175 # Processes arguments for a menu entry, turning -label option into
1176 # -label and -underline options, returned by ::tk::UnderlineAmpersand.
1177 #
1178 sub AmpArgs
1179 {
1180 my ($w, $add, $type, %args) = @_;
1181 my @options;
1182 while(my($opt,$val) = each %args)
1183 {
1184 if ($opt eq "-label")
1185 {
1186 my ($newtext,$under) = $w->UnderlineAmpersand($val);
1187 push @options, -label => $newtext, -underline => $under;
1188 }
1189 else
1190 {
1191 push @options, $opt, $val;
1192 }
1193 }
1194 $w->$type(@options);
1195 }
1196
1197 1;
1198
1199 __END__
1200
1201