Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 9581e06328b271da9afd223ccec745261ff019e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
/*******************************************************************************
 * Copyright (c) 2000, 2014 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.jface.action;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.NotEnabledException;
import org.eclipse.jface.action.ExternalActionManager.IBindingManagerCallback;
import org.eclipse.jface.bindings.Trigger;
import org.eclipse.jface.bindings.TriggerSequence;
import org.eclipse.jface.bindings.keys.IKeyLookup;
import org.eclipse.jface.bindings.keys.KeyLookupFactory;
import org.eclipse.jface.bindings.keys.KeyStroke;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;

/**
 * A contribution item which delegates to an action.
 * <p>
 * This class may be instantiated; it is not intended to be subclassed.
 * </p>
 * @noextend This class is not intended to be subclassed by clients.
 */
public class ActionContributionItem extends ContributionItem {
 
	/**
	 * Mode bit: Show text on tool items or buttons, even if an image is
	 * present. If this mode bit is not set, text is only shown on tool items if
	 * there is no image present.
	 * 
	 * @since 3.0
	 */
	public static int MODE_FORCE_TEXT = 1;

	/** a string inserted in the middle of text that has been shortened */
	private static final String ellipsis = "..."; //$NON-NLS-1$

	/**
	 * Stores the result of the action. False when the action returned failure.
	 */
	private Boolean result = null;

	private static boolean USE_COLOR_ICONS = true;

	/**
	 * Returns whether color icons should be used in toolbars.
	 * 
	 * @return <code>true</code> if color icons should be used in toolbars,
	 *         <code>false</code> otherwise
	 */
	public static boolean getUseColorIconsInToolbars() {
		return USE_COLOR_ICONS;
	}

	/**
	 * Sets whether color icons should be used in toolbars.
	 * 
	 * @param useColorIcons
	 *            <code>true</code> if color icons should be used in toolbars,
	 *            <code>false</code> otherwise
	 */
	public static void setUseColorIconsInToolbars(boolean useColorIcons) {
		USE_COLOR_ICONS = useColorIcons;
	}

	/**
	 * The presentation mode.
	 */
	private int mode = 0;

	/**
	 * The action.
	 */
	private IAction action;

	/**
	 * The listener for changes to the text of the action contributed by an
	 * external source.
	 */
	private final IPropertyChangeListener actionTextListener = new IPropertyChangeListener() {

		/**
		 * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
		 */
		@Override
		public void propertyChange(PropertyChangeEvent event) {
			update(event.getProperty());
		}
	};

	/**
	 * Remembers all images in use by this contribution item
	 */
	private LocalResourceManager imageManager;

	/**
	 * Listener for SWT button widget events.
	 */
	private Listener buttonListener;

	/**
	 * Listener for SWT menu item widget events.
	 */
	private Listener menuItemListener;

	/**
	 * Listener for action property change notifications.
	 */
	private final IPropertyChangeListener propertyListener = new IPropertyChangeListener() {
		@Override
		public void propertyChange(PropertyChangeEvent event) {
			actionPropertyChange(event);
		}
	};

	/**
	 * Listener for SWT tool item widget events.
	 */
	private Listener toolItemListener;

	/**
	 * The widget created for this item; <code>null</code> before creation and
	 * after disposal.
	 */
	private Widget widget = null;

	private Listener menuCreatorListener;

	/**
	 * Creates a new contribution item from the given action. The id of the
	 * action is used as the id of the item.
	 * 
	 * @param action
	 *            the action
	 */
	public ActionContributionItem(IAction action) {
		super(action.getId());
		this.action = action;
	}

	/**
	 * Handles a property change event on the action (forwarded by nested
	 * listener).
	 */
	private void actionPropertyChange(final PropertyChangeEvent e) {
		// This code should be removed. Avoid using free asyncExec

		if (isVisible() && widget != null) {
			Display display = widget.getDisplay();
			if (display.getThread() == Thread.currentThread()) {
				update(e.getProperty());
			} else {
				display.asyncExec(new Runnable() {
					@Override
					public void run() {
						update(e.getProperty());
					}
				});
			}

		}
	}

	/**
	 * Compares this action contribution item with another object. Two action
	 * contribution items are equal if they refer to the identical Action.
	 */
	@Override
	public boolean equals(Object o) {
		if (!(o instanceof ActionContributionItem)) {
			return false;
		}
		return action.equals(((ActionContributionItem) o).action);
	}

