Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 6f40db2c71bf7964ae009f00dede60bffc38226d (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
/*****************************************************************************
 * Copyright (c) 2015 Christian W. Damus 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:
 *   Christian W. Damus - Initial API and implementation
 *   
 *****************************************************************************/

package org.eclipse.papyrus.infra.core.internal.language;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.ContentHandler;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.papyrus.infra.core.Activator;
import org.eclipse.papyrus.infra.core.language.ILanguage;
import org.eclipse.papyrus.infra.core.language.ILanguageProvider;
import org.eclipse.papyrus.infra.core.language.ILanguageService;
import org.eclipse.papyrus.infra.core.resource.ModelSet;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * A default language provider for extensions that simply declare content-type matches for languages.
 */
public class DefaultLanguageProvider implements ILanguageProvider {
	private static Map<EPackage, IContentType> CONTENT_TYPES = new WeakHashMap<>();

	private static IContentType NULL_CONTENT_TYPE = Platform.getContentTypeManager().getContentType("org.eclipse.emf.ecore.xmi"); //$NON-NLS-1$

	private final Set<IContentType> contentTypes = Sets.newHashSet();

	private final List<ILanguage> languages = Lists.newArrayList();

	private List<LanguageProxy> languageProxies;

	public DefaultLanguageProvider() {
		super();
	}

	@Override
	public synchronized Iterable<ILanguage> getLanguages(ILanguageService languageService, URI modelURI, boolean uriHasFileExtension) {
		Set<URI> allURIs;

		try {
			allURIs = resolveURIs(modelURI, uriHasFileExtension);
		} catch (CoreException e) {
			Activator.log.log(e.getStatus());

			// Can't match our content types against anything
			return Collections.emptyList();
		}

		if (!matchContentType(allURIs)) {
			return Collections.emptyList();
		} else {
			// If any of my content-types matches, then all of my languages are present
			resolveProxies();
			return Collections.unmodifiableList(languages);
		}
	}

	@Override
	public synchronized Iterable<ILanguage> getLanguages(ILanguageService languageService, ModelSet modelSet) {
		if (!matchContentType(modelSet.getResources())) {
			return Collections.emptyList();
		} else {
			// If any of my content-types matches, then all of my languages are present
			resolveProxies();
			return Collections.unmodifiableList(languages);
		}
	}

	void addContentType(String id) {
		IContentType contentType = Platform.getContentTypeManager().getContentType(id);
		if (contentType == null) {
			Activator.log.warn("No such content-type in language provider extension: " + id); //$NON-NLS-1$
		} else {
			contentTypes.add(contentType);
		}
	}

	synchronized void addLanguage(ILanguage language) {
		this.languages.add(language);
	}

	synchronized void addLanguage(IConfigurationElement config, String attribute) {
		if (languageProxies == null) {
			languageProxies = Lists.newArrayList();
		}

		languageProxies.add(new LanguageProxy(config, attribute));
	}

	private void resolveProxies() {
		if (languageProxies != null) {
			try {
				for (LanguageProxy next : languageProxies) {
					ILanguage resolved = next.resolve();
					if (resolved != null) {
						addLanguage(resolved);
					}
				}
			} finally {
				languageProxies = null;
			}
		}
	}

	private Set<URI> resolveURIs(URI modelURI, boolean uriHasFileExtension) throws CoreException {
		// If given an extension, just take that
		if (uriHasFileExtension) {
			return Collections.singleton(modelURI);
		}

		Set<URI> result = Sets.newHashSet();

		if (modelURI.isPlatformResource()) {
			String baseName = modelURI.lastSegment();
			IPath path = new Path(modelURI.trimSegments(1).toPlatformString(true));
			IContainer container = (path.segmentCount() > 1) ? ResourcesPlugin.getWorkspace().getRoot().getFolder(path) : ResourcesPlugin.getWorkspace().getRoot().getProject(path.lastSegment());
			for (IResource next : container.members()) {
				if (next.getType() == IResource.FILE) {
					IPath nextPath = next.getFullPath();
					String name = nextPath.removeFileExtension().lastSegment();
					if (name.equals(baseName)) {
						result.add(URI.createPlatformResourceURI(nextPath.toString(), true));
					}
				}
			}
		} else if (modelURI.isFile()) {
			String baseName = modelURI.lastSegment();
			File directory = new File(modelURI.trimSegments(1).toFileString());
			for (File next : directory.listFiles()) {
				if (next.isFile()) {
					IPath nextPath = new Path(directory.getPath()).append(next.getName());
					String name = nextPath.removeFileExtension().lastSegment();
					if (name.equals(baseName)) {
						result.add(URI.createPlatformResourceURI(nextPath.toString(), true));
					}
				}
			}
		}

		return result;
	}

	private boolean matchContentType(Set<URI> uris) {
		boolean result = false;

		out: for (URI next : uris) {
			try {
				Map<String, ?> desc = URIConverter.INSTANCE.contentDescription(next, null);
				String contentTypeID = (String) desc.get(ContentHandler.CONTENT_TYPE_PROPERTY);
				if (contentTypeID != null) {
					IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeID);
					if (contentType != null) {
						for (IContentType type : contentTypes) {
							if (contentType.isKindOf(type)) {
								result = true;
								break out;
							}
						}
					}
				}
			} catch (IOException e) {
				// Not our content type, I guess
			}
		}

		return result;
	}

	private boolean matchContentType(Collection<? extends Resource> resources) {
		boolean result = false;
		Set<EPackage> packagesSeen = new HashSet<>();

		out: for (Resource next : resources) {
			String filename = next.getURI().lastSegment();

			// TODO: Is it really sufficient to check only the roots? Other content could be contained
			for (EObject root : next.getContents()) {
				EPackage ePackage = root.eClass().getEPackage();
				if (packagesSeen.add(ePackage)) {
					IContentType contentType = getContentType(ePackage, filename);
					if (contentType != null) {
						for (IContentType type : contentTypes) {
							if (contentType.isKindOf(type)) {
								result = true;
								break out;
							}
						}
					}
				}
			}
		}

		return result;
	}

	/**
	 * We don't actually have a mapping in EMF between packages and content-types,
	 * so we infer it by feeding the platform's content-type system some fake inputs,
	 * relaying on the standard EMF pattern of using XML namespace declarations to
	 * determine content-type.
	 * 
	 * @param ePackage
	 *            the package to infer the content-type
	 * @param filename
	 *            used as a hint to the platform's content-type manager
	 * 
	 * @return the content-type or a placeholder for unknown content (never {@code null})
	 */
	private IContentType getContentType(EPackage ePackage, String filename) {
		return CONTENT_TYPES.computeIfAbsent(ePackage, package_ -> {
			IContentType contentType = null;

			StringReader xmiString = createStringReader(ePackage);
			try {
				IContentDescription desc = Platform.getContentTypeManager().getDescriptionFor(xmiString, filename, null);
				contentType = (desc == null) ? null : desc.getContentType();
			} catch (IOException e) {
				// Not our content type, I guess
			}

			if (contentType == null) {
				contentType = NULL_CONTENT_TYPE;
			}

			return contentType;
		});
	}

	private StringReader createStringReader(EPackage ePackage) {
		String xmi = String.format(
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?><xmi:XMI xmlns:xmi=\"%s\" xmlns:content=\"%s\"/>", //$NON-NLS-1$
				XMIResource.XMI_2_1_URI, ePackage.getNsURI());
		return new StringReader(xmi);
	}

	//
	// Nested types
	//

	private static class LanguageProxy {
		private final IConfigurationElement config;
		private final String attribute;

		LanguageProxy(IConfigurationElement config, String attribute) {
			super();

			this.config = config;
			this.attribute = attribute;
		}

		ILanguage resolve() {
			try {
				return (ILanguage) config.createExecutableExtension(attribute);
			} catch (Exception e) {
				Activator.log.error("Failed to instantiate language in provider extension from contributor " + config.getContributor().getName(), e); //$NON-NLS-1$
				return null;
			}
		}
	}
}

Back to the top