Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: cebda1487ffcb69066b83a449282dd2559bb6d8b (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
/*******************************************************************************
 * Copyright (c) 2007, 2008 Wind River Systems, Inc. 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:
 *     Anton Leherbauer (Wind River Systems) - initial API and implementation
 *******************************************************************************/

package org.eclipse.cdt.internal.ui.wizards.filewizard;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.cdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.cdt.internal.corext.template.c.FileTemplateContextType;
import org.eclipse.cdt.internal.ui.preferences.CodeTemplatePreferencePage;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.core.runtime.content.IContentTypeMatcher;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;

/**
 * A new file creation wizard page with support for templates.
 *
 * @since 5.0
 */
public class WizardNewFileFromTemplateCreationPage extends WizardNewFileCreationPage {

	private Combo fTemplatesCombo;
	private Template[] fTemplates;
	protected boolean fUseTemplate = true;

	/**
	 * Create a new 'file from template' page.
	 *
	 * @param pageName
	 * @param selection
	 */
	public WizardNewFileFromTemplateCreationPage(String pageName, IStructuredSelection selection) {
		super(pageName, selection);
	}

	/*
	 * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#createAdvancedControls(org.eclipse.swt.widgets.Composite)
	 */
	@Override
	protected void createAdvancedControls(Composite parent) {
		Composite groupComposite = new Composite(parent, SWT.NONE);
		groupComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		groupComposite.setLayout(layout);

		final Button useTemplateButton = new Button(groupComposite, SWT.CHECK);

		useTemplateButton.setText(NewFileWizardMessages.WizardNewFileFromTemplateCreationPage_useTemplate_label);
		useTemplateButton.setSelection(fUseTemplate);
		SelectionListener useTemplateListener = new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				fUseTemplate = useTemplateButton.getSelection();
				fTemplatesCombo.setEnabled(fUseTemplate);
			}
		};
		useTemplateButton.addSelectionListener(useTemplateListener);

		fTemplatesCombo = new Combo(groupComposite, SWT.READ_ONLY);
		fTemplatesCombo.setEnabled(fUseTemplate);
		fTemplatesCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		final Button configureButton = new Button(groupComposite, SWT.PUSH);
		configureButton.setText(NewFileWizardMessages.WizardNewFileFromTemplateCreationPage_configure_label);

		SelectionListener changeTemplateListener = new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				editTemplates();
			}
		};
		configureButton.addSelectionListener(changeTemplateListener);
		updateTemplates();

		super.createAdvancedControls(parent);
	}

	protected void editTemplates() {
		String prefPageId = CodeTemplatePreferencePage.PREF_ID;
		Map<String, String> data = null;
		String templateName = null;
		Template template = getSelectedTemplate();
		if (template != null) {
			templateName = template.getName();
		}
		if (templateName != null) {
			data = new HashMap<String, String>();
			data.put(CodeTemplatePreferencePage.DATA_SELECT_TEMPLATE, templateName);
		}
		PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getShell(), prefPageId,
				new String[] { prefPageId }, data);
		if (dialog.open() == Window.OK) {
			updateTemplates();
		}
	}

	/*
	 * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#getInitialContents()
	 */
	@Override
	protected InputStream getInitialContents() {
		Template template = getSelectedTemplate();
		if (fUseTemplate && template != null) {
			IFile fileHandle = createFileHandle(getContainerFullPath().append(getResourceName()));
			String lineDelimiter = StubUtility.getLineDelimiterPreference(getContainterProject());
			try {
				String content = StubUtility.getFileContent(template, fileHandle, lineDelimiter);
				if (content != null) {
					try {
						String charset = fileHandle.getParent().getDefaultCharset();
						return new ByteArrayInputStream(content.getBytes(charset));
					} catch (UnsupportedEncodingException exc) {
						return new ByteArrayInputStream(content.getBytes());
					}
				}
			} catch (CoreException exc) {
			}
		}
		return super.getInitialContents();
	}

	/*
	 * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#handleEvent(org.eclipse.swt.widgets.Event)
	 */
	@Override
	public void handleEvent(Event event) {
		updateTemplates();
		super.handleEvent(event);
	}

	protected void updateTemplates() {
		Template selected = getSelectedTemplate();
		boolean isDefaultSelected = (selected != null && fTemplates.length == 1)
				|| (fTemplatesCombo != null && fTemplatesCombo.getSelectionIndex() == 0);
		fTemplates = getApplicableTemplates();
		int idx = 0;
		String[] names = new String[fTemplates.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = fTemplates[i].getName();
			if (!isDefaultSelected && selected != null && selected.getName().equals(names[i])) {
				idx = i;
			}
		}
		if (fTemplatesCombo != null) {
			if (names.length == 0) {
				names = new String[] { NewFileWizardMessages.WizardNewFileFromTemplateCreationPage_noTemplate_name };
			}
			fTemplatesCombo.setItems(names);
			fTemplatesCombo.select(idx);
		}
	}

	/**
	 * @return the selected template or <code>null</code> if none
	 */
	protected Template getSelectedTemplate() {
		if (fTemplates != null) {
			int index = 0;
			if (fTemplatesCombo != null) {
				index = fTemplatesCombo.getSelectionIndex();
				if (index < 0) {
					index = 0;
				}
			}
			if (index < fTemplates.length) {
				return fTemplates[index];
			}
		}
		return null;
	}

	private String getResourceName() {
		String fileName = getFileName();
		String fileExtension = getFileExtension();
		if (fileExtension != null && fileExtension.length() > 0 && !fileName.endsWith('.' + fileExtension)) {
			fileName += '.';
			fileName += fileExtension;
		}
		return fileName;
	}

	private IProject getContainterProject() {
		IPath containerPath = getContainerFullPath();
		if (containerPath != null) {
			return ResourcesPlugin.getWorkspace().getRoot().getProject(containerPath.segment(0));
		}
		return null;
	}

	/**
	 * Configure the set of selectable templates.
	 * @return the set of templates
	 */
	protected Template[] getApplicableTemplates() {
		IProject project = getContainterProject();
		String fileName = getResourceName();
		String[] contentTypes = getAllContentTypeIdsForFileName(project, fileName);
		return StubUtility.getFileTemplatesForContentTypes(contentTypes, project);
	}

	private static String[] getAllContentTypeIdsForFileName(IProject project, String fileName) {
		IContentTypeMatcher matcher;
		if (project == null || !project.isAccessible()) {
			IContentTypeManager contentTypeMgr = Platform.getContentTypeManager();
			matcher = contentTypeMgr;
		} else {
			try {
				matcher = project.getContentTypeMatcher();
			} catch (CoreException exc) {
				IContentTypeManager contentTypeMgr = Platform.getContentTypeManager();
				matcher = contentTypeMgr;
			}
		}
		IContentType[] contentTypes = matcher.findContentTypesFor(fileName);
		List<String> result = new ArrayList<String>(contentTypes.length * 2);
		for (int i = 0; i < contentTypes.length; i++) {
			IContentType contentType = contentTypes[i];
			String id = contentType.getId();
			result.add(id);
		}
		// add base types
		for (int i = 0; i < contentTypes.length; i++) {
			IContentType contentType = contentTypes[i].getBaseType();
			while (contentType != null) {
				String id = contentType.getId();
				if (result.contains(id)) {
					break;
				}
				result.add(id);
				contentType = contentType.getBaseType();
			}
		}
		if (result.isEmpty()) {
			result.add(FileTemplateContextType.CONTENTTYPE_TEXT);
		}
		return result.toArray(new String[result.size()]);
	}

}

Back to the top