Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b2511a9c77c489b8fd41d6c451c78430b85d57b5 (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
/*******************************************************************************
 * Copyright (c) 2007, 2011 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.model;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.ResourceBundle;
import org.eclipse.core.commands.CommandManager;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.commands.contexts.ContextManager;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.bindings.Binding;
import org.eclipse.jface.bindings.BindingManager;
import org.eclipse.jface.bindings.Scheme;
import org.eclipse.jface.bindings.keys.KeyBinding;
import org.eclipse.jface.bindings.keys.KeySequence;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.keys.KeysPreferencePage;
import org.eclipse.ui.internal.keys.NewKeysPreferenceMessages;
import org.eclipse.ui.internal.misc.StatusUtil;
import org.eclipse.ui.internal.util.Util;
import org.eclipse.ui.keys.IBindingService;
import org.eclipse.ui.services.IServiceLocator;
import org.eclipse.ui.statushandlers.StatusManager;

/**
 * @since 3.4
 * 
 */
public class KeyController {
	private static final String DELIMITER = ","; //$NON-NLS-1$
	private static final String ESCAPED_QUOTE = "\""; //$NON-NLS-1$
	private static final String REPLACEMENT = "\"\""; //$NON-NLS-1$
	/**
	 * The resource bundle from which translations can be retrieved.
	 */
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
			.getBundle(KeysPreferencePage.class.getName());
	private ListenerList eventManager = null;
	private BindingManager fBindingManager;
	private ContextModel contextModel;
	private SchemeModel fSchemeModel;
	private BindingModel bindingModel;
	private boolean notifying = true;
	private ConflictModel conflictModel;
	private IServiceLocator serviceLocator;

	private ListenerList getEventManager() {
		if (eventManager == null) {
			eventManager = new ListenerList(ListenerList.IDENTITY);
		}
		return eventManager;
	}

	public void setNotifying(boolean b) {
		notifying = b;
	}

	public boolean isNotifying() {
		return notifying;
	}

	public void firePropertyChange(Object source, String propId, Object oldVal,
			Object newVal) {
		if (!isNotifying()) {
			return;
		}
		if (Util.equals(oldVal, newVal)) {
			return;
		}

		Object[] listeners = getEventManager().getListeners();
		PropertyChangeEvent event = new PropertyChangeEvent(source, propId,
				oldVal, newVal);
		for (int i = 0; i < listeners.length; i++) {
			((IPropertyChangeListener) listeners[i]).propertyChange(event);
		}
	}

	public void addPropertyChangeListener(IPropertyChangeListener listener) {
		getEventManager().add(listener);
	}

	public void removePropertyChangeListener(IPropertyChangeListener listener) {
		getEventManager().remove(listener);
	}

	public void init(IServiceLocator locator) {
		getEventManager().clear();
		this.serviceLocator = locator;
		fBindingManager = loadModelBackend(serviceLocator);
		contextModel = new ContextModel(this);
		contextModel.init(serviceLocator);
		fSchemeModel = new SchemeModel(this);
		fSchemeModel.init(fBindingManager);
		bindingModel = new BindingModel(this);
		bindingModel.init(serviceLocator, fBindingManager, contextModel);
		conflictModel = new ConflictModel(this);
		conflictModel.init(fBindingManager, bindingModel);
		addSetContextListener();
		addSetBindingListener();
		addSetConflictListener();
		addSetKeySequenceListener();
		addSetSchemeListener();
		addSetModelObjectListener();
	}

	private static BindingManager loadModelBackend(IServiceLocator locator) {
		IBindingService bindingService = (IBindingService) locator
				.getService(IBindingService.class);
		BindingManager bindingManager = new BindingManager(
				new ContextManager(), new CommandManager());
		final Scheme[] definedSchemes = bindingService.getDefinedSchemes();
		try {
			Scheme modelActiveScheme = null;
			for (int i = 0; i < definedSchemes.length; i++) {
				final Scheme scheme = definedSchemes[i];
				final Scheme copy = bindingManager.getScheme(scheme.getId());
				copy.define(scheme.getName(), scheme.getDescription(), scheme
						.getParentId());
				if (definedSchemes[i].getId().equals(bindingService.getActiveScheme().getId())) {
					modelActiveScheme = copy;
				}
			}
			bindingManager.setActiveScheme(modelActiveScheme);
		} catch (final NotDefinedException e) {
			StatusManager.getManager().handle(
					new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH,
							"Keys page found an undefined scheme", e)); //$NON-NLS-1$
		}
		
		bindingManager.setLocale(bindingService.getLocale());
		bindingManager.setPlatform(bindingService.getPlatform());
		bindingManager.setBindings(bindingService.getBindings());
		return bindingManager;
	}

	public ContextModel getContextModel() {
		return contextModel;
	}

	public SchemeModel getSchemeModel() {
		return fSchemeModel;
	}

	public BindingModel getBindingModel() {
		return bindingModel;
	}

	public ConflictModel getConflictModel() {
		return conflictModel;
	}

	private void addSetContextListener() {
		addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getSource() == contextModel
						&& CommonModel.PROP_SELECTED_ELEMENT.equals(event
								.getProperty())) {
					updateBindingContext((ContextElement) event.getNewValue());
				}
			}
		});
	}

	private void addSetBindingListener() {
		addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getSource() == bindingModel
						&& CommonModel.PROP_SELECTED_ELEMENT.equals(event
								.getProperty())) {
					BindingElement binding = (BindingElement) event
							.getNewValue();
					if (binding == null) {
						conflictModel.setSelectedElement(null);
						return;
					}
					conflictModel.setSelectedElement(binding);
					ContextElement context = binding.getContext();
					if (context != null) {
						contextModel.setSelectedElement(context);
					}
				}
			}
		});
	}

	private void addSetConflictListener() {
		addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getSource() == conflictModel
						&& CommonModel.PROP_SELECTED_ELEMENT.equals(event
								.getProperty())) {
					if (event.getNewValue() != null) {
						bindingModel.setSelectedElement((ModelElement) event
								.getNewValue());
					}
				}
			}
		});
	}

	private void addSetKeySequenceListener() {
		addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (BindingElement.PROP_TRIGGER.equals(event.getProperty())) {
					updateTrigger((BindingElement) event.getSource(),
							(KeySequence) event.getOldValue(),
							(KeySequence) event.getNewValue());
				}
			}
		});
	}

	private void addSetModelObjectListener() {
		addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getSource() instanceof BindingElement
						&& ModelElement.PROP_MODEL_OBJECT.equals(event
								.getProperty())) {
					if (event.getNewValue() != null) {
						BindingElement element = (BindingElement) event
								.getSource();
						Object oldValue = event.getOldValue();
						Object newValue = event.getNewValue();
						if (oldValue instanceof Binding
								&& newValue instanceof Binding) {
							conflictModel.updateConflictsFor(element,
									((Binding) oldValue).getTriggerSequence(),
									((Binding) newValue).getTriggerSequence(),
									false);
						} else {
							conflictModel.updateConflictsFor(element, false);
						}

						ContextElement context = element.getContext();
						if (context != null) {
							contextModel.setSelectedElement(context);
						}
					}
				}
			}
		});
	}

	private void addSetSchemeListener() {
		addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getSource() == fSchemeModel
						&& CommonModel.PROP_SELECTED_ELEMENT.equals(event
								.getProperty())) {
					changeScheme((SchemeElement) event.getOldValue(),
							(SchemeElement) event.getNewValue());
				}
			}
		});
	}

	/**
	 * @param oldScheme
	 * @param newScheme
	 */
	protected void changeScheme(SchemeElement oldScheme, SchemeElement newScheme) {
		if (newScheme == null
				|| newScheme.getModelObject() == fBindingManager
						.getActiveScheme()) {
			return;
		}
		try {
			fBindingManager
					.setActiveScheme((Scheme) newScheme.getModelObject());
			bindingModel.refresh(contextModel);
			bindingModel.setSelectedElement(null);
		} catch (NotDefinedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void updateBindingContext(ContextElement context) {
		if (context == null) {
			return;
		}
		BindingElement activeBinding = (BindingElement) bindingModel
				.getSelectedElement();
		if (activeBinding == null) {
			return;
		}
		String activeSchemeId = fSchemeModel.getSelectedElement().getId();
		Object obj = activeBinding.getModelObject();
		if (obj instanceof KeyBinding) {
			KeyBinding keyBinding = (KeyBinding) obj;
			if (!keyBinding.getContextId().equals(context.getId())) {
				final KeyBinding binding = new KeyBinding(keyBinding
						.getKeySequence(),
						keyBinding.getParameterizedCommand(), activeSchemeId,
						context.getId(), null, null, null, Binding.USER);
				if (keyBinding.getType() == Binding.USER) {
					fBindingManager.removeBinding(keyBinding);
				} else {
					fBindingManager.addBinding(new KeyBinding(keyBinding
							.getKeySequence(), null, keyBinding.getSchemeId(),
							keyBinding.getContextId(), null, null, null,
							Binding.USER));
				}
				bindingModel.getBindingToElement().remove(
						activeBinding.getModelObject());

				fBindingManager.addBinding(binding);
				activeBinding.fill(binding, contextModel);
				bindingModel.getBindingToElement().put(binding, activeBinding);
			}
		}
	}

	/**
	 * @param activeBinding
	 * @param oldSequence
	 * @param keySequence
	 */
	public void updateTrigger(BindingElement activeBinding,
			KeySequence oldSequence, KeySequence keySequence) {
		if (activeBinding == null) {
			return;
		}
		Object obj = activeBinding.getModelObject();
		if (obj instanceof KeyBinding) {
			KeyBinding keyBinding = (KeyBinding) obj;
			if (!keyBinding.getKeySequence().equals(keySequence)) {
				if (keySequence != null && !keySequence.isEmpty()) {
					String activeSchemeId = fSchemeModel.getSelectedElement()
							.getId();
					ModelElement selectedElement = contextModel
							.getSelectedElement();
					String activeContextId = selectedElement == null ? IContextService.CONTEXT_ID_WINDOW
							: selectedElement.getId();
					final KeyBinding binding = new KeyBinding(keySequence,
							keyBinding.getParameterizedCommand(),
							activeSchemeId, activeContextId, null, null, null,
							Binding.USER);
					Map bindingToElement = bindingModel.getBindingToElement();
					bindingToElement.remove(keyBinding);
					if (keyBinding.getType() == Binding.USER) {
						fBindingManager.removeBinding(keyBinding);
					} else {
						fBindingManager.addBinding(new KeyBinding(keyBinding
								.getKeySequence(), null, keyBinding
								.getSchemeId(), keyBinding.getContextId(),
								null, null, null, Binding.USER));
					}

					fBindingManager.addBinding(binding);
					activeBinding.fill(binding, contextModel);
					bindingModel.getBindingToElement().put(binding,
							activeBinding);

					// Remove binding for any system conflicts

					bindingModel.setSelectedElement(activeBinding);
				} else {
					bindingModel.getBindingToElement().remove(keyBinding);
					if (keyBinding.getType() == Binding.USER) {
						fBindingManager.removeBinding(keyBinding);
					} else {
						fBindingManager.addBinding(new KeyBinding(keyBinding
								.getKeySequence(), null, keyBinding
								.getSchemeId(), keyBinding.getContextId(),
								null, null, null, Binding.USER));
					}
					activeBinding.fill(keyBinding.getParameterizedCommand());
				}
			}
		} else if (obj instanceof ParameterizedCommand) {
			ParameterizedCommand cmd = (ParameterizedCommand) obj;
			if (keySequence != null && !keySequence.isEmpty()) {
				String activeSchemeId = fSchemeModel.getSelectedElement()
						.getId();
				ModelElement selectedElement = contextModel
						.getSelectedElement();
				String activeContextId = selectedElement == null ? IContextService.CONTEXT_ID_WINDOW
						: selectedElement.getId();
				final KeyBinding binding = new KeyBinding(keySequence, cmd,
						activeSchemeId, activeContextId, null, null, null,
						Binding.USER);
				fBindingManager.addBinding(binding);
				activeBinding.fill(binding, contextModel);
				bindingModel.getBindingToElement().put(binding, activeBinding);
			}
		}
	}

	/**
	 * Replaces all the current bindings with the bindings in the local copy of
	 * the binding manager.
	 * 
	 * @param bindingService
	 *            The binding service that saves the changes made to the local
	 *            copy of the binding manager
	 */
	public void saveBindings(IBindingService bindingService) {
		try {
			bindingService.savePreferences(fBindingManager.getActiveScheme(),
					fBindingManager.getBindings());
		} catch (IOException e) {
			logPreferenceStoreException(e);
		}
	}

	/**
	 * Logs the given exception, and opens an error dialog saying that something
	 * went wrong. The exception is assumed to have something to do with the
	 * preference store.
	 * 
	 * @param exception
	 *            The exception to be logged; must not be <code>null</code>.
	 */
	private final void logPreferenceStoreException(final Throwable exception) {
		final String message = NewKeysPreferenceMessages.PreferenceStoreError_Message;
		String exceptionMessage = exception.getMessage();
		if (exceptionMessage == null) {
			exceptionMessage = message;
		}
		final IStatus status = new Status(IStatus.ERROR,
				WorkbenchPlugin.PI_WORKBENCH, 0, exceptionMessage, exception);
		WorkbenchPlugin.log(message, status);
		StatusUtil.handleStatus(message, exception, StatusManager.SHOW);
	}

	/**
	 * Filters contexts for the When Combo.
	 * 
	 * @param actionSets
	 *            <code>true</code> to filter action set contexts
	 * @param internal
	 *            <code>false</code> to filter internal contexts
	 * 
	 */
	public void filterContexts(boolean actionSets, boolean internal) {
		contextModel.filterContexts(actionSets, internal);
	}

	/**
	 * Sets the bindings to default.
	 * 
	 * @param bindingService
	 */
	public void setDefaultBindings(IBindingService bindingService) {
		// Fix the scheme in the local changes.
		final String defaultSchemeId = bindingService.getDefaultSchemeId();
		final Scheme defaultScheme = fBindingManager.getScheme(defaultSchemeId);
		try {
			fBindingManager.setActiveScheme(defaultScheme);
		} catch (final NotDefinedException e) {
			// At least we tried....
		}

		// Restore any User defined bindings
		Binding[] bindings = fBindingManager.getBindings();
		for (int i = 0; i < bindings.length; i++) {
			if (bindings[i].getType() == Binding.USER) {
				fBindingManager.removeBinding(bindings[i]);
			}
		}

		bindingModel.refresh(contextModel);
		saveBindings(bindingService);
	}

	public void exportCSV(Shell shell) {
		final FileDialog fileDialog = new FileDialog(shell, SWT.SAVE
				| SWT.SHEET);
		fileDialog.setFilterExtensions(new String[] { "*.csv" }); //$NON-NLS-1$
		fileDialog.setFilterNames(new String[] { Util.translateString(
				RESOURCE_BUNDLE, "csvFilterName") }); //$NON-NLS-1$
		fileDialog.setOverwrite(true);
		final String filePath = fileDialog.open();
		if (filePath == null) {
			return;
		}

		final SafeRunnable runnable = new SafeRunnable() {
			public final void run() throws IOException {
				Writer fileWriter = null;
				try {
					fileWriter = new BufferedWriter(new OutputStreamWriter(
							new FileOutputStream(filePath), "UTF-8")); //$NON-NLS-1$
					final Object[] bindingElements = bindingModel.getBindings()
							.toArray();
					for (int i = 0; i < bindingElements.length; i++) {
						final BindingElement be = (BindingElement) bindingElements[i];
						if (be.getTrigger() == null
								|| be.getTrigger().isEmpty()) {
							continue;
						}
						StringBuffer buffer = new StringBuffer();
						buffer.append(ESCAPED_QUOTE
								+ Util.replaceAll(be.getCategory(),
										ESCAPED_QUOTE, REPLACEMENT)
								+ ESCAPED_QUOTE + DELIMITER);
						buffer.append(ESCAPED_QUOTE + be.getName()
								+ ESCAPED_QUOTE + DELIMITER);
						buffer.append(ESCAPED_QUOTE + be.getTrigger().format()
								+ ESCAPED_QUOTE + DELIMITER);
						buffer.append(ESCAPED_QUOTE + be.getContext().getName()
								+ ESCAPED_QUOTE);
						buffer.append(System.getProperty("line.separator")); //$NON-NLS-1$
						fileWriter.write(buffer.toString());
					}

				} finally {
					if (fileWriter != null) {
						try {
							fileWriter.close();
						} catch (final IOException e) {
							// At least I tried.
						}
					}

				}
			}
		};
		SafeRunner.run(runnable);
	}
}

Back to the top