	/**
	 * The <code>ActionContributionItem</code> implementation of this
	 * <code>IContributionItem</code> method creates an SWT
	 * <code>Button</code> for the action using the action's style. If the
	 * action's checked property has been set, the button is created and primed
	 * to the value of the checked property.
	 */
	@Override
	public void fill(Composite parent) {
		if (widget == null && parent != null) {
			int flags = SWT.PUSH;
			if (action != null) {
				if (action.getStyle() == IAction.AS_CHECK_BOX) {
					flags = SWT.TOGGLE;
				}
				if (action.getStyle() == IAction.AS_RADIO_BUTTON) {
					flags = SWT.RADIO;
				}
			}

			Button b = new Button(parent, flags);
			b.setData(this);
			b.addListener(SWT.Dispose, getButtonListener());
			// Don't hook a dispose listener on the parent
			b.addListener(SWT.Selection, getButtonListener());
			if (action.getHelpListener() != null) {
				b.addHelpListener(action.getHelpListener());
			}
			widget = b;

			update(null);

			// Attach some extra listeners.
			action.addPropertyChangeListener(propertyListener);
			if (action != null) {
				String commandId = action.getActionDefinitionId();
				ExternalActionManager.ICallback callback = ExternalActionManager
						.getInstance().getCallback();

				if ((callback != null) && (commandId != null)) {
					callback.addPropertyChangeListener(commandId,
							actionTextListener);
				}
			}
		}
	}

	/**
	 * The <code>ActionContributionItem</code> implementation of this
	 * <code>IContributionItem</code> method creates an SWT
	 * <code>MenuItem</code> for the action using the action's style. If the
	 * action's checked property has been set, a button is created and primed to
	 * the value of the checked property. If the action's menu creator property
	 * has been set, a cascading submenu is created.
	 */
	@Override
	public void fill(Menu parent, int index) {
		if (widget == null && parent != null) {
			int flags = SWT.PUSH;
			if (action != null) {
				int style = action.getStyle();
				if (style == IAction.AS_CHECK_BOX) {
					flags = SWT.CHECK;
				} else if (style == IAction.AS_RADIO_BUTTON) {
					flags = SWT.RADIO;
				} else if (style == IAction.AS_DROP_DOWN_MENU) {
					flags = SWT.CASCADE;
				}
			}

			MenuItem mi = null;
			if (index >= 0) {
				mi = new MenuItem(parent, flags, index);
			} else {
				mi = new MenuItem(parent, flags);
			}
			widget = mi;

			mi.setData(this);
			mi.addListener(SWT.Dispose, getMenuItemListener());
			mi.addListener(SWT.Selection, getMenuItemListener());
			if (action.getHelpListener() != null) {
				mi.addHelpListener(action.getHelpListener());
			}

			if (flags == SWT.CASCADE) {
				// just create a proxy for now, if the user shows it then 
				// fill it in
				Menu subMenu = new Menu(parent);
				subMenu.addListener(SWT.Show, getMenuCreatorListener());
				subMenu.addListener(SWT.Hide, getMenuCreatorListener());
				mi.setMenu(subMenu);
			}

			update(null);

			// Attach some extra listeners.
			action.addPropertyChangeListener(propertyListener);
			if (action != null) {
				String commandId = action.getActionDefinitionId();
				ExternalActionManager.ICallback callback = ExternalActionManager
						.getInstance().getCallback();

				if ((callback != null) && (commandId != null)) {
					callback.addPropertyChangeListener(commandId,
							actionTextListener);
				}
			}
		}
	}

	/**
	 * The <code>ActionContributionItem</code> implementation of this ,
	 * <code>IContributionItem</code> method creates an SWT
	 * <code>ToolItem</code> for the action using the action's style. If the
	 * action's checked property has been set, a button is created and primed to
	 * the value of the checked property. If the action's menu creator property
	 * has been set, a drop-down tool item is created.
	 */
	@Override
	public void fill(ToolBar parent, int index) {
		if (widget == null && parent != null) {
			int flags = SWT.PUSH;
			if (action != null) {
				int style = action.getStyle();
				if (style == IAction.AS_CHECK_BOX) {
					flags = SWT.CHECK;
				} else if (style == IAction.AS_RADIO_BUTTON) {
					flags = SWT.RADIO;
				} else if (style == IAction.AS_DROP_DOWN_MENU) {
					flags = SWT.DROP_DOWN;
				}
			}

			ToolItem ti = null;
			if (index >= 0) {
				ti = new ToolItem(parent, flags, index);
			} else {
				ti = new ToolItem(parent, flags);
			}
			ti.setData(this);
			ti.addListener(SWT.Selection, getToolItemListener());
			ti.addListener(SWT.Dispose, getToolItemListener());

			widget = ti;

			update(null);

			// Attach some extra listeners.
			action.addPropertyChangeListener(propertyListener);
			if (action != null) {
				String commandId = action.getActionDefinitionId();
				ExternalActionManager.ICallback callback = ExternalActionManager
						.getInstance().getCallback();

				if ((callback != null) && (commandId != null)) {
					callback.addPropertyChangeListener(commandId,
							actionTextListener);
				}
			}
		}
	}

	/**
	 * Returns the action associated with this contribution item.
	 * 
	 * @return the action
	 */
	public IAction getAction() {
		return action;
	}

