KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > commands > ws > CommandContributionItem


1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.internal.commands.ws;
12
13 import java.net.MalformedURLException JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.Map JavaDoc;
18
19 import org.eclipse.core.runtime.Platform;
20 import org.eclipse.jface.action.ContributionItem;
21 import org.eclipse.jface.action.ExternalActionManager;
22 import org.eclipse.jface.action.IContributionManagerOverrides;
23 import org.eclipse.jface.resource.ImageDescriptor;
24 import org.eclipse.swt.SWT;
25 import org.eclipse.swt.events.HelpListener;
26 import org.eclipse.swt.graphics.Image;
27 import org.eclipse.swt.widgets.Button;
28 import org.eclipse.swt.widgets.Composite;
29 import org.eclipse.swt.widgets.Display;
30 import org.eclipse.swt.widgets.Event;
31 import org.eclipse.swt.widgets.Listener;
32 import org.eclipse.swt.widgets.Menu;
33 import org.eclipse.swt.widgets.MenuItem;
34 import org.eclipse.swt.widgets.ToolBar;
35 import org.eclipse.swt.widgets.ToolItem;
36 import org.eclipse.swt.widgets.Widget;
37 import org.eclipse.ui.commands.CommandEvent;
38 import org.eclipse.ui.commands.ICommand;
39 import org.eclipse.ui.commands.ICommandListener;
40 import org.eclipse.ui.commands.NotDefinedException;
41 import org.eclipse.ui.commands.NotHandledException;
42 import org.eclipse.ui.help.WorkbenchHelp;
43
44 /**
45  * <p>
46  * A contribution item which delegates to a command. This is a contribution
47  * item that just passes as much of the complexity as it can on to the
48  * underlying command.
49  * </p>
50  * <p>
51  * This class may be instantiated; it is not intended to be subclassed.
52  * </p>
53  *
54  * @since 3.0
55  */

