Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 2258ffc3504c0be50dd3ff3d0e6d67ea910a9dd8 (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
/*******************************************************************************
 * Copyright (c) 2000, 2016 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Jan-Hendrik Diederich, Bredex GmbH - bug 201052
 *     Lars Vogel <Lars.Vogel@vogella.com> - Bug 472654
 *     Dirk Fauth <dirk.fauth@googlemail.com> - Bug 473063
 *     Patrik Suzzi <psuzzi@gmail.com> - Bug 500420
 *     Sopot Cela <scela@redhat.com> - Bug 502004
 *******************************************************************************/
package org.eclipse.ui.internal.registry;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.dynamichelpers.IExtensionChangeHandler;
import org.eclipse.core.runtime.dynamichelpers.IExtensionTracker;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.services.log.Logger;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.MSnippetContainer;
import org.eclipse.e4.ui.model.application.ui.MUIElement;
import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveRegistry;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.activities.WorkbenchActivityHelper;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.e4.compatibility.E4Util;
import org.eclipse.ui.internal.util.PrefUtil;

/**
 * Perspective registry.
 */
public class PerspectiveRegistry implements IPerspectiveRegistry, IExtensionChangeHandler {

	@Inject
	private IExtensionRegistry extensionRegistry;

	@Inject
	EModelService modelService;

	@Inject
	MApplication application;

	@Inject
	IEclipseContext context;

	private IEclipseContext impExpHandlerContext;

	@Inject
	Logger logger;

	private Map<String, PerspectiveDescriptor> descriptors = new HashMap<>();

	@PostConstruct
	void postConstruct(MApplication application) {
		IExtensionPoint point = extensionRegistry.getExtensionPoint("org.eclipse.ui.perspectives"); //$NON-NLS-1$
		for (IConfigurationElement element : point.getConfigurationElements()) {
			String id = element.getAttribute(IWorkbenchRegistryConstants.ATT_ID);
			descriptors.put(id, new PerspectiveDescriptor(id, element));
		}

		List<MUIElement> snippets = application.getSnippets();
		for (MUIElement snippet : snippets) {
			if (snippet instanceof MPerspective) {
				MPerspective perspective = (MPerspective) snippet;
				String id = perspective.getElementId();

				// See if the clone is customizing an a predefined perspective without changing
				// its name
				PerspectiveDescriptor existingDescriptor = descriptors.get(id);

				if (existingDescriptor == null) {
					// A custom perspective with its own name.
					createDescriptor(perspective);
				} else {
					// A custom perspecitve with a name of a pre-defined perspective
					existingDescriptor.setHasCustomDefinition(true);
				}
			}
		}

		impExpHandlerContext = context.createChild();
		impExpHandlerContext.set(PerspectiveRegistry.class, this);
		ContextInjectionFactory.make(ImportExportPespectiveHandler.class, impExpHandlerContext);
	}

	public void addPerspective(MPerspective perspective) {
		application.getSnippets().add(perspective);
		createDescriptor(perspective);
	}

	private void createDescriptor(MPerspective perspective) {
		String label = perspective.getLocalizedLabel();
		String originalId = getOriginalId(perspective);
		PerspectiveDescriptor originalDescriptor = descriptors.get(originalId);
		String id = perspective.getElementId();
		PerspectiveDescriptor newDescriptor = new PerspectiveDescriptor(id, label, originalDescriptor);

		if (perspective.getIconURI() != null) {
			try {
				ImageDescriptor img = ImageDescriptor.createFromURL(new URI(perspective.getIconURI()).toURL());
				newDescriptor.setImageDescriptor(img);
			} catch (MalformedURLException | URISyntaxException | IllegalArgumentException e) {
				logger.warn(e, MessageFormat.format("Error on applying configured perspective icon: {0}", //$NON-NLS-1$
						perspective.getIconURI()));
			}
		}

		descriptors.put(id, newDescriptor);
	}

	/**
	 * Construct a new registry.
	 */
	public PerspectiveRegistry() {
		IExtensionTracker tracker = PlatformUI.getWorkbench().getExtensionTracker();
		tracker.registerHandler(this, null);

	}

	@Override
	public IPerspectiveDescriptor clonePerspective(String id, String label, IPerspectiveDescriptor desc)
			throws IllegalArgumentException {
		// FIXME: compat clonePerspective. Not called in 3.8
		E4Util.unsupported("clonePerspective"); //$NON-NLS-1$
		return null;
	}

	@Override
	public void deletePerspective(IPerspectiveDescriptor toDelete) {
		PerspectiveDescriptor perspective = (PerspectiveDescriptor) toDelete;
		if (perspective.isPredefined())
			return;

		descriptors.remove(perspective.getId());
		removeSnippet(application, perspective.getId());
	}

	private MUIElement removeSnippet(MSnippetContainer snippetContainer, String id) {
		MUIElement snippet = modelService.findSnippet(snippetContainer, id);
		if (snippet != null)
			snippetContainer.getSnippets().remove(snippet);
		return snippet;
	}

	/**
	 * Deletes a list of perspectives
	 *
	 * @param perspToDelete
	 */
	public void deletePerspectives(ArrayList<IPerspectiveDescriptor> perspToDelete) {
		for (int i = 0; i < perspToDelete.size(); i++) {
			deletePerspective(perspToDelete.get(i));
		}
	}

	@Override
	public IPerspectiveDescriptor findPerspectiveWithId(String perspectiveId) {
		return findPerspectiveWithId(perspectiveId, true);
	}

	public IPerspectiveDescriptor findPerspectiveWithId(String perspectiveId, boolean considerRestrictRules) {
		IPerspectiveDescriptor candidate = descriptors.get(perspectiveId);
		if (considerRestrictRules && WorkbenchActivityHelper.restrictUseOf(candidate)) {
			return null;
		}
		return candidate;
	}

	@Override
	public IPerspectiveDescriptor findPerspectiveWithLabel(String label) {
		for (IPerspectiveDescriptor descriptor : descriptors.values()) {
			if (descriptor.getLabel().equals(label)) {
				if (WorkbenchActivityHelper.restrictUseOf(descriptor)) {
					return null;
				}
				return descriptor;
			}
		}
		return null;
	}

	@Override
	public String getDefaultPerspective() {
		String defaultId = PrefUtil.getAPIPreferenceStore()
				.getString(IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID);
		// empty string may be returned but we want to return null if nothing
		// found
		if (defaultId.length() == 0 || findPerspectiveWithId(defaultId) == null) {
			Workbench instance = Workbench.getInstance();
			return instance == null ? null : instance.getDefaultPerspectiveId();
		}

		return defaultId;
	}

	@Override
	public IPerspectiveDescriptor[] getPerspectives() {
		Collection<?> descs = WorkbenchActivityHelper.restrictCollection(descriptors.values(), new ArrayList<>());
		return descs.toArray(new IPerspectiveDescriptor[descs.size()]);
	}

	/**
	 * @see IPerspectiveRegistry#setDefaultPerspective(String)
	 */
	@Override
	public void setDefaultPerspective(String id) {
		IPerspectiveDescriptor desc = findPerspectiveWithId(id);
		if (desc != null) {
			PrefUtil.getAPIPreferenceStore().setValue(IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id);
		}
	}

	/**
	 * Return <code>true</code> if a label is valid. This checks only the given
	 * label in isolation. It does not check whether the given label is used by any
	 * existing perspectives.
	 *
	 * @param label the label to test
	 * @return whether the label is valid
	 */
	public boolean validateLabel(String label) {
		label = label.trim();
		if (label.length() <= 0) {
			return false;
		}
		return true;
	}

	@Override
	public void revertPerspective(IPerspectiveDescriptor perspToRevert) {
		PerspectiveDescriptor perspective = (PerspectiveDescriptor) perspToRevert;
		if (!perspective.isPredefined())
			return;

		perspective.setHasCustomDefinition(false);
		removeSnippet(application, perspective.getId());
	}

	/**
	 * Dispose the receiver.
	 */
	public void dispose() {
		if (impExpHandlerContext != null) {
			impExpHandlerContext.dispose();
		}
		PlatformUI.getWorkbench().getExtensionTracker().unregisterHandler(this);
		// FIXME: what was this listener for?
		// WorkbenchPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(
		// preferenceListener);
	}

	@Override
	public void removeExtension(IExtension source, Object[] objects) {
		// TODO compat: what do we do about disappearing extensions
	}

	@Override
	public void addExtension(IExtensionTracker tracker, IExtension addedExtension) {
		// TODO compat: what do we do about appeaering extensions
	}

	/**
	 * Create a new perspective.
	 *
	 * @param label              the name of the new descriptor
	 * @param originalDescriptor the descriptor on which to base the new descriptor
	 * @return a new perspective descriptor or <code>null</code> if the creation
	 *         failed.
	 */
	public PerspectiveDescriptor createPerspective(String label, PerspectiveDescriptor originalDescriptor) {

		String newID = createNewId(label, originalDescriptor);
		PerspectiveDescriptor newDescriptor = new PerspectiveDescriptor(newID, label, originalDescriptor);
		descriptors.put(newDescriptor.getId(), newDescriptor);
		return newDescriptor;
	}

	/**
	 * Return an id for the new descriptor.
	 *
	 * The id must encode the original id. id is of the form <originalId>.label
	 *
	 * @param label
	 * @param originalDescriptor
	 * @return the new id
	 */
	private String createNewId(String label, PerspectiveDescriptor originalDescriptor) {
		return originalDescriptor.getOriginalId() + '.' + label;
	}

	private String getOriginalId(MPerspective p) {
		String id = p.getElementId();
		String label = p.getLabel();
		if (label == null) {
			label = ""; //$NON-NLS-1$
			logger.warn(String.format("Perspective %s has no label. Contributor is %s.", p.getElementId(), //$NON-NLS-1$
					p.getContributorURI()));
		}
		int index = id.lastIndexOf('.');
		// Custom perspectives store the user defined names in their labels
		String trimE4 = label.trim();
		String trimE3 = label.replace(' ', '_').trim();
		if (id.endsWith(label)) {
			index = id.lastIndexOf(label) - 1;
		} else if (id.endsWith(trimE4)) {
			index = id.lastIndexOf(trimE4) - 1;
		} else if (id.endsWith(trimE3)) {
			index = id.lastIndexOf(trimE3) - 1;
		}
		if (index >= 0 && index < id.length()) {
			return id.substring(0, index);
		}
		return id;
	}
}

Back to the top