	/**
	 * Returns the listener for SWT button widget events.
	 * 
	 * @return a listener for button events
	 */
	private Listener getButtonListener() {
		if (buttonListener == null) {
			buttonListener = new Listener() {
				@Override
				public void handleEvent(Event event) {
					switch (event.type) {
					case SWT.Dispose:
						handleWidgetDispose(event);
						break;
					case SWT.Selection:
						Widget ew = event.widget;
						if (ew != null) {
							handleWidgetSelection(event, ((Button) ew)
									.getSelection());
						}
						break;
					}
				}
			};
		}
		return buttonListener;
	}

	/**
	 * Returns the listener for SWT menu item widget events.
	 * 
	 * @return a listener for menu item events
	 */
	private Listener getMenuItemListener() {
		if (menuItemListener == null) {
			menuItemListener = new Listener() {
				@Override
				public void handleEvent(Event event) {
					switch (event.type) {
					case SWT.Dispose:
						handleWidgetDispose(event);
						break;
					case SWT.Selection:
						Widget ew = event.widget;
						if (ew != null) {
							handleWidgetSelection(event, ((MenuItem) ew)
									.getSelection());
						}
						break;
					}
				}
			};
		}
		return menuItemListener;
	}

	/**
	 * Returns the presentation mode, which is the bitwise-or of the
	 * <code>MODE_*</code> constants. The default mode setting is 0, meaning
	 * that for menu items, both text and image are shown (if present), but for
	 * tool items, the text is shown only if there is no image.
	 * 
	 * @return the presentation mode settings
	 * 
	 * @since 3.0
	 */
	public int getMode() {
		return mode;
	}

	/**
	 * Returns the listener for SWT tool item widget events.
	 * 
	 * @return a listener for tool item events
	 */
	private Listener getToolItemListener() {
		if (toolItemListener == null) {
			toolItemListener = new Listener() {
				@Override
				public void handleEvent(Event event) {
					switch (event.type) {
					case SWT.Dispose:
						handleWidgetDispose(event);
						break;
					case SWT.Selection:
						Widget ew = event.widget;
						if (ew != null) {
							handleWidgetSelection(event, ((ToolItem) ew)
									.getSelection());
						}
						break;
					}
				}
			};
		}
		return toolItemListener;
	}

	/**
	 * Handles a widget dispose event for the widget corresponding to this item.
	 */
	private void handleWidgetDispose(Event e) {
		// Check if our widget is the one being disposed.
		if (e.widget == widget) {
			// Dispose of the menu creator.
			if (action.getStyle() == IAction.AS_DROP_DOWN_MENU
					&& menuCreatorCalled) {
				IMenuCreator mc = action.getMenuCreator();
				if (mc != null) {
					mc.dispose();
				}
			}

			// Unhook all of the listeners.
			action.removePropertyChangeListener(propertyListener);
			if (action != null) {
				String commandId = action.getActionDefinitionId();
				ExternalActionManager.ICallback callback = ExternalActionManager
						.getInstance().getCallback();

				if ((callback != null) && (commandId != null)) {
					callback.removePropertyChangeListener(commandId,
							actionTextListener);
				}
			}

			// Clear the widget field.
			widget = null;

			disposeOldImages();
		}
	}

