Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 3cafdb028cf99f046cd4643494e71f7e3f07ab73 (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
/*******************************************************************************
 * Copyright (c) 2011 Wind River Systems, Inc. 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:
 * William Chen (Wind River)	[360494]Provide an "Open With" action in the pop 
 * 								up menu of file system nodes of Target Explorer.
 *******************************************************************************/
package org.eclipse.tcf.te.tcf.filesystem.ui.internal.handlers;

import java.io.File;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.window.Window;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.tcf.te.tcf.filesystem.core.internal.operations.IOpExecutor;
import org.eclipse.tcf.te.tcf.filesystem.core.internal.operations.OpCacheUpdate;
import org.eclipse.tcf.te.tcf.filesystem.core.internal.utils.CacheManager;
import org.eclipse.tcf.te.tcf.filesystem.core.internal.utils.ContentTypeHelper;
import org.eclipse.tcf.te.tcf.filesystem.core.internal.utils.PersistenceManager;
import org.eclipse.tcf.te.tcf.filesystem.core.model.FSTreeNode;
import org.eclipse.tcf.te.tcf.filesystem.ui.activator.UIPlugin;
import org.eclipse.tcf.te.tcf.filesystem.ui.internal.operations.UiExecutor;
import org.eclipse.tcf.te.tcf.filesystem.ui.nls.Messages;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.EditorSelectionDialog;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.ide.IDE;

/**
 * A menu for opening files in the target explorer.
 * <p>
 * An <code>OpenWithMenu</code> is used to populate a menu with "Open With" actions. One action is
 * added for each editor which is applicable to the selected file. If the user selects one of these
 * items, the corresponding editor is opened on the file.
 * </p>
 * 
 * @since 3.7 - Copied and modified based on org.eclipse.ui.actions.OpenWithMenu to avoid
 *        introducing org.eclipse.core.resources
 */
public class OpenWithMenu extends ContributionItem {
	private static final String DEFAULT_TEXT_EDITOR = "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$

	/**
	 * The id of this action.
	 */
	public static final String ID = UIPlugin.getUniqueIdentifier() + ".OpenWithMenu";//$NON-NLS-1$

	/*
	 * Compares the labels from two IEditorDescriptor objects
	 */
	private static final Comparator<IEditorDescriptor> comparer = new Comparator<IEditorDescriptor>() {
		private Collator collator = Collator.getInstance();

		@Override
		public int compare(IEditorDescriptor arg0, IEditorDescriptor arg1) {
			String s1 = arg0.getLabel();
			String s2 = arg1.getLabel();
			return collator.compare(s1, s2);
		}
	};
	// The selected tree node.
	FSTreeNode node;
	// The current workbench page.
	IWorkbenchPage page;
	// The editor registry.
	IEditorRegistry registry;

	/**
	 * Create an instance using the specified page and the specified FSTreeNode.
	 * 
	 * @param page The page to open the editor.
	 * @param node The FSTreeNode to be opened.
	 */
	public OpenWithMenu(IWorkbenchPage page, FSTreeNode node) {
		super(ID);
		this.node = node;
		this.page = page;
		this.registry = PlatformUI.getWorkbench().getEditorRegistry();
	}

	/**
	 * Returns an image to show for the corresponding editor descriptor.
	 * 
	 * @param editorDesc the editor descriptor, or null for the system editor
	 * @return the image or null
	 */
	private Image getImage(IEditorDescriptor editorDesc) {
		ImageDescriptor imageDesc = getImageDescriptor(editorDesc);
		if (imageDesc == null) {
			return null;
		}
		return imageDesc.createImage();
	}

	/**
	 * Returns the image descriptor for the given editor descriptor, or null if it has no image.
	 */
	private ImageDescriptor getImageDescriptor(IEditorDescriptor editorDesc) {
		ImageDescriptor imageDesc = null;
		if (editorDesc == null) {
			imageDesc = registry.getImageDescriptor(node.name);
			// TODO: is this case valid, and if so, what are the implications for content-type
			// editor bindings?
		}
		else {
			imageDesc = editorDesc.getImageDescriptor();
		}
		if (imageDesc == null) {
			if (editorDesc != null && editorDesc.getId().equals(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID)) {
				imageDesc = registry.getSystemExternalEditorImageDescriptor(node.name);
			}
		}
		return imageDesc;
	}

	/**
	 * Creates the menu item for the editor descriptor.
	 * 
	 * @param menu the menu to add the item to
	 * @param descriptor the editor descriptor, or null for the system editor
	 * @param preferredEditor the descriptor of the preferred editor, or <code>null</code>
	 */
	private void createMenuItem(Menu menu, final IEditorDescriptor descriptor, final IEditorDescriptor preferredEditor) {
		final MenuItem menuItem = new MenuItem(menu, SWT.RADIO);
		boolean isPreferred = preferredEditor != null && descriptor.getId()
		                .equals(preferredEditor.getId());
		menuItem.setSelection(isPreferred);
		menuItem.setText(descriptor.getLabel());
		Image image = getImage(descriptor);
		if (image != null) {
			menuItem.setImage(image);
		}
		Listener listener = new Listener() {
			@Override
			public void handleEvent(Event event) {
				switch (event.type) {
				case SWT.Selection:
					if (menuItem.getSelection()) {
						syncOpen(descriptor, false);
					}
					break;
				default:
					break;
				}
			}
		};
		menuItem.addListener(SWT.Selection, listener);
	}

	/**
	 * Creates the Other... menu item
	 * 
	 * @param menu the menu to add the item to
	 */
	@SuppressWarnings("unused")
	private void createOtherMenuItem(final Menu menu) {
		new MenuItem(menu, SWT.SEPARATOR);
		final MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
		menuItem.setText(Messages.OpenWithMenu_OpenWith);
		Listener listener = new Listener() {
			@Override
			public void handleEvent(Event event) {
				switch (event.type) {
				case SWT.Selection:
					EditorSelectionDialog dialog = new EditorSelectionDialog(menu.getShell());
					dialog.setMessage(NLS
					                .bind(Messages.OpenWithMenu_ChooseEditorForOpening, node.name));
					if (dialog.open() == Window.OK) {
						IEditorDescriptor editor = dialog.getSelectedEditor();
						if (editor != null) {
							syncOpen(editor, editor.isOpenExternal());
						}
					}
					break;
				default:
					break;
				}
			}
		};
		menuItem.addListener(SWT.Selection, listener);
	}

	/**
	 * Get the default editor for this FSTreeNode.
	 * 
	 * @return The descriptor of the default editor.
	 */
	private IEditorDescriptor getDefaultEditor() {
		// Try file specific editor.
		try {
			String editorID = PersistenceManager.getInstance().getPersistentProperties(node)
			                .get(IDE.EDITOR_KEY);
			if (editorID != null) {
				IEditorDescriptor desc = registry.findEditor(editorID);
				if (desc != null) {
					return desc;
				}
			}
		}
		catch (Exception e) {
			// do nothing
		}

		IContentType contentType = null;
		contentType = ContentTypeHelper.getContentType(node);
		// Try lookup with filename
		return registry.getDefaultEditor(node.name, contentType);
	}

	/*
	 * (non-Javadoc) Fills the menu with perspective items.
	 */
	@SuppressWarnings("unused")
	@Override
	public void fill(Menu menu, int index) {

		IEditorDescriptor defaultEditor = registry.findEditor(DEFAULT_TEXT_EDITOR);
		IEditorDescriptor preferredEditor = getDefaultEditor();

		IEditorDescriptor[] editors = registry.getEditors(node.name, ContentTypeHelper.getContentType(node));
		Collections.sort(Arrays.asList(editors), comparer);

		boolean defaultFound = false;

		// Check that we don't add it twice. This is possible
		// if the same editor goes to two mappings.
		ArrayList<IEditorDescriptor> alreadyMapped = new ArrayList<IEditorDescriptor>();

		for (int i = 0; i < editors.length; i++) {
			IEditorDescriptor editor = editors[i];
			if (!alreadyMapped.contains(editor)) {
				createMenuItem(menu, editor, preferredEditor);
				if (defaultEditor != null && editor.getId().equals(defaultEditor.getId())) {
					defaultFound = true;
				}
				alreadyMapped.add(editor);
			}
		}

		// Only add a separator if there is something to separate
		if (editors.length > 0) {
			new MenuItem(menu, SWT.SEPARATOR);
		}

		// Add default editor. Check it if it is saved as the preference.
		if (!defaultFound && defaultEditor != null) {
			createMenuItem(menu, defaultEditor, preferredEditor);
		}

		// Add system editor (should never be null)
		IEditorDescriptor descriptor = registry
		                .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
		createMenuItem(menu, descriptor, preferredEditor);

		createDefaultMenuItem(menu);

		// add Other... menu item
		createOtherMenuItem(menu);
	}

	/*
	 * (non-Javadoc) Returns whether this menu is dynamic.
	 */
	@Override
	public boolean isDynamic() {
		return true;
	}

	/**
	 * Creates the menu item for clearing the current selection.
	 * 
	 * @param menu the menu to add the item to
	 * @param file the file being edited
	 */
	private void createDefaultMenuItem(Menu menu) {
		final MenuItem menuItem = new MenuItem(menu, SWT.RADIO);
		menuItem.setSelection(getDefaultEditor() == null);
		menuItem.setText(Messages.OpenWithMenu_DefaultEditor);

		Listener listener = new Listener() {
			@Override
			public void handleEvent(Event event) {
				switch (event.type) {
				case SWT.Selection:
					if (menuItem.getSelection()) {
						PersistenceManager.getInstance().getPersistentProperties(node)
						                .put(IDE.EDITOR_KEY, null);
						try {
							syncOpen(getEditorDescriptor(), false);
						}
						catch (PartInitException e) {
							e.printStackTrace();
						}
					}
					break;
				default:
					break;
				}
			}
		};

		menuItem.addListener(SWT.Selection, listener);
	}

	/**
	 * Get an appropriate editor for the FSTreeNode. If the default editor is not found, it will
	 * search the in-place editor, the external editor and finally the default text editor.
	 * 
	 * @return An appropriate editor to open the node using "Default Editor".
	 * @throws PartInitException
	 */
	protected IEditorDescriptor getEditorDescriptor() throws PartInitException {
		IEditorDescriptor defaultDescriptor = getDefaultEditor();
		if (defaultDescriptor != null) {
			return defaultDescriptor;
		}

		IEditorDescriptor editorDesc = null;

		// next check the OS for in-place editor (OLE on Win32)
		if (registry.isSystemInPlaceEditorAvailable(node.name)) {
			editorDesc = registry.findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID);
		}

		// next check with the OS for an external editor
		if (editorDesc == null && registry.isSystemExternalEditorAvailable(node.name)) {
			editorDesc = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
		}

		// next lookup the default text editor
		if (editorDesc == null) {
			editorDesc = registry.findEditor(DEFAULT_TEXT_EDITOR);
		}

		// if no valid editor found, bail out
		if (editorDesc == null) {
			throw new PartInitException(Messages.OpenWithMenu_NoEditorFound);
		}

		return editorDesc;
	}

	/**
	 * Synchronize and open the file using the specified editor descriptor. If openUsingDescriptor
	 * is true, it will try to use an external editor to open it if an eclipse editor is not
	 * available.
	 * 
	 * @param editorDescriptor The editor descriptor used to open the node.
	 * @param openUsingDescriptor If an external editor should be used to open the node.
	 */
	protected void syncOpen(IEditorDescriptor editorDescriptor, boolean openUsingDescriptor) {
		File file = CacheManager.getCacheFile(node);
		if (!file.exists()) {
			// If the file node's local cache does not exist yet, download it.
			IOpExecutor executor = new UiExecutor();
			IStatus status = executor.execute(new OpCacheUpdate(node));
			if (!status.isOK()) {
				return;
			}
		}
		openInEditor(editorDescriptor, openUsingDescriptor);
	}

	/**
	 * Open the editor using the specified editor descriptor. If openUsingDescriptor is true, it
	 * will try to use an external editor to open it if an eclipse editor is not available.
	 * 
	 * @param editorDescriptor The editor descriptor used to open the node.
	 * @param openUsingDescriptor If an external editor should be used to open the node.
	 */
	private void openInEditor(IEditorDescriptor editorDescriptor, boolean openUsingDescriptor) {
		try {
			IPath path = CacheManager.getCachePath(node);
			IFileStore fileStore = EFS.getLocalFileSystem().getStore(path);
			FileStoreEditorInput input = new FileStoreEditorInput(fileStore);
			if (openUsingDescriptor) {
				String editorId = editorDescriptor.getId();
				page.openEditor(input, editorId, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID);
			}
			else {
				String editorId = IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID;
				if (editorDescriptor != null) editorId = editorDescriptor.getId();
				page.openEditor(input, editorId, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID);
				Map<QualifiedName, String> properties = PersistenceManager.getInstance()
				                .getPersistentProperties(node);
				properties.put(IDE.EDITOR_KEY, editorId);
			}
		}
		catch (PartInitException e) {
			e.printStackTrace();
		}
	}
}

Back to the top