Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b5590ccf094075c6cfa8dfeccc8b3cf9a6aab67d (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
/*******************************************************************************
 * Copyright (c) 2005, 2012 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.ui.internal.keys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.eclipse.core.commands.CommandManager;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.e4.core.commands.ECommandService;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.bindings.EBindingService;
import org.eclipse.e4.ui.bindings.keys.KeyBindingDispatcher;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.commands.MBindingContext;
import org.eclipse.e4.ui.model.application.commands.MBindingTable;
import org.eclipse.e4.ui.model.application.commands.MCommand;
import org.eclipse.e4.ui.model.application.commands.MCommandsFactory;
import org.eclipse.e4.ui.model.application.commands.MKeyBinding;
import org.eclipse.e4.ui.model.application.commands.MParameter;
import org.eclipse.e4.ui.model.application.commands.impl.CommandsFactoryImpl;
import org.eclipse.jface.bindings.Binding;
import org.eclipse.jface.bindings.BindingManager;
import org.eclipse.jface.bindings.IBindingManagerListener;
import org.eclipse.jface.bindings.Scheme;
import org.eclipse.jface.bindings.TriggerSequence;
import org.eclipse.jface.bindings.keys.KeySequence;
import org.eclipse.jface.util.Util;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.keys.IBindingService;

/**
 * <p>
 * Provides services related to the binding architecture (e.g., keyboard
 * shortcuts) within the workbench. This service can be used to access the
 * currently active bindings, as well as the current state of the binding
 * architecture.
 * </p>
 * 
 * @since 3.1
 */
public final class BindingService implements IBindingService {

	@Inject
	private MApplication application;

	@Inject
	private EBindingService bindingService;

	@Inject
	private ECommandService commandService;

	@Inject
	private CommandManager commandManager;

	@Inject
	private BindingManager manager;

	@Inject
	@Optional
	private KeyBindingDispatcher dispatcher;

	private BindingPersistence bp;

	private Map<String, MBindingContext> bindingContexts = new HashMap<String, MBindingContext>();

	private String[] activeSchemeIds;
	
	/**
	 * Key assist dialog for workbench key bindings, lazily created and cached
	 */
	private GlobalKeyAssistDialog keyAssistDialog;

	private IEclipseContext context;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.services.IDisposable#dispose()
	 */
	public void dispose() {
		bp.dispose();
	}

	@Inject
	public void setContext(IEclipseContext context) {
		this.context = context;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#addBindingManagerListener(org.eclipse
	 * .jface.bindings.IBindingManagerListener)
	 */
	public void addBindingManagerListener(IBindingManagerListener listener) {
		manager.addBindingManagerListener(listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#removeBindingManagerListener(org.
	 * eclipse.jface.bindings.IBindingManagerListener)
	 */
	public void removeBindingManagerListener(IBindingManagerListener listener) {
		manager.removeBindingManagerListener(listener);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getActiveBindingsFor(org.eclipse.
	 * core.commands.ParameterizedCommand)
	 */
	public TriggerSequence[] getActiveBindingsFor(ParameterizedCommand parameterizedCommand) {
		Collection<TriggerSequence> seq = bindingService.getSequencesFor(parameterizedCommand);
		return seq.toArray(new TriggerSequence[seq.size()]);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getActiveBindingsFor(java.lang.String
	 * )
	 */
	public TriggerSequence[] getActiveBindingsFor(String commandId) {
		return getActiveBindingsFor(commandService.createCommand(commandId, null));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getActiveScheme()
	 */
	public Scheme getActiveScheme() {
		return manager.getActiveScheme();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getBestActiveBindingFor(org.eclipse
	 * .core.commands.ParameterizedCommand)
	 */
	public TriggerSequence getBestActiveBindingFor(ParameterizedCommand command) {
		TriggerSequence seq = bindingService.getBestSequenceFor(command);
		return seq;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getBestActiveBindingFor(java.lang
	 * .String)
	 */
	public TriggerSequence getBestActiveBindingFor(String commandId) {
		ParameterizedCommand cmd = commandService.createCommand(commandId, null);
		return bindingService.getBestSequenceFor(cmd);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getBestActiveBindingFormattedFor(
	 * java.lang.String)
	 */
	public String getBestActiveBindingFormattedFor(String commandId) {
		TriggerSequence sequence = bindingService.getBestSequenceFor(commandService.createCommand(
				commandId, null));
		return sequence == null ? null : sequence.format();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getBindings()
	 */
	public Binding[] getBindings() {
		return manager.getBindings();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getBuffer()
	 */
	public TriggerSequence getBuffer() {
		if (dispatcher == null) {
			return KeySequence.getInstance();
		}
		return dispatcher.getBuffer();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getDefaultSchemeId()
	 */
	public String getDefaultSchemeId() {
		return BindingPersistence.getDefaultSchemeId();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getDefinedSchemes()
	 */
	public Scheme[] getDefinedSchemes() {
		return manager.getDefinedSchemes();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getLocale()
	 */
	public String getLocale() {
		return manager.getLocale();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getPartialMatches(org.eclipse.jface
	 * .bindings.TriggerSequence)
	 */
	public Map getPartialMatches(TriggerSequence trigger) {
		final TriggerSequence[] prefixes = trigger.getPrefixes();
		final int prefixesLength = prefixes.length;
		if (prefixesLength == 0) {
			return Collections.EMPTY_MAP;
		}

		Collection<Binding> partialMatches = bindingService.getPartialMatches(trigger);
		Map<TriggerSequence, Object> prefixTable = new HashMap<TriggerSequence, Object>();
		for (Binding binding : partialMatches) {
			for (int i = 0; i < prefixesLength; i++) {
				final TriggerSequence prefix = prefixes[i];
				final Object value = prefixTable.get(prefix);
				if ((prefixTable.containsKey(prefix)) && (value instanceof Map)) {
					((Map) value).put(prefixTable, binding);
				} else {
					final Map map = new HashMap();
					prefixTable.put(prefix, map);
					map.put(prefixTable, binding);
				}
			}
		}
		return prefixTable;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getPerfectMatch(org.eclipse.jface
	 * .bindings.TriggerSequence)
	 */
	public Binding getPerfectMatch(TriggerSequence trigger) {
		return bindingService.getPerfectMatch(trigger);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getPlatform()
	 */
	public String getPlatform() {
		return Util.getWS();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#getScheme(java.lang.String)
	 */
	public Scheme getScheme(String schemeId) {
		return manager.getScheme(schemeId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#isKeyFilterEnabled()
	 */
	public boolean isKeyFilterEnabled() {
		return dispatcher == null ? false : dispatcher.getKeyDownFilter().isEnabled();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#isPartialMatch(org.eclipse.jface.
	 * bindings.TriggerSequence)
	 */
	public boolean isPartialMatch(TriggerSequence trigger) {
		return bindingService.isPartialMatch(trigger);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#isPerfectMatch(org.eclipse.jface.
	 * bindings.TriggerSequence)
	 */
	public boolean isPerfectMatch(TriggerSequence trigger) {
		return bindingService.isPerfectMatch(trigger);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#openKeyAssistDialog()
	 */
	public void openKeyAssistDialog() {
		if (keyAssistDialog == null) {
			Display.getCurrent();
			keyAssistDialog = new GlobalKeyAssistDialog(context, dispatcher);
		}
		if (keyAssistDialog.getShell() == null) {
			keyAssistDialog.setParentShell(Display.getCurrent().getActiveShell());
		}
		keyAssistDialog.open();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#readRegistryAndPreferences(org.eclipse
	 * .ui.commands.ICommandService)
	 */
	public void readRegistryAndPreferences(ICommandService commandService) {
		if (bp == null) {
			bp = new BindingPersistence(manager, commandManager) {
				@Override
				public void reRead() {
					super.reRead();
					// after having read the registry and preferences, persist
					// and update the model
					persistToModel(manager.getActiveScheme());
				}
			};
		}
		bp.read();
	}

	private void saveLegacyPreferences(Scheme activeScheme, Binding[] bindings) throws IOException {
		BindingPersistence.write(activeScheme, bindings);
		try {
			manager.setActiveScheme(activeScheme);
		} catch (final NotDefinedException e) {
			WorkbenchPlugin.log("The active scheme is not currently defined.", //$NON-NLS-1$
					WorkbenchPlugin.getStatus(e));
		}
		manager.setBindings(bindings);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#savePreferences(org.eclipse.jface
	 * .bindings.Scheme, org.eclipse.jface.bindings.Binding[])
	 */
	public void savePreferences(Scheme activeScheme, Binding[] bindings) throws IOException {
		saveLegacyPreferences(activeScheme, bindings);
		persistToModel(activeScheme);
	}

	private void persistToModel(Scheme activeScheme) {
		// save the active scheme to the model
		writeSchemeToModel(activeScheme);
		activeSchemeIds = getSchemeIds(activeScheme.getId());

		// weeds out any of the deleted system bindings using the binding
		// manager
		HashSet<Binding> activeBindings = new HashSet<Binding>(
				manager.getActiveBindingsDisregardingContextFlat());

		// get all of the (active) model bindings that point to the actual runtime
		// bindings
		HashMap<Binding, MKeyBinding> bindingToKey = new HashMap<Binding, MKeyBinding>();
		for (MBindingTable table : application.getBindingTables()) {
			for (MKeyBinding modelBinding : table.getBindings()) {
				final Object obj = modelBinding.getTransientData().get(
						EBindingService.MODEL_TO_BINDING_KEY);
				if (obj instanceof Binding) {
					bindingToKey.put((Binding) obj, modelBinding);
				}
			}
		}

		// go through each of the (active) bindings in the model to see if there are any
		// bindings that we should remove
		final HashSet<Binding> deleted = new HashSet<Binding>(bindingToKey.keySet());
		deleted.removeAll(activeBindings);
		for (Binding binding : deleted) {
			if (binding.getType() == Binding.USER) {
				removeBinding(binding);
			} else {
				final MKeyBinding model = bindingToKey.get(binding);
				if (!model.getTags().contains(EBindingService.DELETED_BINDING_TAG)) {
					model.getTags().add(EBindingService.DELETED_BINDING_TAG);
				}
			}
		}
		
		// go through each of the active bindings (from the binding manager) to
		// see if there are any bindings that we should add to the runtime
		for (Binding binding : activeBindings) {
			final MKeyBinding model = bindingToKey.get(binding);
			MKeyBinding toAddModel = model;
			Binding toAddBinding = binding;

			// if we've switched schemes then we need to check to see if we
			// should override any of the old bindings
			final Binding conflict = bindingService.getPerfectMatch(binding.getTriggerSequence());

			if (conflict != null && conflict.getContextId().equals(binding.getContextId())) {
				final int rc = compareTo(conflict, binding);
				if (rc < 0) {
					// we need to delete the existing binding
					final MKeyBinding conflictModel = bindingToKey.get(conflict);
					if (conflict.getType() == Binding.USER) {
						removeBinding(conflict);
					} else if (conflictModel != null) {
						if (!conflictModel.getTags().contains(EBindingService.DELETED_BINDING_TAG)) {
							conflictModel.getTags().add(EBindingService.DELETED_BINDING_TAG);
						}
					}
				} else if (rc > 0) {
					// the existing binding is correct
					// we need to delete the new binding
					if (binding.getType() == Binding.USER) {
						removeBinding(binding);
					} else if (model != null) {
						if (!model.getTags().contains(EBindingService.DELETED_BINDING_TAG)) {
							model.getTags().add(EBindingService.DELETED_BINDING_TAG);
						}
					}
					// make sure we don't re-add them
					toAddModel = null;
					toAddBinding = null;
				}
			}
			if (toAddModel != null) {
				if (toAddModel.getTags().contains(EBindingService.DELETED_BINDING_TAG)) {
					toAddModel.getTags().remove(EBindingService.DELETED_BINDING_TAG);
				}
			} else if (toAddBinding != null) {
				addBinding(toAddBinding);
			}

		}
	}

	private final String[] getSchemeIds(String schemeId) {
		final List<String> strings = new ArrayList<String>();
		while (schemeId != null) {
			strings.add(schemeId);
			try {
				schemeId = getScheme(schemeId).getParentId();
			} catch (final NotDefinedException e) {
				return new String[0];
			}
		}

		return strings.toArray(new String[strings.size()]);
	}

	/*
	 * Copied from
	 * org.eclipse.jface.bindings.BindingManager.compareSchemes(String, String)
	 * 
	 * Returns an in based on scheme 1 < scheme 2
	 */
	private final int compareSchemes(final String schemeId1, final String schemeId2) {
		if (activeSchemeIds == null) {
			return 0;
		}
		if (!schemeId2.equals(schemeId1)) {
			for (int i = 0; i < activeSchemeIds.length; i++) {
				final String schemePointer = activeSchemeIds[i];
				if (schemeId2.equals(schemePointer)) {
					return 1;
				} else if (schemeId1.equals(schemePointer)) {
					return -1;
				}
			}
		}
		return 0;
	}

	/**
	 * Compare 2 bindings, taking into account Scheme and type.
	 * 
	 * @param current
	 *            the existing binding
	 * @param addition
	 *            the incoming binding
	 * @return an int indicating current > addition
	 */
	private int compareTo(Binding current, Binding addition) {
		final Scheme s1 = manager.getScheme(current.getSchemeId());
		final Scheme s2 = manager.getScheme(addition.getSchemeId());
		if (!s1.equals(s2)) {
			int rc = compareSchemes(s1.getId(), s2.getId());
			if (rc != 0) {
				// this is because the compare is inverted
				return rc > 0 ? -1 : 1;
			}
		}
		return current.getType() - addition.getType();
	}


	private void writeSchemeToModel(Scheme activeScheme) {
		List<String> tags = application.getTags();
		boolean found = false;
		// replace the old scheme id
		Iterator<String> i = tags.iterator();
		while (i.hasNext() && !found) {
			String tag = i.next();
			if (tag.startsWith(EBindingService.ACTIVE_SCHEME_TAG)) {
				i.remove();
				found = true;
			}
		}
		tags.add(EBindingService.ACTIVE_SCHEME_TAG + ":" + activeScheme.getId()); //$NON-NLS-1$
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.keys.IBindingService#setKeyFilterEnabled(boolean)
	 */
	public void setKeyFilterEnabled(boolean enabled) {
		if (dispatcher != null) {
			dispatcher.getKeyDownFilter().setEnabled(enabled);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.keys.IBindingService#getConflictsFor(org.eclipse.jface
	 * .bindings.TriggerSequence)
	 */
	public Collection<Binding> getConflictsFor(TriggerSequence sequence) {
		return bindingService.getConflictsFor(sequence);
	}

	public MBindingContext getBindingContext(String id) {
		// cache
		MBindingContext result = bindingContexts.get(id);
		if (result == null) {
			// search
			result = searchContexts(id, application.getRootContext());
			if (result == null) {
				// create
				result = MCommandsFactory.INSTANCE.createBindingContext();
				result.setElementId(id);
				result.setName("Auto::" + id); //$NON-NLS-1$
				application.getRootContext().add(result);
			}
			if (result != null) {
				bindingContexts.put(id, result);
			}
		}
		return result;
	}

	/**
	 * @param id
	 * @param rootContext
	 * @return
	 */
	private MBindingContext searchContexts(String id, List<MBindingContext> rootContext) {
		for (MBindingContext context : rootContext) {
			if (context.getElementId().equals(id)) {
				return context;
			}
			MBindingContext result = searchContexts(id, context.getChildren());
			if (result != null) {
				return result;
			}
		}
		return null;
	}

	/**
	 * TODO Promote this method to API.
	 * <p>
	 * Adds a single new binding to the existing array of bindings. If the array
	 * is currently <code>null</code>, then a new array is created and this
	 * binding is added to it. This method does not detect duplicates.
	 * </p>
	 * <p>
	 * This method completes in amortized <code>O(1)</code>.
	 * </p>
	 * 
	 * @param binding
	 *            The binding to be added; must not be <code>null</code>.
	 */
	public final void addBinding(final Binding binding) {
		MBindingTable table = getMTable(binding.getContextId());
		createORupdateMKeyBinding(application, table, binding);
	}

	/**
	 * @param contextId
	 * @return
	 */
	private MBindingTable getMTable(String contextId) {
		for (MBindingTable bt : application.getBindingTables()) {
			if (bt.getBindingContext().getElementId().equals(contextId)) {
				return bt;
			}
		}
		// create a new table if we couldn't find one
		MBindingTable table = CommandsFactoryImpl.eINSTANCE.createBindingTable();
		table.setBindingContext(getBindingContext(contextId));
		table.setElementId(contextId);
		application.getBindingTables().add(table);
		return table;

	}

	static private boolean isSameBinding(MKeyBinding existingBinding, MCommand cmd, Binding binding) {
		// see org.eclipse.jface.bindings.Binding#equals(final Object object)
		if (!cmd.equals(existingBinding.getCommand()))
			return false;
		String existingKeySequence = existingBinding.getKeySequence();
		if (existingKeySequence == null)
			return false;
		if (!existingKeySequence.equals(binding.getTriggerSequence().format()))
			return false;

		// tags to look for:
		ArrayList<String> expectedTagList = new ArrayList<String>(4);

		String schemeId = binding.getSchemeId();
		if (schemeId != null && !schemeId.equals(BindingPersistence.getDefaultSchemeId())) {
			expectedTagList.add(EBindingService.SCHEME_ID_ATTR_TAG + ":" + schemeId); //$NON-NLS-1$
		}
		String locale = binding.getLocale();
		if (locale != null) {
			expectedTagList.add(EBindingService.LOCALE_ATTR_TAG + ":" + locale); //$NON-NLS-1$
		}
		String platform = binding.getPlatform();
		if (platform != null) {
			expectedTagList.add(EBindingService.PLATFORM_ATTR_TAG + ":" + platform); //$NON-NLS-1$
		}
		if (binding.getType() == Binding.USER) {
			expectedTagList.add(EBindingService.TYPE_ATTR_TAG + ":user"); //$NON-NLS-1$
		}
		return existingBinding.getTags().equals(expectedTagList);
	}

	// TBD the "update" procedure should not typically be run.
	// Add some sort of timestamp on the source files and update
	// only when it changes
	// TBD placement: this should be in the "3.x bridge" code
	static public MKeyBinding createORupdateMKeyBinding(MApplication application,
			MBindingTable table,
			Binding binding) {
		ParameterizedCommand parmCmd = binding.getParameterizedCommand();

		String id = parmCmd.getId();
		MCommand cmd = null;
		for (MCommand appCommand : application.getCommands()) {
			if (id.equals(appCommand.getElementId())) {
				cmd = appCommand;
				break;
			}
		}
		if (cmd == null) {
			return null;
		}

		MKeyBinding keyBinding = null;
		for (MKeyBinding existingBinding : table.getBindings()) {
			Binding b = (Binding) existingBinding.getTransientData().get(
					EBindingService.MODEL_TO_BINDING_KEY);
			if (binding.equals(b)) {
				keyBinding = existingBinding;
				break;
			}
			if (isSameBinding(existingBinding, cmd, binding)) {
				keyBinding = existingBinding;
				break;
			}
		}

		if (keyBinding == null) {
			keyBinding = CommandsFactoryImpl.eINSTANCE.createKeyBinding();
			keyBinding.setCommand(cmd);
			table.getBindings().add(keyBinding);
		}
		keyBinding.setKeySequence(binding.getTriggerSequence().format());

		for (Object obj : parmCmd.getParameterMap().entrySet()) {
			@SuppressWarnings({ "unchecked" })
			Map.Entry<String, String> entry = (Map.Entry<String, String>) obj;

			String paramID = entry.getKey();
			if (paramID == null)
				continue;
			List<MParameter> bindingParams = keyBinding.getParameters();
			MParameter p = null;
			for (MParameter param : bindingParams) {
				if (paramID.equals(param.getElementId())) {
					p = param;
					break;
				}
			}
			if (p == null) {
				p = CommandsFactoryImpl.eINSTANCE.createParameter();
				p.setElementId(entry.getKey());
				keyBinding.getParameters().add(p);
			}
			p.setName(entry.getKey());
			p.setValue(entry.getValue());
		}

		List<String> tags = keyBinding.getTags();
		// just add the 'schemeId' tag if the binding is for anything other than
		// the default scheme
		if (binding.getSchemeId() != null
				&& !binding.getSchemeId().equals(BindingPersistence.getDefaultSchemeId())) {
			tags.add(EBindingService.SCHEME_ID_ATTR_TAG + ":" + binding.getSchemeId()); //$NON-NLS-1$
		}
		if (binding.getLocale() != null) {
			tags.add(EBindingService.LOCALE_ATTR_TAG + ":" + binding.getLocale()); //$NON-NLS-1$
		}
		if (binding.getPlatform() != null) {
			tags.add(EBindingService.PLATFORM_ATTR_TAG + ":" + binding.getPlatform()); //$NON-NLS-1$
		}
		// just add the 'type' tag if it's a user binding
		if (binding.getType() == Binding.USER) {
			tags.add(EBindingService.TYPE_ATTR_TAG + ":user"); //$NON-NLS-1$
		}
		keyBinding.getTransientData().put(EBindingService.MODEL_TO_BINDING_KEY, binding);
		return keyBinding;
	}

	private MKeyBinding findMKeyBinding(MBindingTable table, Binding binding) {
		List<MKeyBinding> mBindings = table.getBindings();

		String bindingSchemeId = binding.getSchemeId() == null ? IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID
				: binding.getSchemeId();

		if (binding.getParameterizedCommand() != null) {
			String commandId = binding.getParameterizedCommand().getId();

			for (MKeyBinding curr : mBindings) {
				Binding transientBinding = (Binding) curr.getTransientData().get(
						EBindingService.MODEL_TO_BINDING_KEY);
				if (transientBinding != null) {
					if (binding.equals(transientBinding)) {
						return curr;
					}
					continue;
				}
				// check equality
				if (curr.getKeySequence().equals(binding.getTriggerSequence().format())
						&& curr.getCommand() != null
						&& curr.getCommand().getElementId().equals(commandId)) {

					String schemeId = IBindingService.DEFAULT_DEFAULT_ACTIVE_SCHEME_ID;
					List<String> tags = curr.getTags();
					// grab the scheme id from the tags
					for (String tag : tags) {
						if (tag.startsWith(EBindingService.SCHEME_ID_ATTR_TAG)) {
							schemeId = tag.substring(9);
							break;
						}
					}
					// if the scheme ids are the same, then we found the
					// MKeyBinding
					if (schemeId.equals(bindingSchemeId)) {
						return curr;
					}
				}
			}
		}
		return null;
	}

	/**
	 * Remove the specific binding by identity. Does nothing if the binding is
	 * not in the manager.
	 * 
	 * @param binding
	 *            The binding to be removed; must not be <code>null</code>.
	 */
	public final void removeBinding(final Binding binding) {
		MKeyBinding mKeyBinding;
		MBindingTable table = null;
		for (MBindingTable bt : application.getBindingTables()) {
			if (bt.getBindingContext().getElementId().equals(binding.getContextId())) {
				table = bt;
				break;
			}
		}
		if (table == null) {
			return;
		}

		// if we're removing a user binding, just remove it from the model and
		// the listeners will take care of removing the binding from the runtime
		// system
		if (binding.getType() == Binding.USER) {
			mKeyBinding = this.findMKeyBinding(table, binding);
			if (mKeyBinding != null) {
				table.getBindings().remove(mKeyBinding);
			}
		}
		// if we're removing a system binding, then find the model binding, add
		// a 'deleted' tag, and explicitly remove the binding from the runtime
		// system
		else {
			mKeyBinding = this.findMKeyBinding(table, binding);
			if (mKeyBinding != null) {
				mKeyBinding.getTags().add(EBindingService.DELETED_BINDING_TAG);
			}
		}
	}

	public BindingManager getBindingManager() {
		return manager;
	}

	public Collection<Binding> getActiveBindings() {
		return bindingService.getActiveBindings();
	}

	public WorkbenchKeyboard getKeyboard() {
		return new WorkbenchKeyboard(dispatcher);
	}
}

Back to the top