	/**
	 * Handles a widget selection event.
	 */
	private void handleWidgetSelection(Event e, boolean selection) {

		Widget item = e.widget;
		if (item != null) {
			int style = item.getStyle();

			if ((style & (SWT.TOGGLE | SWT.CHECK)) != 0) {
				if (action.getStyle() == IAction.AS_CHECK_BOX) {
					action.setChecked(selection);
				}
			} else if ((style & SWT.RADIO) != 0) {
				if (action.getStyle() == IAction.AS_RADIO_BUTTON) {
					action.setChecked(selection);
				}
			} else if ((style & SWT.DROP_DOWN) != 0) {
				if (e.detail == 4) { // on drop-down button
					if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) {
						IMenuCreator mc = action.getMenuCreator();
						menuCreatorCalled = true;
						ToolItem ti = (ToolItem) item;
						// we create the menu as a sub-menu of "dummy" so that
						// we can use
						// it in a cascading menu too.
						// If created on a SWT control we would get an SWT
						// error...
						// Menu dummy= new Menu(ti.getParent());
						// Menu m= mc.getMenu(dummy);
						// dummy.dispose();
						if (mc != null) {
							Menu m = mc.getMenu(ti.getParent());
							if (m != null) {
								// position the menu below the drop down item
								Point point = ti.getParent().toDisplay(
										new Point(e.x, e.y));
								m.setLocation(point.x, point.y); // waiting
																	// for SWT
								// 0.42
								m.setVisible(true);
								return; // we don't fire the action
							}
						}
					}
				}
			}

			ExternalActionManager.IExecuteCallback callback = null;
			String actionDefinitionId = action.getActionDefinitionId();
			if (actionDefinitionId != null) {
				Object obj = ExternalActionManager.getInstance()
						.getCallback();
				if (obj instanceof ExternalActionManager.IExecuteCallback) {
					callback = (ExternalActionManager.IExecuteCallback) obj;
				}
			}

			// Ensure action is enabled first.
			// See 1GAN3M6: ITPUI:WINNT - Any IAction in the workbench can be
			// executed while disabled.
			if (action.isEnabled()) {
				boolean trace = Policy.TRACE_ACTIONS;

				long ms = 0L;
				if (trace) {
					ms = System.currentTimeMillis();
					System.out.println("Running action: " + action.getText()); //$NON-NLS-1$
				}				
				
				IPropertyChangeListener resultListener = null;
				if (callback != null) {
					resultListener = new IPropertyChangeListener() {
						@Override
						public void propertyChange(PropertyChangeEvent event) {
							// Check on result
							if (event.getProperty().equals(IAction.RESULT)) {
								if (event.getNewValue() instanceof Boolean) {
									result = (Boolean) event.getNewValue();
								}
							}
						}
					};
					action.addPropertyChangeListener(resultListener);
					callback.preExecute(action, e);
				}

				action.runWithEvent(e);

				if (callback != null) {
					if (result == null || result.equals(Boolean.TRUE)) {
						callback.postExecuteSuccess(action, Boolean.TRUE);
					} else {
						callback.postExecuteFailure(action,
								new ExecutionException(action.getText()
										+ " returned failure.")); //$NON-NLS-1$
					}
				}

				if (resultListener!=null) {
					result = null;
					action.removePropertyChangeListener(resultListener);
				}
				if (trace) {
					System.out.println((System.currentTimeMillis() - ms)
							+ " ms to run action: " + action.getText()); //$NON-NLS-1$
				}
			} else {
				if (callback != null) {
					callback.notEnabled(action, new NotEnabledException(action
							.getText()
							+ " is not enabled.")); //$NON-NLS-1$
				}
			}
		}
	}

	@Override
	public int hashCode() {
		return action.hashCode();
	}

	/**
	 * Returns whether the given action has any images.
	 * 
	 * @param actionToCheck
	 *            the action
	 * @return <code>true</code> if the action has any images,
	 *         <code>false</code> if not
	 */
	private boolean hasImages(IAction actionToCheck) {
		return actionToCheck.getImageDescriptor() != null
				|| actionToCheck.getHoverImageDescriptor() != null
				|| actionToCheck.getDisabledImageDescriptor() != null;
	}

	/**
	 * Returns whether the command corresponding to this action is active.
	 */
	private boolean isCommandActive() {
		IAction actionToCheck = getAction();

		if (actionToCheck != null) {
			String commandId = actionToCheck.getActionDefinitionId();
			ExternalActionManager.ICallback callback = ExternalActionManager
					.getInstance().getCallback();

			if (callback != null) {
				return callback.isActive(commandId);
			}
		}
		return true;
	}

	/**
	 * The action item implementation of this <code>IContributionItem</code>
	 * method returns <code>true</code> for menu items and <code>false</code>
	 * for everything else.
	 */
	@Override
	public boolean isDynamic() {
		if (widget instanceof MenuItem) {
			// Optimization. Only recreate the item is the check or radio style
			// has changed.
			boolean itemIsCheck = (widget.getStyle() & SWT.CHECK) != 0;
			boolean actionIsCheck = getAction() != null
					&& getAction().getStyle() == IAction.AS_CHECK_BOX;
			boolean itemIsRadio = (widget.getStyle() & SWT.RADIO) != 0;
			boolean actionIsRadio = getAction() != null
					&& getAction().getStyle() == IAction.AS_RADIO_BUTTON;
			return (itemIsCheck != actionIsCheck)
					|| (itemIsRadio != actionIsRadio);
		}
		return false;
	}

	@Override
	public boolean isEnabled() {
		return action != null && action.isEnabled();
	}

	/**
	 * Returns <code>true</code> if this item is allowed to enable,
	 * <code>false</code> otherwise.
	 * 
	 * @return if this item is allowed to be enabled
	 * @since 2.0
	 */
	protected boolean isEnabledAllowed() {
		if (getParent() == null) {
			return true;
		}
		Boolean value = getParent().getOverrides().getEnabled(this);
		return (value == null) ? true : value.booleanValue();
	}

	/**
	 * The <code>ActionContributionItem</code> implementation of this
	 * <code>ContributionItem</code> method extends the super implementation
	 * by also checking whether the command corresponding to this action is
	 * active.
	 */
	@Override
	public boolean isVisible() {
		return super.isVisible() && isCommandActive();
	}

	/**
	 * Sets the presentation mode, which is the bitwise-or of the
	 * <code>MODE_*</code> constants.
	 * 
	 * @param mode
	 *            the presentation mode settings
	 * 
	 * @since 3.0
	 */
	public void setMode(int mode) {
		this.mode = mode;
		update();
	}

	/**
	 * The action item implementation of this <code>IContributionItem</code>
	 * method calls <code>update(null)</code>.
	 */
	@Override
	public final void update() {
		update(null);
	}

	/**
	 * Synchronizes the UI with the given property.
	 * 
	 * @param propertyName
	 *            the name of the property, or <code>null</code> meaning all
	 *            applicable properties
	 */
	@Override
	public void update(String propertyName) {
		if (widget != null) {
			// determine what to do
			boolean textChanged = propertyName == null
					|| propertyName.equals(IAction.TEXT);
			boolean imageChanged = propertyName == null
					|| propertyName.equals(IAction.IMAGE);
			boolean tooltipTextChanged = propertyName == null
					|| propertyName.equals(IAction.TOOL_TIP_TEXT);
			boolean enableStateChanged = propertyName == null
					|| propertyName.equals(IAction.ENABLED)
					|| propertyName
							.equals(IContributionManagerOverrides.P_ENABLED);
			boolean checkChanged = (action.getStyle() == IAction.AS_CHECK_BOX || action
					.getStyle() == IAction.AS_RADIO_BUTTON)
					&& (propertyName == null || propertyName
							.equals(IAction.CHECKED));

			if (widget instanceof ToolItem) {
				ToolItem ti = (ToolItem) widget;
				String text = action.getText();
				// the set text is shown only if there is no image or if forced
				// by MODE_FORCE_TEXT
				boolean showText = text != null
						&& ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action));

				// only do the trimming if the text will be used
				if (showText && text != null) {
					text = Action.removeAcceleratorText(text);
					text = Action.removeMnemonics(text);
				}

				if (textChanged) {
					String textToSet = showText ? text : ""; //$NON-NLS-1$
					boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0;
					if (rightStyle || !ti.getText().equals(textToSet)) {
						// In addition to being required to update the text if
						// it
						// gets nulled out in the action, this is also a
						// workaround
						// for bug 50151: Using SWT.RIGHT on a ToolBar leaves
						// blank space
						ti.setText(textToSet);
					}
				}

				if (imageChanged) {
					// only substitute a missing image if it has no text
					updateImages(!showText);
				}

				if (tooltipTextChanged || textChanged) {
					String toolTip = action.getToolTipText();
					if ((toolTip == null) || (toolTip.length() == 0)) {
						toolTip = text;
					}

					ExternalActionManager.ICallback callback = ExternalActionManager
							.getInstance().getCallback();
					String commandId = action.getActionDefinitionId();
					if ((callback != null) && (commandId != null)
							&& (toolTip != null)) {
						String acceleratorText = callback
								.getAcceleratorText(commandId);
						if (acceleratorText != null
								&& acceleratorText.length() != 0) {
							toolTip = JFaceResources.format(
									"Toolbar_Tooltip_Accelerator", //$NON-NLS-1$
									new Object[] { toolTip, acceleratorText });
						}
					}

					// if the text is showing, then only set the tooltip if
					// different
					if (!showText || toolTip != null && !toolTip.equals(text)) {
						ti.setToolTipText(toolTip);
					} else {
						ti.setToolTipText(null);
					}
				}

				if (enableStateChanged) {
					boolean shouldBeEnabled = action.isEnabled()
							&& isEnabledAllowed();

					if (ti.getEnabled() != shouldBeEnabled) {
						ti.setEnabled(shouldBeEnabled);
					}
				}

				if (checkChanged) {
					boolean bv = action.isChecked();

					if (ti.getSelection() != bv) {
						ti.setSelection(bv);
					}
				}
				return;
			}

			if (widget instanceof MenuItem) {
				MenuItem mi = (MenuItem) widget;

				if (textChanged) {
					int accelerator = 0;
					String acceleratorText = null;
					IAction updatedAction = getAction();
					String text = null;
					accelerator = updatedAction.getAccelerator();
					ExternalActionManager.ICallback callback = ExternalActionManager
							.getInstance().getCallback();

					// Block accelerators that are already in use.
					if ((accelerator != 0) && (callback != null)
							&& (callback.isAcceleratorInUse(accelerator))) {
						accelerator = 0;
					}

					/*
					 * Process accelerators on GTK in a special way to avoid Bug
					 * 42009. We will override the native input method by
					 * allowing these reserved accelerators to be placed on the
					 * menu. We will only do this for "Ctrl+Shift+[0-9A-FU]".
					 */
					final String commandId = updatedAction
							.getActionDefinitionId();
					if ((Util.isGtk()) && (callback instanceof IBindingManagerCallback)
							&& (commandId != null)) {
						final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback;
						final IKeyLookup lookup = KeyLookupFactory.getDefault();
						final TriggerSequence[] triggerSequences = bindingManagerCallback
								.getActiveBindingsFor(commandId);
						for (int i = 0; i < triggerSequences.length; i++) {
							final TriggerSequence triggerSequence = triggerSequences[i];
							final Trigger[] triggers = triggerSequence
									.getTriggers();
							if (triggers.length == 1) {
								final Trigger trigger = triggers[0];
								if (trigger instanceof KeyStroke) {
									final KeyStroke currentKeyStroke = (KeyStroke) trigger;
									final int currentNaturalKey = currentKeyStroke
											.getNaturalKey();
									if ((currentKeyStroke.getModifierKeys() == (lookup
											.getCtrl() | lookup.getShift()))
											&& ((currentNaturalKey >= '0' && currentNaturalKey <= '9')
													|| (currentNaturalKey >= 'A' && currentNaturalKey <= 'F') || (currentNaturalKey == 'U'))) {
										accelerator = currentKeyStroke
												.getModifierKeys()
												| currentNaturalKey;
										acceleratorText = triggerSequence
												.format();
										break;
									}
								}
							}
						}
					}

					if (accelerator == 0) {
						if ((callback != null) && (commandId != null)) {
							acceleratorText = callback
									.getAcceleratorText(commandId);
						}
					}

					IContributionManagerOverrides overrides = null;

					if (getParent() != null) {
						overrides = getParent().getOverrides();
					}

					if (overrides != null) {
						text = getParent().getOverrides().getText(this);
					}

					mi.setAccelerator(accelerator);

					if (text == null) {
						text = updatedAction.getText();
					}

					if (text != null && acceleratorText == null) {
						// use extracted accelerator text in case accelerator
						// cannot be fully represented in one int (e.g.
						// multi-stroke keys)
						acceleratorText = LegacyActionTools
								.extractAcceleratorText(text);
						if (acceleratorText == null && accelerator != 0) {
							acceleratorText = Action
									.convertAccelerator(accelerator);
						}
					}

					if (text == null) {
						text = ""; //$NON-NLS-1$
					} else {
						text = Action.removeAcceleratorText(text);
					}

					if (acceleratorText == null) {
						mi.setText(text);
					} else {
						mi.setText(text + '\t' + acceleratorText);
					}
				}

				if (imageChanged) {
					updateImages(false);
				}

				if (enableStateChanged) {
					boolean shouldBeEnabled = action.isEnabled()
							&& isEnabledAllowed();

					if (mi.getEnabled() != shouldBeEnabled) {
						mi.setEnabled(shouldBeEnabled);
					}
				}

				if (checkChanged) {
					boolean bv = action.isChecked();

					if (mi.getSelection() != bv) {
						mi.setSelection(bv);
					}
				}

				return;
			}

			if (widget instanceof Button) {
				Button button = (Button) widget;

				if (imageChanged) {
					updateImages(false);
				}

				if (textChanged) {
					String text = action.getText();
					boolean showText = text != null && ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action));
					// only do the trimming if the text will be used
					if (showText) {
						text = Action.removeAcceleratorText(text);
					}
					String textToSet = showText ? text : ""; //$NON-NLS-1$
					button.setText(textToSet);
				}

				if (tooltipTextChanged) {
					button.setToolTipText(action.getToolTipText());
				}

				if (enableStateChanged) {
					boolean shouldBeEnabled = action.isEnabled()
							&& isEnabledAllowed();

					if (button.getEnabled() != shouldBeEnabled) {
						button.setEnabled(shouldBeEnabled);
					}
				}

				if (checkChanged) {
					boolean bv = action.isChecked();

					if (button.getSelection() != bv) {
						button.setSelection(bv);
					}
				}
				return;
			}
		}
	}

	/**
	 * Updates the images for this action.
	 * 
	 * @param forceImage
	 *            <code>true</code> if some form of image is compulsory, and
	 *            <code>false</code> if it is acceptable for this item to have
	 *            no image
	 * @return <code>true</code> if there are images for this action,
	 *         <code>false</code> if not
	 */
	private boolean updateImages(boolean forceImage) {

		ResourceManager parentResourceManager = JFaceResources.getResources();

		if (widget instanceof ToolItem) {
			if (USE_COLOR_ICONS) {
				ImageDescriptor image = action.getHoverImageDescriptor();
				if (image == null) {
					image = action.getImageDescriptor();
				}
				ImageDescriptor disabledImage = action
						.getDisabledImageDescriptor();

				// Make sure there is a valid image.
				if (image == null && forceImage) {
					image = ImageDescriptor.getMissingImageDescriptor();
				}

				LocalResourceManager localManager = new LocalResourceManager(
						parentResourceManager);

				// performance: more efficient in SWT to set disabled and hot
				// image before regular image
				((ToolItem) widget)
						.setDisabledImage(disabledImage == null ? null
								: localManager
										.createImageWithDefault(disabledImage));
				((ToolItem) widget).setImage(image == null ? null
						: localManager.createImageWithDefault(image));

				disposeOldImages();
				imageManager = localManager;

				return image != null;
			}
			ImageDescriptor image = action.getImageDescriptor();
			ImageDescriptor hoverImage = action.getHoverImageDescriptor();
			ImageDescriptor disabledImage = action.getDisabledImageDescriptor();

			// If there is no regular image, but there is a hover image,
			// convert the hover image to gray and use it as the regular image.
			if (image == null && hoverImage != null) {
				image = ImageDescriptor.createWithFlags(action
						.getHoverImageDescriptor(), SWT.IMAGE_GRAY);
			} else {
				// If there is no hover image, use the regular image as the
				// hover image,
				// and convert the regular image to gray
				if (hoverImage == null && image != null) {
					hoverImage = image;
					image = ImageDescriptor.createWithFlags(action
							.getImageDescriptor(), SWT.IMAGE_GRAY);
				}
			}

			// Make sure there is a valid image.
			if (hoverImage == null && image == null && forceImage) {
				image = ImageDescriptor.getMissingImageDescriptor();
			}

			// Create a local resource manager to remember the images we've
			// allocated for this tool item
			LocalResourceManager localManager = new LocalResourceManager(
					parentResourceManager);

			// performance: more efficient in SWT to set disabled and hot image
			// before regular image
			((ToolItem) widget).setDisabledImage(disabledImage == null ? null
					: localManager.createImageWithDefault(disabledImage));
			((ToolItem) widget).setHotImage(hoverImage == null ? null
					: localManager.createImageWithDefault(hoverImage));
			((ToolItem) widget).setImage(image == null ? null : localManager
					.createImageWithDefault(image));

			// Now that we're no longer referencing the old images, clear them
			// out.
			disposeOldImages();
			imageManager = localManager;

			return image != null;
		} else if (widget instanceof Item || widget instanceof Button) {

			// Use hover image if there is one, otherwise use regular image.
			ImageDescriptor image = action.getHoverImageDescriptor();
			if (image == null) {
				image = action.getImageDescriptor();
			}
			// Make sure there is a valid image.
			if (image == null && forceImage) {
				image = ImageDescriptor.getMissingImageDescriptor();
			}

			// Create a local resource manager to remember the images we've
			// allocated for this widget
			LocalResourceManager localManager = new LocalResourceManager(
					parentResourceManager);

			if (widget instanceof Item) {
				((Item) widget).setImage(image == null ? null : localManager
						.createImageWithDefault(image));
			} else if (widget instanceof Button) {
				((Button) widget).setImage(image == null ? null : localManager
						.createImageWithDefault(image));
			}

			// Now that we're no longer referencing the old images, clear them
			// out.
			disposeOldImages();
			imageManager = localManager;

			return image != null;
		}
		return false;
	}

	/**
	 * Dispose any images allocated for this contribution item
	 */
	private void disposeOldImages() {
		if (imageManager != null) {
			imageManager.dispose();
			imageManager = null;
		}
	}

	/**
	 * Shorten the given text <code>t</code> so that its length doesn't exceed
	 * the width of the given ToolItem.The default implementation replaces
	 * characters in the center of the original string with an ellipsis ("...").
	 * Override if you need a different strategy.
	 * 
	 * @param textValue
	 *            the text to shorten
	 * @param item
	 *            the tool item the text belongs to
	 * @return the shortened string
	 * 
	 */
	protected String shortenText(String textValue, ToolItem item) {
		if (textValue == null) {
			return null;
		}

		GC gc = new GC(item.getParent());

		int maxWidth = item.getImage().getBounds().width * 4;

		if (gc.textExtent(textValue).x < maxWidth) {
			gc.dispose();
			return textValue;
		}

		for (int i = textValue.length(); i > 0; i--) {
			String test = textValue.substring(0, i);
			test = test + ellipsis;
			if (gc.textExtent(test).x < maxWidth) {
				gc.dispose();
				return test;
			}

		}
		gc.dispose();
		// If for some reason we fall through abort
		return textValue;
	}

	@Override
	public void dispose() {
		if (widget != null) {
			widget.dispose();
			widget = null;
		}
		holdMenu = null;
	}
	
	/**
	 * Handle show and hide on the proxy menu for IAction.AS_DROP_DOWN_MENU
	 * actions.
	 * 
	 * @return the appropriate listener
	 * @since 3.4
	 */
	private Listener getMenuCreatorListener() {
		if (menuCreatorListener == null) {
			menuCreatorListener = new Listener() {
				@Override
				public void handleEvent(Event event) {
					switch (event.type) {
					case SWT.Show:
						handleShowProxy((Menu) event.widget);
						break;
					case SWT.Hide:
						handleHideProxy((Menu) event.widget);
						break;
					}
				}
			};
		}
		return menuCreatorListener;
	}
	
	/**
	 * This is the easiest way to hold the menu until we can swap it in to the
	 * proxy.
	 */
	private Menu holdMenu = null;

	private boolean menuCreatorCalled = false;
	
	/**
	 * The proxy menu is being shown, we better get the real menu.
	 * 
	 * @param proxy
	 *            the proxy menu
	 * @since 3.4
	 */
	private void handleShowProxy(Menu proxy) {
		proxy.removeListener(SWT.Show, getMenuCreatorListener());
		IMenuCreator mc = action.getMenuCreator();
		menuCreatorCalled  = true;
		if (mc == null) {
			return;
		}
		holdMenu = mc.getMenu(proxy.getParentMenu());
		if (holdMenu == null) {
			return;
		}
		copyMenu(holdMenu, proxy);
	}

	/**
	 * Create MenuItems in the proxy menu that can execute the real menu items
	 * if selected. Create proxy menus for any real item submenus.
	 * 
	 * @param realMenu
	 *            the real menu to copy from
	 * @param proxy
	 *            the proxy menu to populate
	 * @since 3.4
	 */
	private void copyMenu(Menu realMenu, Menu proxy) {
		if (realMenu.isDisposed() || proxy.isDisposed()) {
			return;
		}
		
		// we notify the real menu so it can populate itself if it was
		// listening for SWT.Show
		realMenu.notifyListeners(SWT.Show, null);

		final Listener passThrough = new Listener() {
			@Override
			public void handleEvent(Event event) {
				if (!event.widget.isDisposed()) {
					Widget realItem = (Widget) event.widget.getData();
					if (!realItem.isDisposed()) {
						int style = event.widget.getStyle();
						if (event.type == SWT.Selection
								&& ((style & (SWT.TOGGLE | SWT.CHECK | SWT.RADIO)) != 0)
								&& realItem instanceof MenuItem) {
							((MenuItem) realItem)
									.setSelection(((MenuItem) event.widget)
											.getSelection());
						}
						event.widget = realItem;
						realItem.notifyListeners(event.type, event);
					}
				}
			}
		};

		MenuItem[] items = realMenu.getItems();
		for (int i = 0; i < items.length; i++) {
			final MenuItem realItem = items[i];
			final MenuItem proxyItem = new MenuItem(proxy, realItem.getStyle());
			proxyItem.setData(realItem);
			proxyItem.setAccelerator(realItem.getAccelerator());
			proxyItem.setEnabled(realItem.getEnabled());
			proxyItem.setImage(realItem.getImage());
			proxyItem.setSelection(realItem.getSelection());
			proxyItem.setText(realItem.getText());

			// pass through any events
			proxyItem.addListener(SWT.Selection, passThrough);
			proxyItem.addListener(SWT.Arm, passThrough);
			proxyItem.addListener(SWT.Help, passThrough);

			final Menu itemMenu = realItem.getMenu();
			if (itemMenu != null) {
				// create a proxy for any sub menu items
				final Menu subMenu = new Menu(proxy);
				subMenu.setData(itemMenu);
				proxyItem.setMenu(subMenu);
				subMenu.addListener(SWT.Show, new Listener() {
					@Override
					public void handleEvent(Event event) {
						event.widget.removeListener(SWT.Show, this);
						if (event.type == SWT.Show) {
							copyMenu(itemMenu, subMenu);
						}
					}
				});
				subMenu.addListener(SWT.Help, passThrough);
				subMenu.addListener(SWT.Hide, passThrough);
			}
		}
	}
	
	/**
	 * The proxy menu is being hidden, so we need to make it go away.
	 * 
	 * @param proxy
	 *            the proxy menu
	 * @since 3.4
	 */
	private void handleHideProxy(final Menu proxy) {
		proxy.removeListener(SWT.Hide, getMenuCreatorListener());
		proxy.getDisplay().asyncExec(new Runnable() {
			@Override
			public void run() {
				if (!proxy.isDisposed()) {
					MenuItem parentItem = proxy.getParentItem();
					proxy.dispose();
					parentItem.setMenu(holdMenu);
				}
				if (holdMenu != null && !holdMenu.isDisposed()) {
					holdMenu.notifyListeners(SWT.Hide, null);
				}
				holdMenu = null;
			}
		});
	}
	
	/**
	 * Return the widget associated with this contribution item. It should not
	 * be cached, as it can be disposed and re-created by its containing
	 * ContributionManager, which controls all of the widgets lifecycle methods.
	 * <p>
	 * This can be used to set layout data on the widget if appropriate. The
	 * actual type of the widget can be any valid control for this
	 * ContributionItem's current ContributionManager.
	 * </p>
	 * 
	 * @return the widget, or <code>null</code> depending on the lifecycle.
	 * @since 3.4
	 */
	public Widget getWidget() {
		return widget;
	}
}

Back to the top