56 public class CommandContributionItem
57     extends ContributionItem
58     implements ICommandListener {
59
60     /**
61      * A cache of images loaded by the command contribution item.
62      */

63     private static class ImageCache {
64         /**
65          * An entry in the cache for tracking images.
66          */

67         private class Entry {
68             /** The greyed representation of the image. */
69             Image grayImage;
70             /** The plain image (unmodified). */
71             Image image;
72
73             /** Disposes this entry by releasing its native resources, if any. */
74             void dispose() {
75                 if (image != null) {
76                     image.dispose();
77                     image = null;
78                 }
79
80                 if (grayImage != null) {
81                     grayImage.dispose();
82                     grayImage = null;
83                 }
84             }
85         }
86
87         /** Map from ImageDescriptor to Entry */
88         private Map JavaDoc entries = new HashMap JavaDoc(11);
89         /** The image used to represent an image that is not available. */
90         private Image missingImage;
91
92         /** Disposes the cache by calling dispose an all of its entries. */
93         void dispose() {
94             for (Iterator JavaDoc i = entries.values().iterator(); i.hasNext();) {
95                 ((Entry) i.next()).dispose();
96             }
97             entries.clear();
98         }
99
100         /**
101          * If the entry is already in the cache, then it simply returns a
102          * reference. Otherwise, it creates a new entry in the cache, and
103          * returns a reference to that.
104          *
105          * @param descriptor
106          * The descriptor to look up in the cache; should not be
107          * <code>null</code>.
108          * @return The entry for that descriptor; never <code>null</code>.
109          */

110         Entry getEntry(ImageDescriptor descriptor) {
111             Entry entry = (Entry) entries.get(descriptor);
112
113             if (entry == null) {
114                 entry = new Entry();
115                 entries.put(descriptor, entry);
116             }
117
118             return entry;
119         }
120
121         /**
122          * Retrieves a greyed representation of the image of the corresponding
123          * URI from the cache. If the image is not in the cache, then it tries
124          * to load the image. If the image URI is invalid, then it returns the
125          * missing image.
126          *
127          * @param imageURI
128          * The URI at which the image is located; may be <code>null</code>
129          * @return The image at the URI, or the missing image if it is invalid.
130          * If the URI is <code>null</code>, then this returns <code>null</code>
131          * as well.
132          */

133         Image getGrayImage(String JavaDoc imageURI) {
134             if (imageURI == null) {
135                 return null;
136             }
137
138             try {
139                 ImageDescriptor descriptor =
140                     ImageDescriptor.createFromURL(new URL JavaDoc(imageURI));
141                 Entry entry = getEntry(descriptor);
142                 if (entry.grayImage == null) {
143                     Image image = getImage(imageURI);
144                     if (image != null) {
145                         entry.grayImage =
146                             new Image(null, image, SWT.IMAGE_GRAY);
147                     }
148                 }
149
150                 return entry.grayImage;
151
152             } catch (MalformedURLException JavaDoc e) {
153                 return new Image(null, getMissingImage(), SWT.IMAGE_GRAY);
154             }
155         }
156
157         /**
158          * Retrieves the image of the corresponding URI from the cache. If the
159          * image is not in the cache, then it tries to load the image. If the
160          * image URI is invalid, then it returns the missing image.
161          *
162          * @param imageURI
163          * The URI at which the image is located; may be <code>null</code>
164          * @return The image at the URI, or the missing image if it is invalid.
165          * If the URI is <code>null</code>, then this returns <code>null</code>
166          * as well.
167          */

168         Image getImage(String JavaDoc imageURI) {
169             if (imageURI == null) {
170                 return null;
171             }
172
173             try {
174                 ImageDescriptor descriptor =
175                     ImageDescriptor.createFromURL(new URL JavaDoc(imageURI));
176                 Entry entry = getEntry(descriptor);
177                 if (entry.image == null) {
178                     entry.image = descriptor.createImage();
179                 }
180
181                 return entry.image;
182
183             } catch (MalformedURLException JavaDoc e) {
184                 return getMissingImage();
185             }
186         }
187
188         /**
189          * Retrieves the missing image from the cache. If the image isn't
190          * available, then it loads it into the cache.
191          *
192          * @return The missing image; never <code>null</code>.
193          */

194         Image getMissingImage() {
195             if (missingImage == null) {
196                 ImageDescriptor descriptor =
197                     ImageDescriptor.getMissingImageDescriptor();
198                 Entry entry = getEntry(descriptor);
199                 if (entry.image == null) {
200                     entry.image = descriptor.createImage();
201                 }
202                 missingImage = entry.image;
203             }
204
205             return missingImage;
206         }
207     }
208
209     /** The global cache of images used by this contribution item. */
210     private static ImageCache globalImageCache;
211     /** Whether command contribution items should use colour icons. */
212     private static boolean useColourIcons = true;
213
214     /**
215      * Checks whether the given menu item belongs to a context menu (the one
216      * that pops up if the user presses the right mouse button).
217      */

218     // private static boolean belongsToContextMenu(MenuItem item) {
219
// Menu menu = item.getParent();
220
// if (menu == null)
221
// return false;
222
// while (menu.getParentMenu() != null)
223
// menu = menu.getParentMenu();
224
// return (menu.getStyle() & SWT.BAR) == 0;
225
// }
226

227     /**
228      * Returns whether color icons should be used in toolbars.
229      *
230      * @return <code>true</code> if color icons should be used in toolbars;
231      * <code>false</code> otherwise.
232      */

233     public static boolean getUseColourIconsInToolbars() {
234         return useColourIcons;
235     }
236
237     /**
238      * Convenience method for removing any optional accelerator text from the
239      * given string. The accelerator text appears at the end of the text, and
240      * is separated from the main part by a single tab character <code>'\t'</code>.
241      *
242      * @param text
243      * The text to be stripped; must not be <code>null</code>.
244      * @return The text sans accelerator; never <code>null</code>.
245      */

246     public static String JavaDoc removeAcceleratorText(String JavaDoc text) {
247         int index = text.lastIndexOf('\t');
248         if (index == -1)
249             index = text.lastIndexOf('@');
250         if (index >= 0)
251             return text.substring(0, index);
252         return text;
253     }
254
255     /**
256      * Sets whether color icons should be used in toolbars.
257      *
258      * @param newValue
259      * <code>true</code> if color icons should be used in
260      * toolbars, <code>false</code> otherwise
261      */

262     public static void setUseColourIconsInToolbars(boolean newValue) {
263         useColourIcons = newValue;
264     }
265
266     /** Listener for SWT button widget events. */
267     private Listener buttonListener;
268     /** The command that this contribution item represents. */
269     private ICommand command;
270     /** The help listener for the command. */
271     private HelpListener helpListener;
272     /** Listener for SWT menu item widget events. */
273     private Listener menuItemListener;
274     /** Listener for SWT tool item widget events. */
275     private Listener toolItemListener;
276     /**
277      * The widget created for this item; <code>null</code> before creation
278      * and after disposal.
279      */

280     private Widget widget = null;
281
282     /**
283      * Creates a new contribution item from the given command. The id of the
284      * command is used as the id of the item.
285      *
286      * @param command
287      * The command from which this contribution item should be
288      * constructed; must not be <code>null</code>.
289      */

290     public CommandContributionItem(ICommand commandToUse) {
291         super(commandToUse.getId());
292         command = commandToUse;
293         helpListener = WorkbenchHelp.createHelpListener(commandToUse);
294     }
295
296     /**
297      * Handles a change event on the command. This performs an update of the
298      * underlying widget to reflect the change.
299      *
300      * @param e
301      * The triggering event; must not be <code>null</code>.
302      */

303     public void commandChanged(final CommandEvent e) {
304         // This code should be removed. Avoid using free asyncExec
305

306         if (isVisible() && widget != null) {
307             Display display = widget.getDisplay();
308             if (display.getThread() == Thread.currentThread()) {
309                 update(e);
310             } else {
311                 display.asyncExec(new Runnable JavaDoc() {
312                     public void run() {
313                         update(e);
314                     }
315                 });
316             }
317
318         }
319     }
320
321     /**
322      * Compares this command contribution item with another object. Two command
323      * contribution items are equal if they refer to the equivalent command.
324      *
325      * @param o
326      * The object with which to compare; may be <code>null</code>.
327      */

328     public boolean equals(Object JavaDoc o) {
329         if (!(o instanceof CommandContributionItem)) {
330             return false;
331         }
332         return command.equals(((CommandContributionItem) o).command);
333     }
334
335     /**
336      * The <code>CommandContributionItem</code> implementation of this <code>IContributionItem</code>
337      * method creates an SWT <code>Button</code> for the command using the
338      * command's style. If the command's checked property has been set, the
339      * button is created and primed to the value of the checked property.
340      *
341      * @param parent
342      * The composite parent which this contribution should place
343      * itself on; must not be <code>null</code>.
344      */

345     public void fill(Composite parent) {
346         if (widget == null && parent != null) {
347             int flags = SWT.PUSH;
348             if (command != null) {
349                 // TODO STYLE
350
// if (action.getStyle() == IAction.AS_CHECK_BOX)
351
// flags = SWT.TOGGLE;
352
//if (action.getStyle() == IAction.AS_RADIO_BUTTON)
353
// flags = SWT.RADIO;
354
}
355
356             Button b = new Button(parent, flags);
357             b.setData(this);
358             b.addListener(SWT.Dispose, getButtonListener());
359             // Don't hook a dispose listener on the parent.
360
b.addListener(SWT.Selection, getButtonListener());
361             b.addHelpListener(helpListener);
362             widget = b;
363
364             update();
365
366             command.addCommandListener(this);
367         }
368     }
369
370     /**
371      * The <code>CommandContributionItem</code> implementation of this <code>IContributionItem</code>
372      * method creates an SWT <code>MenuItem</code> for the action using the
373      * command's style. If the command's checked property has been set, a
374      * button is created and primed to the value of the checked property. If
375      * the command's menu creator property has been set, a cascading submenu is
376      * created.
377      *
378      * @param parent
379      * The menu on which this contribution item should place itself;
380      * must not be <code>null</code>.
381      * @param index
382      * The index at which this contribution item should place
383      * itself. If it is a negative number, then this simply appends
384      * the item.
385      */

386     public void fill(Menu parent, int index) {
387         if (widget == null && parent != null) {
388             Menu subMenu = null;
389             int flags = SWT.PUSH;
390             if (command != null) {
391                 // TODO STYLE
392
//int style = action.getStyle();
393
//if (style == IAction.AS_CHECK_BOX)
394
// flags = SWT.CHECK;
395
//else if (style == IAction.AS_RADIO_BUTTON)
396
// flags = SWT.RADIO;
397
//else if (style == IAction.AS_DROP_DOWN_MENU) {
398
// IMenuCreator mc = action.getMenuCreator();
399
// if (mc != null) {
400
// subMenu = mc.getMenu(parent);
401
// flags = SWT.CASCADE;
402
// }
403
//}
404
}
405
406             MenuItem mi = null;
407             if (index >= 0)
408                 mi = new MenuItem(parent, flags, index);
409             else
410                 mi = new MenuItem(parent, flags);
411             widget = mi;
412
413             mi.setData(this);
414             mi.addListener(SWT.Dispose, getMenuItemListener());
415             mi.addListener(SWT.Selection, getMenuItemListener());
416             mi.addHelpListener(helpListener);
417
418             if (subMenu != null)
419                 mi.setMenu(subMenu);
420
421             update();
422
423             command.addCommandListener(this);
424         }
425     }
426
427     /**
428      * The <code>CommandContributionItem</code> implementation of this <code>IContributionItem</code>
429      * method creates an SWT <code>ToolItem</code> for the command using the
430      * command's style. If the command's checked property has been set, a
431      * button is created and primed to the value of the checked property. If
432      * the command's menu creator property has been set, a drop-down tool item
433      * is created.
434      *
435      * @param parent
436      * The tool bar on which this contribution item should place
437      * itself; must not be <code>null</code>.
438      * @param index
439      * The index at which this contribution item should place
440      * itself. If it is a negative number, then this simply appends
441      * the item.
442      */

443     public void fill(ToolBar parent, int index) {
444         if (widget == null && parent != null) {
445             int flags = SWT.PUSH;
446             if (command != null) {
447                 // TODO STYLE
448
//int style = action.getStyle();
449
//if (style == IAction.AS_CHECK_BOX)
450
// flags = SWT.CHECK;
451
//else if (style == IAction.AS_RADIO_BUTTON)
452
// flags = SWT.RADIO;
453
//else if (style == IAction.AS_DROP_DOWN_MENU)
454
// flags = SWT.DROP_DOWN;
455
}
456
457             ToolItem ti = null;
458             if (index >= 0)
459                 ti = new ToolItem(parent, flags, index);
460             else
461                 ti = new ToolItem(parent, flags);
462             ti.setData(this);
463             ti.addListener(SWT.Selection, getToolItemListener());
464             ti.addListener(SWT.Dispose, getToolItemListener());
465
466             widget = ti;
467
468             update();
469
470             command.addCommandListener(this);
471         }
472     }
473
474     /**
475      * Returns the listener for SWT button widget events. This lazy initializes
476      * the listener.
477      *
478      * @return A listener for button events; never <code>null</code>.
479      */

480     private Listener getButtonListener() {
481         if (buttonListener == null) {
482             buttonListener = new Listener() {
483                 public void handleEvent(Event event) {
484                     switch (event.type) {
485                         case SWT.Dispose :
486                             handleWidgetDispose(event);
487                             break;
488                         case SWT.Selection :
489                             Widget ew = event.widget;
490                             if (ew != null) {
491                                 handleWidgetSelection(
492                                     event,
493                                     ((Button) ew).getSelection());
494                             }
495                             break;
496                     }
497                 }
498             };
499         }
500         return buttonListener;
501     }
502
503     /**
504      * Returns the command associated with this contribution item.
505      *
506      * @return The associated command; never <code>null</code>.
507      */

508     public ICommand getCommand() {
509         return command;
510     }
511
512     /**
513      * Returns the image cache. The cache is global, and is shared by all
514      * command contribution items. This has the disadvantage that once an image
515      * is allocated, it is never freed until the display is disposed. However,
516      * it has the advantage that the same image in different contribution
517      * managers is only ever created once.
518      *
519      * @param The
520      * global image cache for command contribution items; never
521      * <code>null</code>.
522      */

523     private ImageCache getImageCache() {
524         ImageCache cache = globalImageCache;
525         if (cache == null) {
526             globalImageCache = cache = new ImageCache();
527             Display display = Display.getDefault();
528             if (display != null) {
529                 display.disposeExec(new Runnable JavaDoc() {
530                     public void run() {
531                         if (globalImageCache != null) {
532                             globalImageCache.dispose();
533                             globalImageCache = null;
534                         }
535                     }
536                 });
537             }
538         }
539         return cache;
540     }
541
542     /**
543      * Returns the listener for SWT menu item widget events. The listener is
544      * lazy initialized when this method is first called.
545      *
546      * @return A listener for menu item events; never <code>null</code>.
547      */

548     private Listener getMenuItemListener() {
549         if (menuItemListener == null) {
550             menuItemListener = new Listener() {
551                 public void handleEvent(Event event) {
552                     switch (event.type) {
553                         case SWT.Dispose :
554                             handleWidgetDispose(event);
555                             break;
556                         case SWT.Selection :
557                             Widget ew = event.widget;
558                             if (ew != null) {
559                                 handleWidgetSelection(
560                                     event,
561                                     ((MenuItem) ew).getSelection());
562                             }
563                             break;
564                     }
565                 }
566             };
567         }
568         return menuItemListener;
569     }
570
571     /**
572      * Returns the listener for SWT tool item widget events. The listener is
573      * lazy initialized when this method is first called.
574      *
575      * @return A listener for tool item events; never <code>null</code>.
576      */

577     private Listener getToolItemListener() {
578         if (toolItemListener == null) {
579             toolItemListener = new Listener() {
580                 public void handleEvent(Event event) {
581                     switch (event.type) {
582                         case SWT.Dispose :
583                             handleWidgetDispose(event);
584                             break;
585                         case SWT.Selection :
586                             Widget ew = event.widget;
587                             if (ew != null) {
588                                 handleWidgetSelection(
589                                     event,
590                                     ((ToolItem) ew).getSelection());
591                             }
592                             break;
593                     }
594                 }
595             };
596         }
597         return toolItemListener;
598     }
599
600     /**
601      * Handles a widget dispose event for the widget corresponding to this
602      * item. This detaches the command listener, and disposes the menu creator
603      * if there is one.
604      *
605      * @param e
606      * The triggering dispose event; must not be <code>null</code>.
607      */

608     private void handleWidgetDispose(Event e) {
609         if (e.widget == widget) {
610             // the item is being disposed
611
// TODO STYLE
612
//if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) {
613
// IMenuCreator mc = action.getMenuCreator();
614
// if (mc != null) {
615
// mc.dispose();
616
// }
617
//}
618
command.removeCommandListener(this);
619             widget = null;
620         }
621     }
622
623     /**
624      * Handles a widget selection event.
625      *
626      * @param e
627      * The triggering selection event; must not be <code>null</code>
628      * @param selection
629      * Whether the item is becoming selected (as opposed to
630      * de-selected).
631      */

632     private void handleWidgetSelection(Event e, boolean selection) {
633         Widget item = e.widget;
634         if (item != null) {
635             // TODO STYLE
636
//int style = item.getStyle();
637
//
638
//if ((style & (SWT.TOGGLE | SWT.CHECK)) != 0) {
639
// if (action.getStyle() == IAction.AS_CHECK_BOX) {
640
// action.setChecked(selection);
641
// }
642
//} else if ((style & SWT.RADIO) != 0) {
643
// if (action.getStyle() == IAction.AS_RADIO_BUTTON) {
644
// action.setChecked(selection);
645
// }
646
//} else if ((style & SWT.DROP_DOWN) != 0) {
647
// if (e.detail == 4) { // on drop-down button
648
// if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) {
649
// IMenuCreator mc = action.getMenuCreator();
650
// ToolItem ti = (ToolItem) item;
651
// // we create the menu as a sub-menu of "dummy" so that
652
// // we can use
653
// // it in a cascading menu too.
654
// // If created on a SWT control we would get an SWT
655
// // error...
656
// //Menu dummy= new Menu(ti.getParent());
657
// //Menu m= mc.getMenu(dummy);
658
// //dummy.dispose();
659
// if (mc != null) {
660
// Menu m = mc.getMenu(ti.getParent());
661
// if (m != null) {
662
// // position the menu below the drop down item
663
// Rectangle b = ti.getBounds();
664
// Point p = ti.getParent().toDisplay(new Point(b.x, b.y +
665
// b.height));
666
// m.setLocation(p.x, p.y); // waiting for SWT
667
// // 0.42
668
// m.setVisible(true);
669
// return; // we don't fire the action
670
// }
671
// }
672
// }
673
// }
674
//}
675

676             // Ensure command is enabled first.
677
// See 1GAN3M6: ITPUI:WINNT - Any IAction in the workbench can be
678
// executed while disabled.
679

680             if (isEnabled(command)) {
681                 boolean trace = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.jface/trace/actions")); //$NON-NLS-1$ //$NON-NLS-2$
682
long ms = System.currentTimeMillis();
683                 try {
684                     if (trace)
685                         System.out.println("Running command: " + command.getName()); //$NON-NLS-1$
686

687                     // TODO Dispatching commands
688
//command.runWithEvent(e);
689

690                     if (trace)
691                         System.out.println((System.currentTimeMillis() - ms) + " ms to run command: " + command.getName()); //$NON-NLS-1$
692
} catch (NotDefinedException nde) {
693                     // TODO Warn the user that the command is now gone.
694
update(); // update the GUI
695
}
696             }
697         }
698     }
699
700     /*
701      * (non-Javadoc) Method declared on Object.
702      */

703     public int hashCode() {
704         return command.hashCode();
705     }
706
707     /**
708      * The command item implementation of this <code>IContributionItem</code>
709      * method returns <code>true</code> for menu items and <code>false</code>
710      * for everything else.
711      */

712     public boolean isDynamic() {
713         if (widget instanceof MenuItem) {
714             //Optimization. Only recreate the item is the check or radio style
715
// has changed.
716
// TODO STYLE
717
boolean itemIsCheck = (widget.getStyle() & SWT.CHECK) != 0;
718             //boolean actionIsCheck = getAction() != null &&
719
// getAction().getStyle() == IAction.AS_CHECK_BOX;
720
boolean itemIsRadio = (widget.getStyle() & SWT.RADIO) != 0;
721             //boolean actionIsRadio = getAction() != null &&
722
// getAction().getStyle() == IAction.AS_RADIO_BUTTON;
723
//return (itemIsCheck != actionIsCheck) || (itemIsRadio !=
724
// actionIsRadio);
725
return false;
726         }
727
728         return false;
729     }
730
731     /*
732      * (non-Javadoc) Method declared on IContributionItem.
733      */

734     public boolean isEnabled() {
735         return isEnabled(command);
736     }
737
738     private static boolean isEnabled(ICommand command) {
739         try {
740             Map JavaDoc attributeValuesByName = command.getAttributeValuesByName();
741
742             if (attributeValuesByName.containsKey("enabled") //$NON-NLS-1$
743
&& !Boolean.TRUE.equals(attributeValuesByName.get("enabled"))) //$NON-NLS-1$
744
return false;
745             else
746                 return true;
747         } catch (NotHandledException eNotHandled) {
748             return false;
749         }
750     }
751     
752     /**
753      * Returns <code>true</code> if this item is allowed to enable, <code>false</code>
754      * otherwise.
755      *
756      * @return If this item is allowed to be enabled
757      * @since 2.0
758      */

759     protected boolean isEnabledAllowed() {
760         if (getParent() == null)
761             return true;
762         Boolean JavaDoc value = getParent().getOverrides().getEnabled(this);
763         return (value == null) ? true : value.booleanValue();
764     }
765
766     /**
767      * Whether this contribution item should be visible.
768      *
769      * @return <code>true</code> if the command is active; <code>false</code>
770      * otherwise.
771      */

772     public boolean isVisible() {
773         return true; // TODO visiblity should consider the activity and context managers.
774
}
775
776     /**
777      * The command item implementation of this <code>IContributionItem</code>
778      * method calls <code>update(null)</code>.
779      */

780     public void update() {
781         update((CommandEvent) null);
782     }
783
784     /**
785      * Synchronizes the UI with the given property.
786      *
787      * @param event
788      * The event triggering the update (which specifies how much of
789      * the command changed). If <code>null</code>, then
790      * everything is updated.
791      */

792     public void update(CommandEvent event) {
793         if (widget != null) {
794             ICommand currentCommand = getCommand();
795
796             // Determine what to do
797
boolean descriptionChanged = true;
798             boolean nameChanged = true;
799             boolean enabledChanged = true;
800             boolean checkedChanged = true;
801             if (event != null) {
802                 descriptionChanged = event.hasDescriptionChanged();
803                 nameChanged = event.hasNameChanged();
804                 // TODO Enable change notification
805
//enabledChanged = event.hasEnabledChanged();
806
// TODO Checked state notification
807
//checkedChanged = event.hasSelectionChanged();
808

809                 if ((event.hasDefinedChanged() && !currentCommand.isDefined())
810                     /* TODO || (event.hasActiveChanged() && !currentCommand.isActive())*/) {
811                     // TODO Dispose of the item?
812
}
813             }
814
815             try {
816                 // Update the widget as a ToolItem
817
if (widget instanceof ToolItem) {
818                     ToolItem ti = (ToolItem) widget;
819
820                     if (descriptionChanged)
821                         ti.setToolTipText(currentCommand.getDescription());
822
823                     if (enabledChanged) {
824                         boolean shouldBeEnabled =
825                             isEnabled(currentCommand) && isEnabledAllowed();
826
827                         if (ti.getEnabled() != shouldBeEnabled)
828                             ti.setEnabled(shouldBeEnabled);
829                     }
830
831                     if (checkedChanged) {
832                         // TODO Selection state
833
//boolean bv = command.isChecked();
834
//
835
//if (ti.getSelection() != bv)
836
// ti.setSelection(bv);
837
}
838
839                     return;
840                 }
841
842                 // Update the widget as a MenuItem
843
if (widget instanceof MenuItem) {
844                     MenuItem mi = (MenuItem) widget;
845
846                     if (nameChanged) {
847                         Integer JavaDoc accelerator = null;
848                         String JavaDoc acceleratorText = null;
849                         String JavaDoc name = null;
850
851                         ExternalActionManager.ICallback callback =
852                             ExternalActionManager.getInstance().getCallback();
853                         if (callback != null) {
854                             String JavaDoc commandId = currentCommand.getId();
855                             if (commandId != null) {
856                                 accelerator =
857                                     callback.getAccelerator(commandId);
858                                 acceleratorText =
859                                     callback.getAcceleratorText(commandId);
860                             }
861                         }
862
863                         IContributionManagerOverrides overrides = null;
864
865                         if (getParent() != null)
866                             overrides = getParent().getOverrides();
867
868                         if (overrides != null)
869                             name = getParent().getOverrides().getText(this);
870
871                         //
872
//if (accelerator == null)
873
// // TODO Not necessary?
874
// accelerator = new Integer(command.getAccelerator());
875

876                         mi.setAccelerator(accelerator.intValue());
877
878                         if (name == null)
879                             name = currentCommand.getName();
880
881                         if (name == null)
882                             name = ""; //$NON-NLS-1$
883
else
884                             name = removeAcceleratorText(name);
885
886                         if (acceleratorText == null)
887                             mi.setText(name);
888                         else
889                             mi.setText(name + '\t' + acceleratorText);
890                     }
891
892                     if (enabledChanged) {
893                         boolean shouldBeEnabled =
894                             isEnabled(currentCommand) && isEnabledAllowed();
895
896                         if (mi.getEnabled() != shouldBeEnabled)
897                             mi.setEnabled(shouldBeEnabled);
898                     }
899
900                     if (checkedChanged) {
901                         // TODO Selection state needed.
902
//boolean bv = command.isChecked();
903
//
904
//if (mi.getSelection() != bv)
905
// mi.setSelection(bv);
906
}
907
908                     return;
909                 }
910
911                 // Update the widget as a button.
912
if (widget instanceof Button) {
913                     Button button = (Button) widget;
914
915                     if (nameChanged) {
916                         String JavaDoc name = currentCommand.getName();
917
918                         if (name != null)
919                             button.setText(name);
920                     }
921
922                     if (descriptionChanged)
923                         button.setToolTipText(currentCommand.getDescription());
924
925                     if (enabledChanged) {
926                         boolean shouldBeEnabled =
927                             isEnabled(currentCommand) && isEnabledAllowed();
928
929                         if (button.getEnabled() != shouldBeEnabled)
930                             button.setEnabled(shouldBeEnabled);
931                     }
932
933                     if (checkedChanged) {
934                         // TODO Selection state needed.
935
//boolean bv = action.isChecked();
936
//
937
//if (button.getSelection() != bv)
938
// button.setSelection(bv);
939
}
940
941                     return;
942                 }
943             } catch (NotDefinedException e) {
944                 /*
945                  * This shouldn't happen very often. It can only happen in a
946                  * multi-threaded environment where a command becomes undefined
947                  * on one thread while another thread is attempting an update.
948                  */

949
950                 // TODO Dispose of the item.
951
}
952         }
953     }
954 }
955
Popular Tags