View | Details | Raw Unified | Return to bug 282114 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/wst/common/snippets/internal/ui/SnippetsCustomizer.java (+37 lines)
Lines 10-18 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.wst.common.snippets.internal.ui;
11
package org.eclipse.wst.common.snippets.internal.ui;
12
12
13
import java.io.File;
13
import java.util.ArrayList;
14
import java.util.ArrayList;
14
import java.util.List;
15
import java.util.List;
15
16
17
import org.eclipse.core.runtime.IPath;
18
import org.eclipse.core.runtime.Platform;
16
import org.eclipse.gef.palette.PaletteContainer;
19
import org.eclipse.gef.palette.PaletteContainer;
17
import org.eclipse.gef.palette.PaletteDrawer;
20
import org.eclipse.gef.palette.PaletteDrawer;
18
import org.eclipse.gef.palette.PaletteEntry;
21
import org.eclipse.gef.palette.PaletteEntry;
Lines 22-38 Link Here
22
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
25
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
23
import org.eclipse.wst.common.snippets.core.ISnippetsEntry;
26
import org.eclipse.wst.common.snippets.core.ISnippetsEntry;
24
import org.eclipse.wst.common.snippets.internal.Logger;
27
import org.eclipse.wst.common.snippets.internal.Logger;
28
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
25
import org.eclipse.wst.common.snippets.internal.editors.ISnippetEditor;
29
import org.eclipse.wst.common.snippets.internal.editors.ISnippetEditor;
26
import org.eclipse.wst.common.snippets.internal.model.SnippetManager;
30
import org.eclipse.wst.common.snippets.internal.model.SnippetManager;
27
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteDrawer;
31
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteDrawer;
28
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteDrawerFactory;
32
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteDrawerFactory;
29
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
33
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
30
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItemFactory;
34
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItemFactory;
35
import org.osgi.framework.Bundle;
31
36
32
37
33
public class SnippetsCustomizer extends PaletteCustomizer {
38
public class SnippetsCustomizer extends PaletteCustomizer {
39
	
34
	protected List activeEditors = new ArrayList();
40
	protected List activeEditors = new ArrayList();
35
	protected List factories = null;
41
	protected List factories = null;
42
	private List<String> deleted = new ArrayList<String>();
36
43
37
	public SnippetsCustomizer() {
44
	public SnippetsCustomizer() {
38
		super();
45
		super();
Lines 117-122 Link Here
117
				Logger.logException(e);
124
				Logger.logException(e);
118
			}
125
			}
119
		}
126
		}
127
		
128
		for (String deletedId : deleted) {
129
			Bundle bundle = Platform.getBundle(SnippetsPlugin.BUNDLE_ID);
130
			IPath path = Platform.getStateLocation(bundle).append(deletedId);
131
			File folder = new File(path.toOSString());
132
			deleteFolders(folder);
133
		}
134
		deleted.clear();
120
135
121
		activeEditors = new ArrayList(0);
136
		activeEditors = new ArrayList(0);
122
137
Lines 127-130 Link Here
127
			Logger.logException(e);
142
			Logger.logException(e);
128
		}
143
		}
129
	}
144
	}
145
	
146
	private void deleteFolders(File folder) {
147
		if (!folder.exists()){
148
			return;
149
		}
150
		File[] listFiles = folder.listFiles();
151
		for (File file : listFiles) {
152
			if (file.isDirectory()){
153
				deleteFolders(file);
154
			} else {
155
				file.delete();
156
			}
157
		}
158
		folder.delete();
159
	}
160
161
	@Override
162
	public void performDelete(PaletteEntry entry) {
163
		deleted.add(entry.getId());
164
		super.performDelete(entry);
165
	}
166
130
}
167
}
(-)src/org/eclipse/wst/common/snippets/internal/ui/SnippetsView.java (-2 / +6 lines)
Lines 83-89 Link Here
83
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteRoot;
83
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteRoot;
84
import org.eclipse.wst.common.snippets.internal.util.UserDrawerSelector;
84
import org.eclipse.wst.common.snippets.internal.util.UserDrawerSelector;
85
import org.eclipse.wst.common.snippets.internal.util.VisibilityUtil;
85
import org.eclipse.wst.common.snippets.internal.util.VisibilityUtil;
86
import org.eclipse.wst.common.snippets.ui.DefaultSnippetInsertion;
87
import org.eclipse.wst.common.snippets.ui.ISnippetInsertion;
86
import org.eclipse.wst.common.snippets.ui.ISnippetInsertion;
88
import org.osgi.framework.Bundle;
87
import org.osgi.framework.Bundle;
89
88
Lines 199-206 Link Here
199
					}
198
					}
200
				}
199
				}
201
			}
200
			}
201
			 
202
			if (insertion == null) {
202
			if (insertion == null) {
203
				insertion = new DefaultSnippetInsertion();
203
				if (item.getProvider()!= null){
204
					insertion = item.getProvider().getSnippetInstertion();
205
				} 
204
			}
206
			}
205
			return insertion;
207
			return insertion;
206
		}
208
		}
Lines 828-833 Link Here
828
				insertion.setItem(item);
830
				insertion.setItem(item);
829
				insertion.setEditorPart(getSite().getPage().getActiveEditor());
831
				insertion.setEditorPart(getSite().getPage().getActiveEditor());
830
				supportedTypes = insertion.getTransfers();
832
				supportedTypes = insertion.getTransfers();
833
			} else {
834
				supportedTypes = new Transfer[]{TextTransfer.getInstance()};
831
			}
835
			}
832
		}
836
		}
833
		else {
837
		else {
(-)src/org/eclipse/wst/common/snippets/internal/ui/EntryDeserializer.java (+2 lines)
Lines 22-27 Link Here
22
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
22
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
23
import org.eclipse.wst.common.snippets.internal.palette.SnippetVariable;
23
import org.eclipse.wst.common.snippets.internal.palette.SnippetVariable;
24
import org.eclipse.wst.common.snippets.internal.util.CommonXML;
24
import org.eclipse.wst.common.snippets.internal.util.CommonXML;
25
import org.eclipse.wst.common.snippets.internal.util.SnippetProviderManager;
25
import org.w3c.dom.Document;
26
import org.w3c.dom.Document;
26
import org.w3c.dom.Element;
27
import org.w3c.dom.Element;
27
import org.w3c.dom.Node;
28
import org.w3c.dom.Node;
Lines 72-77 Link Here
72
		item.setCategoryName(element.getAttribute(SnippetsPlugin.NAMES.CATEGORY));
73
		item.setCategoryName(element.getAttribute(SnippetsPlugin.NAMES.CATEGORY));
73
		item.setClassName(element.getAttribute(SnippetsPlugin.NAMES.CLASSNAME));
74
		item.setClassName(element.getAttribute(SnippetsPlugin.NAMES.CLASSNAME));
74
		item.setEditorClassName(element.getAttribute(SnippetsPlugin.NAMES.EDITORCLASSNAME));
75
		item.setEditorClassName(element.getAttribute(SnippetsPlugin.NAMES.EDITORCLASSNAME));
76
		item.setProvider(SnippetProviderManager.findProvider(element.getAttribute(SnippetsPlugin.NAMES.PROVIDER_ID)));
75
		NodeList children = element.getChildNodes();
77
		NodeList children = element.getChildNodes();
76
		int length = children.getLength();
78
		int length = children.getLength();
77
		for (int i = 0; i < length; i++) {
79
		for (int i = 0; i < length; i++) {
(-)src/org/eclipse/wst/common/snippets/internal/ui/EntrySerializer.java (+2 lines)
Lines 116-121 Link Here
116
			element.setAttribute(SnippetsPlugin.NAMES.CLASSNAME, item.getClassName());
116
			element.setAttribute(SnippetsPlugin.NAMES.CLASSNAME, item.getClassName());
117
		if (item.getEditorClassName() != null)
117
		if (item.getEditorClassName() != null)
118
			element.setAttribute(SnippetsPlugin.NAMES.EDITORCLASSNAME, item.getEditorClassName());
118
			element.setAttribute(SnippetsPlugin.NAMES.EDITORCLASSNAME, item.getEditorClassName());
119
		if (item.getProvider() != null)
120
			element.setAttribute(SnippetsPlugin.NAMES.PROVIDER_ID, item.getProvider().getId());
119
		if (item.getContentString() != null)
121
		if (item.getContentString() != null)
120
			element.appendChild(createContent(doc, item));
122
			element.appendChild(createContent(doc, item));
121
		ISnippetVariable[] variables = item.getVariables();
123
		ISnippetVariable[] variables = item.getVariables();
(-)META-INF/MANIFEST.MF (-2 / +3 lines)
Lines 25-30 Link Here
25
 org.eclipse.ui;bundle-version="[3.4.0,4.0.0)",
25
 org.eclipse.ui;bundle-version="[3.4.0,4.0.0)",
26
 org.eclipse.jface.text;bundle-version="[3.4.0,4.0.0)",
26
 org.eclipse.jface.text;bundle-version="[3.4.0,4.0.0)",
27
 org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
27
 org.eclipse.core.resources;bundle-version="[3.4.0,4.0.0)",
28
 org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)"
28
 org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)",
29
 org.eclipse.core.expressions
29
Bundle-ActivationPolicy: lazy
30
Bundle-ActivationPolicy: lazy
30
Bundle-RequiredExecutionEnvironment: J2SE-1.4
31
Bundle-RequiredExecutionEnvironment: J2SE-1.5
(-).classpath (-2 / +2 lines)
Lines 1-7 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
2
<classpath>
3
	<classpathentry kind="src" path="src"/>
3
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
4
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.4"/>
5
	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
4
	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
5
	<classpathentry kind="src" path="src"/>
6
	<classpathentry kind="output" path="bin"/>
6
	<classpathentry kind="output" path="bin"/>
7
</classpath>
7
</classpath>
(-)plugin.xml (+17 lines)
Lines 6-11 Link Here
6
		id="SnippetContributions"
6
		id="SnippetContributions"
7
		name="%Snippets_View_Contributions_Extension.name"
7
		name="%Snippets_View_Contributions_Extension.name"
8
		schema="schema/SnippetContributions.exsd" />
8
		schema="schema/SnippetContributions.exsd" />
9
		
10
 <extension-point 
11
 	id="SnippetProvider" 
12
 	name="%extension-point.name.0" 
13
 	schema="schema/SnippetProvider.exsd"/>
9
14
10
	<!-- the view itself -->
15
	<!-- the view itself -->
11
	<extension point="org.eclipse.ui.views">
16
	<extension point="org.eclipse.ui.views">
Lines 175-178 Link Here
175
			</action>
180
			</action>
176
		</viewerContribution>
181
		</viewerContribution>
177
	</extension>
182
	</extension>
183
 <extension
184
       point="org.eclipse.wst.common.snippets.SnippetProvider">
185
    <provider
186
          impl="org.eclipse.wst.common.snippets.ui.TextSnippetProvider"
187
          priority="100">
188
       <enablement>
189
          <instanceof
190
                value="org.eclipse.ui.texteditor.ITextEditor">
191
          </instanceof>
192
       </enablement>
193
    </provider>
194
 </extension>
178
</plugin>
195
</plugin>
(-)plugin.properties (+2 lines)
Lines 13-15 Link Here
13
Snippets.name=Snippets
13
Snippets.name=Snippets
14
Snippets_View_Contributions_Extension.name=Snippets View Contributions Extension
14
Snippets_View_Contributions_Extension.name=Snippets View Contributions Extension
15
Add_to_Snippets.name=Add to Snippets...
15
Add_to_Snippets.name=Add to Snippets...
16
17
extension-point.name.0 = SnippetProvider
(-)src/org/eclipse/wst/common/snippets/internal/palette/ModelFactoryForPlugins.java (+1 lines)
Lines 169-174 Link Here
169
		setProperty(item, SnippetsPlugin.NAMES.ID, element.getAttribute(SnippetsPlugin.NAMES.ID));
169
		setProperty(item, SnippetsPlugin.NAMES.ID, element.getAttribute(SnippetsPlugin.NAMES.ID));
170
		setProperty(item, SnippetsPlugin.NAMES.LABEL, element.getAttribute(SnippetsPlugin.NAMES.LABEL));
170
		setProperty(item, SnippetsPlugin.NAMES.LABEL, element.getAttribute(SnippetsPlugin.NAMES.LABEL));
171
		setProperty(item, SnippetsPlugin.NAMES.LARGEICON, element.getAttribute(SnippetsPlugin.NAMES.LARGEICON));
171
		setProperty(item, SnippetsPlugin.NAMES.LARGEICON, element.getAttribute(SnippetsPlugin.NAMES.LARGEICON));
172
		setProperty(item, SnippetsPlugin.NAMES.PROVIDER_ID, element.getAttribute(SnippetsPlugin.NAMES.PROVIDER_ID));
172
173
173
		IConfigurationElement[] children = element.getChildren();
174
		IConfigurationElement[] children = element.getChildren();
174
		for (int i = 0; i < children.length; i++) {
175
		for (int i = 0; i < children.length; i++) {
(-)src/org/eclipse/wst/common/snippets/internal/palette/UserModelDumper.java (-7 / +4 lines)
Lines 178-183 Link Here
178
			element.setAttribute(SnippetsPlugin.NAMES.CLASSNAME, ((SnippetPaletteItem) item).getClassName());
178
			element.setAttribute(SnippetsPlugin.NAMES.CLASSNAME, ((SnippetPaletteItem) item).getClassName());
179
		if (((SnippetPaletteItem) item).getEditorClassName() != null)
179
		if (((SnippetPaletteItem) item).getEditorClassName() != null)
180
			element.setAttribute(SnippetsPlugin.NAMES.EDITORCLASSNAME, ((SnippetPaletteItem) item).getEditorClassName());
180
			element.setAttribute(SnippetsPlugin.NAMES.EDITORCLASSNAME, ((SnippetPaletteItem) item).getEditorClassName());
181
		if (((SnippetPaletteItem) item).getProvider() != null)
182
			element.setAttribute(SnippetsPlugin.NAMES.PROVIDER_ID, ((SnippetPaletteItem) item).getProvider().getId());
181
		element.appendChild(createContent(doc, item));
183
		element.appendChild(createContent(doc, item));
182
		ISnippetVariable[] variables = item.getVariables();
184
		ISnippetVariable[] variables = item.getVariables();
183
		for (int i = 0; i < variables.length; i++) {
185
		for (int i = 0; i < variables.length; i++) {
Lines 279-291 Link Here
279
			Logger.log(Logger.ERROR, "could not save " + stream, e); //$NON-NLS-1$
281
			Logger.log(Logger.ERROR, "could not save " + stream, e); //$NON-NLS-1$
280
		}
282
		}
281
		finally {
283
		finally {
282
			try {
284
			//				stream.close();
283
				stream.close();
285
			document = null;
284
				document = null;
285
			}
286
			catch (IOException e) {
287
				// nothing to be done while closing
288
			}
289
		}
286
		}
290
	}
287
	}
291
288
(-)src/org/eclipse/wst/common/snippets/internal/palette/SnippetCustomizerDialog.java (-30 / +200 lines)
Lines 10-21 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.wst.common.snippets.internal.palette;
11
package org.eclipse.wst.common.snippets.internal.palette;
12
12
13
import java.io.BufferedInputStream;
14
import java.io.BufferedOutputStream;
15
import java.io.File;
16
import java.io.FileInputStream;
13
import java.io.FileNotFoundException;
17
import java.io.FileNotFoundException;
14
import java.io.FileOutputStream;
18
import java.io.FileOutputStream;
15
import java.io.IOException;
19
import java.io.IOException;
20
import java.io.InputStream;
16
import java.io.OutputStream;
21
import java.io.OutputStream;
22
import java.util.Enumeration;
17
import java.util.List;
23
import java.util.List;
24
import java.util.zip.ZipEntry;
25
import java.util.zip.ZipException;
26
import java.util.zip.ZipFile;
27
import java.util.zip.ZipOutputStream;
18
28
29
import org.eclipse.core.runtime.Platform;
19
import org.eclipse.gef.palette.PaletteDrawer;
30
import org.eclipse.gef.palette.PaletteDrawer;
20
import org.eclipse.gef.palette.PaletteEntry;
31
import org.eclipse.gef.palette.PaletteEntry;
21
import org.eclipse.gef.palette.PaletteRoot;
32
import org.eclipse.gef.palette.PaletteRoot;
Lines 32-47 Link Here
32
import org.eclipse.swt.widgets.Shell;
43
import org.eclipse.swt.widgets.Shell;
33
import org.eclipse.ui.PlatformUI;
44
import org.eclipse.ui.PlatformUI;
34
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
45
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
46
import org.eclipse.wst.common.snippets.core.ISnippetItem;
35
import org.eclipse.wst.common.snippets.internal.IHelpContextIds;
47
import org.eclipse.wst.common.snippets.internal.IHelpContextIds;
36
import org.eclipse.wst.common.snippets.internal.SnippetDefinitions;
48
import org.eclipse.wst.common.snippets.internal.SnippetDefinitions;
37
import org.eclipse.wst.common.snippets.internal.SnippetsMessages;
49
import org.eclipse.wst.common.snippets.internal.SnippetsMessages;
50
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
38
import org.eclipse.wst.common.snippets.internal.SnippetsPluginImageHelper;
51
import org.eclipse.wst.common.snippets.internal.SnippetsPluginImageHelper;
39
import org.eclipse.wst.common.snippets.internal.SnippetsPluginImages;
52
import org.eclipse.wst.common.snippets.internal.SnippetsPluginImages;
40
import org.eclipse.wst.common.snippets.internal.model.SnippetManager;
53
import org.eclipse.wst.common.snippets.internal.model.SnippetManager;
41
import org.eclipse.wst.common.snippets.internal.ui.SnippetsCustomizer;
54
import org.eclipse.wst.common.snippets.internal.ui.SnippetsCustomizer;
55
import org.osgi.framework.Bundle;
42
56
43
public class SnippetCustomizerDialog extends PaletteCustomizerDialog {
57
public class SnippetCustomizerDialog extends PaletteCustomizerDialog {
44
58
59
	private enum EXPORT_IMPORT_STRATEGY {
60
		ARCHIVE, XML;
61
	}
62
45
	private class ExportAction extends PaletteCustomizationAction {
63
	private class ExportAction extends PaletteCustomizationAction {
46
		public ExportAction() {
64
		public ExportAction() {
47
			setEnabled(false);
65
			setEnabled(false);
Lines 54-86 Link Here
54
72
55
		protected void handleExport() {
73
		protected void handleExport() {
56
			PaletteDrawer exportCategory = (PaletteDrawer) getSelectedPaletteEntry();
74
			PaletteDrawer exportCategory = (PaletteDrawer) getSelectedPaletteEntry();
75
			EXPORT_IMPORT_STRATEGY strategy = exportStrategy(exportCategory);
57
76
58
			final FileDialog fileDialog = new FileDialog(getShell(), SWT.SAVE);
77
			if (EXPORT_IMPORT_STRATEGY.ARCHIVE == strategy){
59
			fileDialog.setText(SnippetsMessages.Export_Snippets);
78
				exportArchive(exportCategory);
60
			fileDialog.setFileName("snippets.xml"); //$NON-NLS-1$
79
			} else {
61
			String[] filterExtensions = new String[2];
80
				exportXML(exportCategory);				
62
			filterExtensions[0] = "*.xml"; //$NON-NLS-1$
81
			}
63
			filterExtensions[1] = "*.*"; //$NON-NLS-1$
82
			updateActions();
64
			fileDialog.setFilterExtensions(filterExtensions);
83
		}
65
			String filename = fileDialog.open();
84
85
		private EXPORT_IMPORT_STRATEGY exportStrategy(PaletteDrawer exportCategory) {
86
			List<ISnippetItem> children = exportCategory.getChildren();
87
			for (ISnippetItem snippetItem : children) {
88
				File folder = new File(SnippetManager.getInstance().getStorage(snippetItem.getId()).toOSString());
89
				if (folder.exists()){
90
					return EXPORT_IMPORT_STRATEGY.ARCHIVE;
91
				}
92
			}
93
			return EXPORT_IMPORT_STRATEGY.XML;
94
		}
95
96
		private void exportArchive(PaletteDrawer exportCategory) {
97
			String filename = openFileDialog("*.zip");//$NON-NLS-1$
66
			if (filename != null) {
98
			if (filename != null) {
67
				SnippetDefinitions definitions = ModelFactoryForUser.getInstance().load(filename);
99
				ZipOutputStream outputStream = null;
68
				ISnippetCategory existingCategory = definitions.getCategory(exportCategory.getId());
100
				try {
101
					SnippetDefinitions definitions = getCategory(exportCategory, filename);
102
					outputStream = new ZipOutputStream(new FileOutputStream(filename));
103
					ZipEntry descriptorFile = new ZipEntry("snippets.xml");
104
					outputStream.putNextEntry(descriptorFile); 
105
					new UserModelDumper().write(definitions, outputStream);
106
					ISnippetCategory existingCategory = definitions.getCategory(exportCategory.getId());
107
					ISnippetItem[] items = existingCategory.getItems();
108
					for (ISnippetItem item : items) {
109
						File folder = new File(SnippetManager.getInstance().getStorage(item.getId()).toOSString());
110
						if (folder.exists()){
111
							addToZip(folder.getParentFile(), folder, outputStream);
112
						}
113
					}
114
				}
115
				catch (FileNotFoundException e) {
116
					// should not have problem finding the output file
117
					e.printStackTrace();
118
				} catch (IOException e) {
119
					e.printStackTrace();
120
				}
121
				finally {
122
					if (outputStream != null)
123
						try {
124
							outputStream.close();
125
						}
126
					catch (IOException e) {
127
						// should not have problem closing the output file
128
						e.printStackTrace();
129
					}
130
				}
131
			}
132
		}
69
133
70
				if (existingCategory == null)
134
		private void addToZip(File root, File folder, ZipOutputStream outputStream) throws IOException {
71
					definitions.getCategories().add(exportCategory);
135
			File[] listFiles = folder.listFiles();
72
				else {
136
			for (File file : listFiles) {
73
					String title = SnippetsMessages.SnippetCustomizerDialog_2; //$NON-NLS-1$
137
				if (file.isDirectory()){
74
					String message = NLS.bind(SnippetsMessages.SnippetCustomizerDialog_4, new String[]{existingCategory.getLabel()});
138
					addToZip(root, file, outputStream);
75
					boolean answer = MessageDialog.openConfirm(getShell(), title, message);
139
				} else {
76
					if (answer) {
140
					ZipEntry ze = new ZipEntry(file.getAbsolutePath().substring(root.getAbsolutePath().length()+1));
77
						definitions.getCategories().remove(existingCategory);
141
					outputStream.putNextEntry(ze);
78
						definitions.getCategories().add(exportCategory);
142
					BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 1024);
143
					byte[] data    = new byte[1024];
144
					int count;
145
					while((count = bis.read(data,0,1024)) != -1) {
146
						outputStream.write(data, 0, count);
79
					}
147
					}
148
					bis.close();
80
				}
149
				}
150
			}
151
		}
81
152
82
				OutputStream outputStream = null;
153
		private void exportXML(PaletteDrawer exportCategory) {
83
				try {
154
			String filename = openFileDialog("*.xml");//$NON-NLS-1$
155
156
			OutputStream outputStream = null;
157
			if (filename != null) {
158
				try{
159
					SnippetDefinitions definitions = getCategory(exportCategory, filename);
84
					outputStream = new FileOutputStream(filename);
160
					outputStream = new FileOutputStream(filename);
85
					new UserModelDumper().write(definitions, outputStream);
161
					new UserModelDumper().write(definitions, outputStream);
86
				}
162
				}
Lines 93-106 Link Here
93
						try {
169
						try {
94
							outputStream.close();
170
							outputStream.close();
95
						}
171
						}
96
						catch (IOException e) {
172
					catch (IOException e) {
97
							// should not have problem closing the output file
173
						// should not have problem closing the output file
98
							e.printStackTrace();
174
						e.printStackTrace();
99
						}
175
					}
100
				}
176
				}
101
177
102
				updateActions();
103
			}
178
			}
179
180
181
		}
182
183
		private SnippetDefinitions getCategory(PaletteDrawer exportCategory,
184
				String fileName) {
185
			SnippetDefinitions definitions = ModelFactoryForUser.getInstance().load(fileName);
186
			ISnippetCategory existingCategory = definitions.getCategory(exportCategory.getId());
187
188
			if (existingCategory == null)
189
				definitions.getCategories().add(exportCategory);
190
			else {
191
				String title = SnippetsMessages.SnippetCustomizerDialog_2; //$NON-NLS-1$
192
				String message = NLS.bind(SnippetsMessages.SnippetCustomizerDialog_4, new String[]{existingCategory.getLabel()});
193
				boolean answer = MessageDialog.openConfirm(getShell(), title, message);
194
				if (answer) {
195
					definitions.getCategories().remove(existingCategory);
196
					definitions.getCategories().add(exportCategory);
197
				}
198
			}
199
			return definitions;
200
		}
201
202
		private String openFileDialog(String extension) {
203
			final FileDialog fileDialog = new FileDialog(getShell(), SWT.SAVE);
204
			fileDialog.setText(SnippetsMessages.Export_Snippets);
205
			fileDialog.setFileName("snippets"+ extension.substring(1)); //$NON-NLS-1$
206
			String[] filterExtensions = new String[2];
207
			filterExtensions[0] = extension;
208
			filterExtensions[1] = "*.*"; //$NON-NLS-1$
209
			fileDialog.setFilterExtensions(filterExtensions);
210
			String filename = fileDialog.open();
211
			return filename;
104
		}
212
		}
105
213
106
		public void run() {
214
		public void run() {
Lines 132-145 Link Here
132
		protected void handleImport() {
240
		protected void handleImport() {
133
			final FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
241
			final FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
134
			fileDialog.setText(SnippetsMessages.Import_Snippets);
242
			fileDialog.setText(SnippetsMessages.Import_Snippets);
135
			fileDialog.setFileName("snippets.xml"); //$NON-NLS-1$
243
//			fileDialog.setFileName("snippets.xml"); //$NON-NLS-1$
136
			String[] filterExtensions = new String[2];
244
			String[] filterExtensions = new String[2];
137
			filterExtensions[0] = "*.xml"; //$NON-NLS-1$
245
			filterExtensions[0] = "*.xml; *.zip"; //$NON-NLS-1$
138
			filterExtensions[1] = "*.*"; //$NON-NLS-1$
246
			filterExtensions[1] = "*.*"; //$NON-NLS-1$
139
			fileDialog.setFilterExtensions(filterExtensions);
247
			fileDialog.setFilterExtensions(filterExtensions);
140
			String filename = fileDialog.open();
248
			String filename = fileDialog.open();
141
			if (filename != null) {
249
			try {
142
				SnippetDefinitions definitions = ModelFactoryForUser.getInstance().load(filename);
250
				if (filename.toLowerCase().endsWith(".zip")){
251
					ZipFile zip = new ZipFile(new File(filename));
252
					ZipEntry entry = zip.getEntry("snippets.xml");
253
					loadMetadata(zip.getInputStream(entry));
254
					Bundle bundle = Platform.getBundle(SnippetsPlugin.BUNDLE_ID);
255
					unzip(zip, Platform.getStateLocation(bundle).toOSString());
256
				} else {
257
					loadMetadata(new FileInputStream(filename));
258
				}
259
260
				
261
			} catch (FileNotFoundException e) {
262
				e.printStackTrace();
263
			} catch (ZipException e) {
264
				// TODO Auto-generated catch block
265
				e.printStackTrace();
266
			} catch (IOException e) {
267
				// TODO Auto-generated catch block
268
				e.printStackTrace();
269
			}
270
		}
271
272
		private void loadMetadata(InputStream fileInputStream) {
273
			if (fileInputStream != null) {
274
				SnippetDefinitions definitions = ModelFactoryForUser.getInstance().load(fileInputStream);
143
				List importCategories = definitions.getCategories();
275
				List importCategories = definitions.getCategories();
144
				List currentCategories = SnippetManager.getInstance().getDefinitions().getCategories();
276
				List currentCategories = SnippetManager.getInstance().getDefinitions().getCategories();
145
				PaletteEntry lastImportEntry = null;
277
				PaletteEntry lastImportEntry = null;
Lines 215-218 Link Here
215
347
216
		return super.open();
348
		return super.open();
217
	}
349
	}
350
351
	public static final void copyInputStream(InputStream in, OutputStream out)
352
	throws IOException
353
	{
354
		byte[] buffer = new byte[1024];
355
		int len;
356
357
		while((len = in.read(buffer)) >= 0)
358
			out.write(buffer, 0, len);
359
360
		in.close();
361
		out.close();
362
	}
363
364
	public void unzip(ZipFile zipFile, String path) throws FileNotFoundException, IOException {
365
		Enumeration entries;
366
		entries = zipFile.entries();
367
368
		while(entries.hasMoreElements()) {
369
			ZipEntry entry = (ZipEntry)entries.nextElement();
370
			File file = new File(path + File.separator+ entry.getName());
371
			if(entry.isDirectory()) {
372
				file.mkdir();
373
				continue;
374
			}
375
			if (!file.getParentFile().exists()){
376
				file.getParentFile().mkdirs();
377
			}
378
			if (entry.getName().toLowerCase().equals("snippets.xml")){
379
				continue;
380
			}
381
382
			copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file)));
383
		}
384
385
		zipFile.close();
386
	}
387
218
}
388
}
(-)src/org/eclipse/wst/common/snippets/internal/palette/ModelFactoryForUser.java (+37 lines)
Lines 219-224 Link Here
219
219
220
		return definitions;
220
		return definitions;
221
	}
221
	}
222
	
223
	public SnippetDefinitions load(InputStream in) {
224
		SnippetDefinitions definitions = new SnippetDefinitions();
225
		Document document = null;
226
		try {
227
			DocumentBuilder builder = CommonXML.getDocumentBuilder();
228
			if (builder != null) {
229
				document = builder.parse(new InputSource(in));
230
			}
231
			else {
232
				Logger.log(Logger.ERROR, "Couldn't obtain a DocumentBuilder"); //$NON-NLS-1$
233
			}
234
		}
235
		catch (FileNotFoundException e) {
236
			// typical of new workspace, don't log it
237
			document = null;
238
		}
239
		catch (IOException e) {
240
			Logger.logException("Could not load user items", e); //$NON-NLS-1$
241
			return definitions;
242
		}
243
		catch (SAXException e) {
244
			Logger.logException("Could not load user items", e); //$NON-NLS-1$
245
			return definitions;
246
		}
247
		if (document == null)
248
			return definitions;
249
		Element library = document.getDocumentElement();
250
		if (library == null || !library.getNodeName().equals(SnippetsPlugin.NAMES.SNIPPETS))
251
			return definitions;
252
		loadDefinitions(definitions, library);
253
254
		connectItemsAndCategories(definitions);
255
256
		return definitions;
257
	}
222
258
223
	public SnippetDefinitions loadCurrent() {
259
	public SnippetDefinitions loadCurrent() {
224
		return load(getFilename());
260
		return load(getFilename());
Lines 313-318 Link Here
313
		setProperty(item, SnippetsPlugin.NAMES.ID, element.getAttribute(SnippetsPlugin.NAMES.ID));
349
		setProperty(item, SnippetsPlugin.NAMES.ID, element.getAttribute(SnippetsPlugin.NAMES.ID));
314
		setProperty(item, SnippetsPlugin.NAMES.LABEL, element.getAttribute(SnippetsPlugin.NAMES.LABEL));
350
		setProperty(item, SnippetsPlugin.NAMES.LABEL, element.getAttribute(SnippetsPlugin.NAMES.LABEL));
315
		setProperty(item, SnippetsPlugin.NAMES.LARGEICON, element.getAttribute(SnippetsPlugin.NAMES.LARGEICON));
351
		setProperty(item, SnippetsPlugin.NAMES.LARGEICON, element.getAttribute(SnippetsPlugin.NAMES.LARGEICON));
352
		setProperty(item, SnippetsPlugin.NAMES.PROVIDER_ID, element.getAttribute(SnippetsPlugin.NAMES.PROVIDER_ID));
316
353
317
		NodeList children = element.getChildNodes();
354
		NodeList children = element.getChildNodes();
318
		for (int i = 0; i < children.getLength(); i++) {
355
		for (int i = 0; i < children.getLength(); i++) {
(-)src/org/eclipse/wst/common/snippets/internal/palette/SnippetPaletteItem.java (+20 lines)
Lines 16-27 Link Here
16
import java.util.Arrays;
16
import java.util.Arrays;
17
import java.util.List;
17
import java.util.List;
18
18
19
import org.eclipse.core.runtime.IPath;
20
import org.eclipse.core.runtime.Platform;
19
import org.eclipse.gef.palette.PaletteContainer;
21
import org.eclipse.gef.palette.PaletteContainer;
20
import org.eclipse.gef.palette.PaletteTemplateEntry;
22
import org.eclipse.gef.palette.PaletteTemplateEntry;
21
import org.eclipse.jface.resource.ImageDescriptor;
23
import org.eclipse.jface.resource.ImageDescriptor;
22
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
24
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
23
import org.eclipse.wst.common.snippets.core.ISnippetItem;
25
import org.eclipse.wst.common.snippets.core.ISnippetItem;
26
import org.eclipse.wst.common.snippets.core.ISnippetProvider;
24
import org.eclipse.wst.common.snippets.core.ISnippetVariable;
27
import org.eclipse.wst.common.snippets.core.ISnippetVariable;
28
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
29
import org.osgi.framework.Bundle;
25
30
26
public class SnippetPaletteItem extends PaletteTemplateEntry implements ISnippetItem {
31
public class SnippetPaletteItem extends PaletteTemplateEntry implements ISnippetItem {
27
32
Lines 38-43 Link Here
38
	protected Object fSourceDescriptor;
43
	protected Object fSourceDescriptor;
39
	protected Object fSourceType = SNIPPET_SOURCE_USER;
44
	protected Object fSourceType = SNIPPET_SOURCE_USER;
40
	protected List fVariables;
45
	protected List fVariables;
46
	private ISnippetProvider provider;
41
47
42
	/**
48
	/**
43
	 * @param label
49
	 * @param label
Lines 219-222 Link Here
219
		fVariables = new ArrayList(variables.length);
225
		fVariables = new ArrayList(variables.length);
220
		fVariables.addAll(Arrays.asList(variables));
226
		fVariables.addAll(Arrays.asList(variables));
221
	}
227
	}
228
229
	public IPath getStorage() {
230
		Bundle bundle = Platform.getBundle(SnippetsPlugin.BUNDLE_ID);
231
		return Platform.getStateLocation(bundle).append(getId());
232
	}
233
234
235
	public ISnippetProvider getProvider() {
236
		return provider;
237
	}
238
239
	public void setProvider(ISnippetProvider provider) {
240
		this.provider = provider;
241
	}
222
}
242
}
(-)src/org/eclipse/wst/common/snippets/internal/palette/AbstractModelFactory.java (+4 lines)
Lines 20-25 Link Here
20
import org.eclipse.wst.common.snippets.internal.Logger;
20
import org.eclipse.wst.common.snippets.internal.Logger;
21
import org.eclipse.wst.common.snippets.internal.SnippetDefinitions;
21
import org.eclipse.wst.common.snippets.internal.SnippetDefinitions;
22
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
22
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
23
import org.eclipse.wst.common.snippets.internal.util.SnippetProviderManager;
23
24
24
public abstract class AbstractModelFactory {
25
public abstract class AbstractModelFactory {
25
26
Lines 73-78 Link Here
73
		setProperties(item, source);
74
		setProperties(item, source);
74
75
75
		migrate50to51(item);
76
		migrate50to51(item);
77
		
76
		return item;
78
		return item;
77
	}
79
	}
78
80
Lines 176-181 Link Here
176
			item.setContentString(propertyValue.toString());
178
			item.setContentString(propertyValue.toString());
177
		else if (property.equals(SnippetsPlugin.NAMES.EDITORCLASSNAME))
179
		else if (property.equals(SnippetsPlugin.NAMES.EDITORCLASSNAME))
178
			item.setEditorClassName(propertyValue.toString());
180
			item.setEditorClassName(propertyValue.toString());
181
		else if (property.equals(SnippetsPlugin.NAMES.PROVIDER_ID))
182
			item.setProvider(SnippetProviderManager.findProvider(propertyValue.toString()));
179
		else
183
		else
180
			setEntryProperty(item, property, propertyValue);
184
			setEntryProperty(item, property, propertyValue);
181
	}
185
	}
(-)src/org/eclipse/wst/common/snippets/internal/actions/AddToSnippetsEditorActionDelegate.java (-79 / +25 lines)
Lines 10-44 Link Here
10
 *******************************************************************************/
10
 *******************************************************************************/
11
package org.eclipse.wst.common.snippets.internal.actions;
11
package org.eclipse.wst.common.snippets.internal.actions;
12
12
13
import org.eclipse.core.runtime.CoreException;
13
import org.eclipse.gef.palette.PaletteDrawer;
14
import org.eclipse.gef.palette.PaletteDrawer;
14
import org.eclipse.gef.ui.palette.customize.PaletteCustomizerDialog;
15
import org.eclipse.gef.ui.palette.customize.PaletteCustomizerDialog;
15
import org.eclipse.jface.action.IAction;
16
import org.eclipse.jface.action.IAction;
16
import org.eclipse.jface.text.BadLocationException;
17
import org.eclipse.jface.text.IDocument;
18
import org.eclipse.jface.text.ITextSelection;
19
import org.eclipse.jface.text.TextSelection;
20
import org.eclipse.jface.viewers.ISelection;
17
import org.eclipse.jface.viewers.ISelection;
21
import org.eclipse.ui.IEditorActionDelegate;
18
import org.eclipse.ui.IEditorActionDelegate;
22
import org.eclipse.ui.IEditorPart;
19
import org.eclipse.ui.IEditorPart;
23
import org.eclipse.ui.IViewActionDelegate;
20
import org.eclipse.ui.IViewActionDelegate;
24
import org.eclipse.ui.IViewPart;
21
import org.eclipse.ui.IViewPart;
25
import org.eclipse.ui.IWorkbenchPart;
26
import org.eclipse.ui.PartInitException;
22
import org.eclipse.ui.PartInitException;
27
import org.eclipse.ui.texteditor.ITextEditor;
23
import org.eclipse.wst.common.snippets.core.ISnippetProvider;
28
import org.eclipse.wst.common.snippets.internal.Logger;
24
import org.eclipse.wst.common.snippets.internal.Logger;
29
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
25
import org.eclipse.wst.common.snippets.internal.SnippetsPlugin;
30
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
26
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
31
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItemFactory;
32
import org.eclipse.wst.common.snippets.internal.ui.SnippetsView;
27
import org.eclipse.wst.common.snippets.internal.ui.SnippetsView;
33
import org.eclipse.wst.common.snippets.internal.util.StringUtils;
28
import org.eclipse.wst.common.snippets.internal.util.SnippetProviderManager;
34
import org.eclipse.wst.common.snippets.internal.util.UserDrawerSelector;
29
import org.eclipse.wst.common.snippets.internal.util.UserDrawerSelector;
35
30
36
31
37
public class AddToSnippetsEditorActionDelegate implements IEditorActionDelegate, IViewActionDelegate {
32
public class AddToSnippetsEditorActionDelegate implements IEditorActionDelegate, IViewActionDelegate {
38
33
39
	private IAction fAction;
40
	private IEditorPart fEditorPart;
34
	private IEditorPart fEditorPart;
41
	private IViewPart fViewPart = null;
35
	private ISnippetProvider selectionProvider;
42
36
43
	/**
37
	/**
44
	 * 
38
	 * 
Lines 47-81 Link Here
47
		super();
41
		super();
48
	}
42
	}
49
43
50
	public IDocument getDocument() {
51
		return getTextEditor().getDocumentProvider().getDocument(fEditorPart.getEditorInput());
52
	}
53
54
	protected ITextSelection getSelection() {
55
		ITextEditor editor = getTextEditor();
56
		if (editor != null) {
57
			ISelection selection = editor.getSelectionProvider().getSelection();
58
			if (selection instanceof ITextSelection) {
59
				return (ITextSelection) selection;
60
			}
61
		}
62
		return new TextSelection(0, 0);
63
	}
64
65
	protected ITextEditor getTextEditor() {
66
		ITextEditor editor = null;
67
		IWorkbenchPart activePart = fViewPart;
68
		if (activePart == null) {
69
			activePart = fEditorPart;
70
		}
71
		if (activePart instanceof ITextEditor) {
72
			editor = (ITextEditor) activePart;
73
		}
74
		if (editor == null) {
75
			editor = (ITextEditor) activePart.getAdapter(ITextEditor.class);
76
		}
77
		return editor;
78
	}
79
44
80
	/**
45
	/**
81
	 * Prompts the user as needed to obtain a category to contain the new
46
	 * Prompts the user as needed to obtain a category to contain the new
Lines 90-104 Link Here
90
		return drawer;
55
		return drawer;
91
	}
56
	}
92
57
93
	/*
94
	 * (non-Javadoc)
95
	 * 
96
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
97
	 */
98
	public void init(IViewPart view) {
58
	public void init(IViewPart view) {
99
		fViewPart = view;
100
	}
59
	}
101
60
61
102
	/*
62
	/*
103
	 * (non-Javadoc)
63
	 * (non-Javadoc)
104
	 * 
64
	 * 
Lines 108-132 Link Here
108
		PaletteDrawer drawer = getUserDrawer();
68
		PaletteDrawer drawer = getUserDrawer();
109
69
110
		if (drawer != null) {
70
		if (drawer != null) {
111
			ITextSelection selection = getSelection();
71
			if (selectionProvider ==null){
112
			String selectedText = null;
72
				selectionProvider = SnippetProviderManager.getApplicableProvider(fEditorPart);
73
				if (selectionProvider ==null){
74
					return;
75
				}
76
			}
77
			
113
			try {
78
			try {
114
				selectedText = getDocument().get(selection.getOffset(), selection.getLength());
79
				SnippetPaletteItem item = selectionProvider.createSnippet(drawer);
115
80
				IViewPart snippets = fEditorPart.getEditorSite().getPage().showView(SnippetsPlugin.NAMES.VIEW_ID);
116
				SnippetPaletteItem item = (SnippetPaletteItem) new SnippetPaletteItemFactory().createNewEntry(fEditorPart.getSite().getShell(), drawer);
117
				item.setDescription(StringUtils.firstLineOf(selectedText).trim() + "..."); //$NON-NLS-1$
118
				item.setContentString(selectedText);
119
120
				IViewPart snippets = fEditorPart.getEditorSite().getPage().showView(SnippetsPlugin.NAMES.VIEW_ID); //$NON-NLS-1$
121
				PaletteCustomizerDialog dialog = ((SnippetsView) snippets).getViewer().getCustomizerDialog();
81
				PaletteCustomizerDialog dialog = ((SnippetsView) snippets).getViewer().getCustomizerDialog();
122
				dialog.setDefaultSelection(item);
82
				dialog.setDefaultSelection(item);
123
				dialog.open();
83
				dialog.open();
124
			}
84
			} catch (PartInitException e) {
125
			catch (BadLocationException e) {
85
				Logger.logException(e);
86
			} catch (CoreException e) {
126
				Logger.logException(e);
87
				Logger.logException(e);
127
			}
128
			catch (PartInitException e1) {
129
				Logger.logException(e1);
130
			}
88
			}
131
		}
89
		}
132
	}
90
	}
Lines 138-145 Link Here
138
	 *      org.eclipse.jface.viewers.ISelection)
96
	 *      org.eclipse.jface.viewers.ISelection)
139
	 */
97
	 */
140
	public void selectionChanged(IAction action, ISelection selection) {
98
	public void selectionChanged(IAction action, ISelection selection) {
141
		fAction = action;
99
		if (selectionProvider != null){
142
		updateWith(selection);
100
			action.setEnabled(selectionProvider.isActionEnabled(selection));
101
		}
143
	}
102
	}
144
103
145
	/*
104
	/*
Lines 150-175 Link Here
150
	 */
109
	 */
151
	public void setActiveEditor(IAction action, IEditorPart targetEditor) {
110
	public void setActiveEditor(IAction action, IEditorPart targetEditor) {
152
		fEditorPart = targetEditor;
111
		fEditorPart = targetEditor;
153
		fAction = action;
112
		selectionProvider = SnippetProviderManager.getApplicableProvider(targetEditor);
154
		if (targetEditor != null && targetEditor.getEditorSite() != null && targetEditor.getEditorSite().getSelectionProvider() != null) {
113
		if (targetEditor != null && targetEditor.getEditorSite() != null && targetEditor.getEditorSite().getSelectionProvider() != null) {
155
			updateWith(targetEditor.getEditorSite().getSelectionProvider().getSelection());
114
			if (selectionProvider != null){
156
		}
115
				action.setEnabled(selectionProvider.isActionEnabled(targetEditor.getEditorSite().getSelectionProvider().getSelection()));
157
	}
158
159
	public void updateWith(ISelection selection) {
160
		if (fAction != null) {
161
			boolean enable = false;
162
			if (selection != null) {
163
				if (selection instanceof ITextSelection) {
164
					if (((ITextSelection) selection).getLength() > 0) {
165
						enable = true;
166
					}
167
				}
168
				else {
169
					enable = !selection.isEmpty();
170
				}
171
			}
116
			}
172
			fAction.setEnabled(enable);
117
			
173
		}
118
		}
174
	}
119
	}
120
175
}
121
}
(-)src/org/eclipse/wst/common/snippets/internal/model/SnippetManager.java (+96 lines)
Lines 13-21 Link Here
13
import java.beans.PropertyChangeEvent;
13
import java.beans.PropertyChangeEvent;
14
import java.beans.PropertyChangeListener;
14
import java.beans.PropertyChangeListener;
15
import java.io.File;
15
import java.io.File;
16
import java.io.FileInputStream;
16
import java.io.FileNotFoundException;
17
import java.io.FileNotFoundException;
17
import java.io.FileOutputStream;
18
import java.io.FileOutputStream;
18
import java.io.IOException;
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.io.OutputStream;
19
import java.util.ArrayList;
22
import java.util.ArrayList;
20
import java.util.Arrays;
23
import java.util.Arrays;
21
import java.util.Iterator;
24
import java.util.Iterator;
Lines 23-28 Link Here
23
26
24
import javax.xml.parsers.DocumentBuilder;
27
import javax.xml.parsers.DocumentBuilder;
25
28
29
import org.eclipse.core.resources.IFile;
30
import org.eclipse.core.resources.IProject;
31
import org.eclipse.core.runtime.CoreException;
32
import org.eclipse.core.runtime.IPath;
33
import org.eclipse.core.runtime.IStatus;
34
import org.eclipse.core.runtime.NullProgressMonitor;
35
import org.eclipse.core.runtime.Path;
36
import org.eclipse.core.runtime.Platform;
37
import org.eclipse.core.runtime.Status;
26
import org.eclipse.gef.palette.PaletteContainer;
38
import org.eclipse.gef.palette.PaletteContainer;
27
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
39
import org.eclipse.wst.common.snippets.core.ISnippetCategory;
28
import org.eclipse.wst.common.snippets.core.ISnippetsEntry;
40
import org.eclipse.wst.common.snippets.core.ISnippetsEntry;
Lines 40-45 Link Here
40
import org.eclipse.wst.common.snippets.internal.palette.WorkspaceModelDumper;
52
import org.eclipse.wst.common.snippets.internal.palette.WorkspaceModelDumper;
41
import org.eclipse.wst.common.snippets.internal.team.CategoryFileInfo;
53
import org.eclipse.wst.common.snippets.internal.team.CategoryFileInfo;
42
import org.eclipse.wst.common.snippets.internal.util.CommonXML;
54
import org.eclipse.wst.common.snippets.internal.util.CommonXML;
55
import org.osgi.framework.Bundle;
43
import org.w3c.dom.Document;
56
import org.w3c.dom.Document;
44
import org.w3c.dom.Element;
57
import org.w3c.dom.Element;
45
import org.w3c.dom.Node;
58
import org.w3c.dom.Node;
Lines 407-411 Link Here
407
			Logger.logException(e);
420
			Logger.logException(e);
408
		}
421
		}
409
	}
422
	}
423
	
424
	public IPath getStorage(String id) {
425
		Bundle bundle = Platform.getBundle(SnippetsPlugin.BUNDLE_ID);
426
		return Platform.getStateLocation(bundle).append(id);
427
	}
428
	
429
	/**
430
	 * Helper method for saving resources in designated snippet resource folder.
431
	 * 
432
	 * @param snippetId - UID of the snippet that is saving content.
433
	 * @param pathList - Project relative path list. The resources are copied in the same structure 
434
	 * 					 in the storage path. e.g. having test.jsp file in project root will result in
435
	 * 					 test.jsp in the storage root. If the jsp  is in [Project Root]/resources/test.jsp
436
	 * 					 this will result in [Snippet Storage Root]/resources/test.jsp 
437
	 * @return
438
	 */
439
	public IStatus moveFilesInStorageFolder(IPath snippetStorage, List<IPath> pathList, IProject project){
440
		File storageFolder = new File(snippetStorage.toOSString());
441
		if (!storageFolder.exists()){
442
			if (!storageFolder.mkdirs()){
443
				return createErrorStatus("Could not create snippet storage folder.", null);
444
			}
445
		}
446
		for (IPath currentPath : pathList) {
447
			IFile file = project.getFile(currentPath);
448
			IPath destPath = snippetStorage.append(currentPath);
449
			File destination = new File(destPath.toOSString());
450
			if (!destination.getParentFile().exists()){
451
				if (!destination.getParentFile().mkdirs()){
452
					return createErrorStatus("Could not create snippet storage folder.", null);
453
				}
454
			}	
455
			try {
456
				copy(file, destination);
457
			} catch (FileNotFoundException e) {
458
				return createErrorStatus(e.getLocalizedMessage(), e);
459
			} catch (IOException e) {
460
				return createErrorStatus(e.getLocalizedMessage(), e);
461
			} catch (CoreException e) {
462
				return e.getStatus();
463
			}
464
		}
465
		
466
		return Status.OK_STATUS;
467
	}
468
	
469
	public IStatus moveFilesInWorkspace(List<File> fileList, IProject target, IPath storagePath) {
470
		for (File file : fileList) {
471
			String fileRelativePath = file.getAbsolutePath().substring(storagePath.toOSString().length());
472
			IFile ifile = target.getFile(new Path(fileRelativePath));
473
			try {
474
				ifile.create(new FileInputStream(file), true, new NullProgressMonitor());
475
			} catch (FileNotFoundException e) {
476
				return createErrorStatus(e.getLocalizedMessage(), e);
477
			} catch (CoreException e) {
478
				return createErrorStatus(e.getLocalizedMessage(), e);
479
			}
480
		}
481
		
482
		return Status.OK_STATUS;
483
	}
484
	
485
	private void copy(IFile source, File destination) throws FileNotFoundException, IOException, CoreException{
486
		copy(source.getContents(), new FileOutputStream(destination));
487
	}	
488
	
489
	private void copy(InputStream in, OutputStream out) throws IOException {
490
		byte[] buffer = new byte[1024];
491
		try {
492
			int n = in.read(buffer);
493
			while (n > 0) {
494
				out.write(buffer, 0, n);
495
				n = in.read(buffer);
496
			}
497
		} finally {
498
			in.close();
499
			out.close();
500
		}
501
	}
502
	
503
	private IStatus createErrorStatus(String msg, Exception e) {
504
		return new Status(IStatus.ERROR, SnippetsPlugin.BUNDLE_ID, msg, e);
505
	}	
410
506
411
}
507
}
(-).settings/org.eclipse.jdt.core.prefs (-7 / +7 lines)
Lines 1-4 Link Here
1
#Wed Mar 28 03:12:48 EDT 2007
1
#Fri Jul 17 15:30:07 EEST 2009
2
eclipse.preferences.version=1
2
eclipse.preferences.version=1
3
org.eclipse.jdt.core.builder.cleanOutputFolder=clean
3
org.eclipse.jdt.core.builder.cleanOutputFolder=clean
4
org.eclipse.jdt.core.builder.duplicateResourceTask=warning
4
org.eclipse.jdt.core.builder.duplicateResourceTask=warning
Lines 7-30 Link Here
7
org.eclipse.jdt.core.circularClasspath=error
7
org.eclipse.jdt.core.circularClasspath=error
8
org.eclipse.jdt.core.classpath.exclusionPatterns=enabled
8
org.eclipse.jdt.core.classpath.exclusionPatterns=enabled
9
org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled
9
org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled
10
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled
10
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
11
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
11
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
12
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
12
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
13
org.eclipse.jdt.core.compiler.compliance=1.4
13
org.eclipse.jdt.core.compiler.compliance=1.5
14
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
14
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
15
org.eclipse.jdt.core.compiler.debug.localVariable=generate
15
org.eclipse.jdt.core.compiler.debug.localVariable=generate
16
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
16
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
17
org.eclipse.jdt.core.compiler.doc.comment.support=enabled
17
org.eclipse.jdt.core.compiler.doc.comment.support=enabled
18
org.eclipse.jdt.core.compiler.maxProblemPerUnit=100
18
org.eclipse.jdt.core.compiler.maxProblemPerUnit=100
19
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
19
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
20
org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
20
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
21
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
21
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
22
org.eclipse.jdt.core.compiler.problem.deprecation=ignore
22
org.eclipse.jdt.core.compiler.problem.deprecation=ignore
23
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
23
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
24
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled
24
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled
25
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
25
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
26
org.eclipse.jdt.core.compiler.problem.emptyStatement=warning
26
org.eclipse.jdt.core.compiler.problem.emptyStatement=warning
27
org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
27
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
28
org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
28
org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
29
org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore
29
org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore
30
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error
30
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error
Lines 74-79 Link Here
74
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
74
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
75
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error
75
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error
76
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
76
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
77
org.eclipse.jdt.core.compiler.source=1.3
77
org.eclipse.jdt.core.compiler.source=1.5
78
org.eclipse.jdt.core.incompatibleJDKLevel=ignore
78
org.eclipse.jdt.core.incompatibleJDKLevel=ignore
79
org.eclipse.jdt.core.incompleteClasspath=error
79
org.eclipse.jdt.core.incompleteClasspath=error
(-)src/org/eclipse/wst/common/snippets/internal/SnippetsPlugin.java (+1 lines)
Lines 43-48 Link Here
43
		String VARIABLES = "variables"; //$NON-NLS-1$
43
		String VARIABLES = "variables"; //$NON-NLS-1$
44
		String VERSION = "version"; //$NON-NLS-1$
44
		String VERSION = "version"; //$NON-NLS-1$
45
		String VIEW_ID = "org.eclipse.wst.common.snippets.internal.ui.SnippetsView"; //$NON-NLS-1$
45
		String VIEW_ID = "org.eclipse.wst.common.snippets.internal.ui.SnippetsView"; //$NON-NLS-1$
46
		String PROVIDER_ID = "snippetProvider";//$NON-NLS-1$
46
	}
47
	}
47
48
48
	public static final String BUNDLE_ID = "org.eclipse.wst.common.snippets"; //$NON-NLS-1$
49
	public static final String BUNDLE_ID = "org.eclipse.wst.common.snippets"; //$NON-NLS-1$
(-)schema/SnippetProvider.exsd (+115 lines)
Added Link Here
1
<?xml version='1.0' encoding='UTF-8'?>
2
<!-- Schema file written by PDE -->
3
<schema targetNamespace="org.eclipse.wst.common.snippets" xmlns="http://www.w3.org/2001/XMLSchema">
4
<annotation>
5
      <appInfo>
6
         <meta.schema plugin="org.eclipse.wst.common.snippets" id="SnippetProvider" name="SnippetProvider"/>
7
      </appInfo>
8
      <documentation>
9
         [Enter description of this extension point.]
10
      </documentation>
11
   </annotation>
12
13
   <include schemaLocation="schema://org.eclipse.core.expressions/schema/expressionLanguage.exsd"/>
14
15
   <element name="extension">
16
      <annotation>
17
         <appInfo>
18
            <meta.element />
19
         </appInfo>
20
      </annotation>
21
      <complexType>
22
         <sequence>
23
            <element ref="provider" minOccurs="1" maxOccurs="unbounded"/>
24
         </sequence>
25
         <attribute name="point" type="string" use="required">
26
            <annotation>
27
               <documentation>
28
                  
29
               </documentation>
30
            </annotation>
31
         </attribute>
32
         <attribute name="id" type="string">
33
            <annotation>
34
               <documentation>
35
                  
36
               </documentation>
37
            </annotation>
38
         </attribute>
39
         <attribute name="name" type="string">
40
            <annotation>
41
               <documentation>
42
                  
43
               </documentation>
44
               <appInfo>
45
                  <meta.attribute translatable="true"/>
46
               </appInfo>
47
            </annotation>
48
         </attribute>
49
      </complexType>
50
   </element>
51
52
   <element name="provider">
53
      <complexType>
54
         <sequence>
55
            <element ref="enablement"/>
56
         </sequence>
57
         <attribute name="impl" type="string">
58
            <annotation>
59
               <documentation>
60
                  
61
               </documentation>
62
               <appInfo>
63
                  <meta.attribute kind="java" basedOn=":org.eclipse.wst.common.snippets.ui.ISnippetProvider"/>
64
               </appInfo>
65
            </annotation>
66
         </attribute>
67
         <attribute name="priority" type="string" use="required">
68
            <annotation>
69
               <documentation>
70
                  0 highest 
71
100 lowest
72
               </documentation>
73
            </annotation>
74
         </attribute>
75
      </complexType>
76
   </element>
77
78
   <annotation>
79
      <appInfo>
80
         <meta.section type="since"/>
81
      </appInfo>
82
      <documentation>
83
         [Enter the first release in which this extension point appears.]
84
      </documentation>
85
   </annotation>
86
87
   <annotation>
88
      <appInfo>
89
         <meta.section type="examples"/>
90
      </appInfo>
91
      <documentation>
92
         [Enter extension point usage example here.]
93
      </documentation>
94
   </annotation>
95
96
   <annotation>
97
      <appInfo>
98
         <meta.section type="apiinfo"/>
99
      </appInfo>
100
      <documentation>
101
         [Enter API information here.]
102
      </documentation>
103
   </annotation>
104
105
   <annotation>
106
      <appInfo>
107
         <meta.section type="implementation"/>
108
      </appInfo>
109
      <documentation>
110
         [Enter information about supplied implementation of this extension point.]
111
      </documentation>
112
   </annotation>
113
114
115
</schema>
(-)src/org/eclipse/wst/common/snippets/internal/dnd/SnippetTransfer.java (+106 lines)
Added Link Here
1
package org.eclipse.wst.common.snippets.internal.dnd;
2
3
4
import org.eclipse.swt.dnd.ByteArrayTransfer;
5
import org.eclipse.swt.dnd.TransferData;
6
7
8
/**
9
 * This derived implementation of a byte array transfer short circuits the transfer process
10
 * so that a local transfer does not serialize the object
11
 * and hence can and will return the original object, not just a clone.
12
 * You only really need ever know about {@link #getInstance ObjectTransfer.getInstance()},
13
 * so that you can include it in when adding drag support to a viewer.
14
 * See {@link EditingDomainViewerDropAdapter} and {@link ViewerDragAdapter} for more details.
15
 * <p>
16
 * As an addded guard, the time is recorded and serialized in javaToNative
17
 * to that navive to java can ensure that it's returns the value that was really to have been transferred.
18
 */
19
public class SnippetTransfer extends ByteArrayTransfer
20
{
21
  /**
22
   * This is the register transfer type name.
23
   */
24
  protected static final String TYPE_NAME = "local-transfer-format";
25
26
  /**
27
   * This is the ID that is registered to the name.
28
   */
29
  protected static final int TYPE_ID = registerType(TYPE_NAME);
30
31
  /**
32
   * This is initialized and returned by {@link #getInstance}.
33
   */
34
  protected static SnippetTransfer instance;
35
36
  /**
37
   * This returns the one instance of this transfer agent.
38
   */
39
  public static SnippetTransfer getInstance()
40
  {
41
    if (instance == null)
42
    {
43
      instance = new SnippetTransfer();
44
    }
45
46
    return instance;
47
  }
48
49
  /**
50
   * This records the time at which the transfer data was recorded.
51
   */
52
  protected long startTime;
53
54
  /**
55
   * This records the data being transferred.
56
   */
57
  protected Object object;
58
59
  /**
60
   * This creates an instance; typically you get one from {@link #getInstance}.
61
   */
62
  protected SnippetTransfer()
63
  {
64
  }
65
66
  /**
67
   * This returns the transfer ids that this agent supports.
68
   */
69
  protected int[] getTypeIds() 
70
  {
71
    return new int[] { TYPE_ID };
72
  }
73
74
  /**
75
   * This returns the transfer names that this agent supports.
76
   */
77
  public String[] getTypeNames() 
78
  {
79
    return new String[] { TYPE_NAME };
80
  }
81
82
  /**
83
   * This records the object and current time and encodes only the current time into the transfer data.
84
   */
85
  public void javaToNative(Object object, TransferData transferData) 
86
  {
87
    startTime = System.currentTimeMillis();
88
    this.object = object;
89
    if (transferData != null)
90
    {
91
      super.javaToNative(String.valueOf(startTime).getBytes(), transferData);
92
    }
93
  }
94
95
  /**
96
   * This decodes the time of the transfer and returns the recorded the object if the recorded time and the decoded time match.
97
   */
98
  public Object nativeToJava(TransferData transferData) 
99
  {
100
    long startTime  = Long.valueOf(new String((byte[])super.nativeToJava(transferData))).longValue();
101
    return
102
      this.startTime == startTime ?
103
        object :
104
        null;
105
  }
106
}
(-)src/org/eclipse/wst/common/snippets/ui/TextSnippetProvider.java (+97 lines)
Added Link Here
1
package org.eclipse.wst.common.snippets.ui;
2
3
import org.eclipse.core.runtime.CoreException;
4
import org.eclipse.core.runtime.IPath;
5
import org.eclipse.core.runtime.IStatus;
6
import org.eclipse.core.runtime.Status;
7
import org.eclipse.gef.palette.PaletteEntry;
8
import org.eclipse.jface.text.BadLocationException;
9
import org.eclipse.jface.text.IDocument;
10
import org.eclipse.jface.text.ITextSelection;
11
import org.eclipse.jface.viewers.ISelection;
12
import org.eclipse.ui.IWorkbenchPart;
13
import org.eclipse.ui.texteditor.ITextEditor;
14
import org.eclipse.wst.common.snippets.core.ISnippetProvider;
15
import org.eclipse.wst.common.snippets.internal.AbstractSnippetProvider;
16
import org.eclipse.wst.common.snippets.internal.Logger;
17
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
18
import org.eclipse.wst.common.snippets.internal.util.StringUtils;
19
20
public class TextSnippetProvider extends AbstractSnippetProvider implements ISnippetProvider {
21
22
23
	@Override
24
	public SnippetPaletteItem createSnippet(PaletteEntry drawer) throws CoreException {
25
		SnippetPaletteItem item = super.createSnippet(drawer);
26
		ITextSelection selection = getTextSelection();
27
		String selectedText = null;
28
		try {
29
			selectedText = getDocument().get(selection.getOffset(), selection.getLength());			
30
			item.setDescription(StringUtils.firstLineOf(selectedText).trim() + "..."); //$NON-NLS-1$
31
			item.setContentString(selectedText);
32
		}
33
		catch (BadLocationException e) {
34
			Logger.logException(e);
35
		}
36
		return item;
37
	}
38
	
39
40
	protected ITextSelection getTextSelection() {
41
		ITextEditor editor = getTextEditor();
42
		if (editor != null) {
43
			ISelection selection = editor.getSelectionProvider().getSelection();
44
			if (selection instanceof ITextSelection) {
45
				return (ITextSelection) selection;
46
			}
47
		}
48
		return null;
49
	}
50
51
	protected ITextEditor getTextEditor() {
52
		ITextEditor editor = null;
53
		IWorkbenchPart activePart = fEditorPart;
54
		
55
		if (activePart instanceof ITextEditor) {
56
			editor = (ITextEditor) activePart;
57
		}
58
		if (editor == null) {
59
			editor = (ITextEditor) activePart.getAdapter(ITextEditor.class);
60
		}
61
		return editor;
62
	}
63
64
	public boolean isActionEnabled(ISelection selection) {
65
		boolean enable = false;
66
		if (selection != null) {
67
			if (selection instanceof ITextSelection) {
68
				if (((ITextSelection) selection).getLength() > 0) {
69
					enable = true;
70
				}
71
			}
72
			else {
73
				enable = !selection.isEmpty();
74
			}
75
		}
76
		return enable;
77
	}
78
79
	public IDocument getDocument() {
80
		return getTextEditor().getDocumentProvider().getDocument(fEditorPart.getEditorInput());
81
	}
82
83
	public IStatus saveAdditionalContent(IPath path) {
84
		return Status.OK_STATUS;
85
	}
86
87
88
	public ISnippetInsertion getSnippetInstertion() {
89
		return new DefaultSnippetInsertion();
90
	}
91
92
93
	public String getId() {
94
		return TextSnippetProvider.class.getCanonicalName();
95
	}
96
97
}
(-)src/org/eclipse/wst/common/snippets/core/ISnippetProvider.java (+26 lines)
Added Link Here
1
package org.eclipse.wst.common.snippets.core;
2
3
import org.eclipse.core.runtime.CoreException;
4
import org.eclipse.core.runtime.IPath;
5
import org.eclipse.core.runtime.IStatus;
6
import org.eclipse.gef.palette.PaletteEntry;
7
import org.eclipse.jface.viewers.ISelection;
8
import org.eclipse.ui.IEditorPart;
9
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
10
import org.eclipse.wst.common.snippets.ui.ISnippetInsertion;
11
12
public interface ISnippetProvider {
13
	
14
	public SnippetPaletteItem createSnippet(PaletteEntry drawer) throws CoreException ;
15
	
16
	public boolean isActionEnabled(ISelection selection);
17
18
	public IStatus saveAdditionalContent(IPath path);
19
	
20
	public ISnippetInsertion getSnippetInstertion();
21
	
22
	public String getId();
23
	
24
	public void setEditor(IEditorPart editor);
25
26
}
(-)src/org/eclipse/wst/common/snippets/internal/SnippetContrubutor.java (+92 lines)
Added Link Here
1
package org.eclipse.wst.common.snippets.internal;
2
3
import org.eclipse.core.expressions.EvaluationContext;
4
import org.eclipse.core.expressions.EvaluationResult;
5
import org.eclipse.core.expressions.Expression;
6
import org.eclipse.core.expressions.ExpressionConverter;
7
import org.eclipse.core.runtime.CoreException;
8
import org.eclipse.core.runtime.IConfigurationElement;
9
import org.eclipse.wst.common.snippets.core.ISnippetProvider;
10
11
public class SnippetContrubutor {
12
	
13
	public static final String ID_EXTENSION_POINT_PROVIDER  = SnippetsPlugin.BUNDLE_ID + ".SnippetProvider"; //$NON-NLS-1$
14
	public static final String IMPL  = "impl"; //$NON-NLS-1$
15
	public static final String PRIO  = "priority"; //$NON-NLS-1$
16
	public static final String ENABLEMENT  = "enablement"; //$NON-NLS-1$
17
	
18
	private ISnippetProvider provider;
19
	private IConfigurationElement extPointElement;
20
	private byte prio;
21
	
22
	
23
24
	private boolean initExecuted = false;
25
	
26
	
27
	public SnippetContrubutor(IConfigurationElement extPointElement) {
28
		super();
29
		this.extPointElement = extPointElement;
30
		init0();
31
	}
32
	
33
	private void init0() {
34
		if (extPointElement.getAttribute(PRIO) != null){
35
			try{
36
				prio = (byte) Integer.parseInt(extPointElement.getAttribute(PRIO));
37
				if(prio < 0 || prio >100){
38
					prio = 100;
39
				}
40
			}catch (NumberFormatException e){
41
				prio = 100;
42
				Logger.logException(e);
43
			}
44
		}
45
	}
46
47
	private void init() {
48
		initExecuted = true;
49
		try {
50
			provider = (ISnippetProvider) extPointElement.createExecutableExtension(IMPL);
51
		} catch (CoreException e) {
52
			e.printStackTrace();
53
		}
54
			
55
56
	}
57
	
58
	
59
	public boolean isApplicable(Object o) {
60
		IConfigurationElement[] configurationElements = extPointElement.getChildren(ENABLEMENT);
61
		if(configurationElements != null)
62
			for (IConfigurationElement configurationElement : configurationElements) {
63
				try {
64
					return testEnablement(configurationElement,o);
65
				} catch (CoreException e) {
66
					//nothing to do testEnablement fails.
67
					return false;
68
				}
69
			}
70
		return false;
71
	}
72
	
73
	private boolean testEnablement(IConfigurationElement enable, Object o) throws CoreException{
74
		Expression exp= ExpressionConverter.getDefault().perform(enable);
75
		EvaluationContext context = new EvaluationContext(null, o);
76
		context.setAllowPluginActivation(true);
77
		return EvaluationResult.TRUE == exp.evaluate(context);
78
	}
79
	
80
	
81
	public ISnippetProvider getProvider() {
82
		if (!initExecuted){
83
			init();
84
		}
85
		return provider;
86
	}
87
	
88
	public byte getPrio() {
89
		return prio;
90
	}
91
92
}
(-)src/org/eclipse/wst/common/snippets/internal/AbstractSnippetProvider.java (+35 lines)
Added Link Here
1
package org.eclipse.wst.common.snippets.internal;
2
3
import org.eclipse.core.runtime.CoreException;
4
import org.eclipse.core.runtime.IStatus;
5
import org.eclipse.gef.palette.PaletteEntry;
6
import org.eclipse.ui.IEditorPart;
7
import org.eclipse.wst.common.snippets.core.ISnippetProvider;
8
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
9
import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItemFactory;
10
11
public abstract class AbstractSnippetProvider implements ISnippetProvider {
12
	
13
	protected IEditorPart fEditorPart;
14
15
	public void setEditor(IEditorPart editor) {
16
		fEditorPart = editor;
17
18
	}
19
	
20
	public SnippetPaletteItem createSnippet(PaletteEntry drawer) throws CoreException {
21
		SnippetPaletteItem snippet = createSnippetMetadata(drawer);
22
		return snippet;
23
	}
24
	
25
	protected SnippetPaletteItem createSnippetMetadata(PaletteEntry drawer) throws CoreException {
26
		SnippetPaletteItem item = (SnippetPaletteItem) new SnippetPaletteItemFactory().createNewEntry(fEditorPart.getSite().getShell(), drawer);
27
		item.setProvider(this);
28
		IStatus status = saveAdditionalContent(item.getStorage());
29
		if (status!= null && status.getSeverity() == IStatus.ERROR){
30
			throw new CoreException(status);
31
		}
32
		return item;
33
	}
34
35
}
(-)src/org/eclipse/wst/common/snippets/internal/util/SnippetProviderManager.java (+78 lines)
Added Link Here
1
package org.eclipse.wst.common.snippets.internal.util;
2
3
import java.util.ArrayList;
4
import java.util.List;
5
6
import org.eclipse.core.runtime.IConfigurationElement;
7
import org.eclipse.core.runtime.IExtension;
8
import org.eclipse.core.runtime.IExtensionPoint;
9
import org.eclipse.core.runtime.Platform;
10
import org.eclipse.ui.IEditorPart;
11
import org.eclipse.wst.common.snippets.core.ISnippetProvider;
12
import org.eclipse.wst.common.snippets.internal.SnippetContrubutor;
13
import org.eclipse.wst.common.snippets.ui.TextSnippetProvider;
14
15
16
public class SnippetProviderManager {
17
18
	private static List<ISnippetProvider> getProviders() {
19
		List<ISnippetProvider> list = new ArrayList<ISnippetProvider>();
20
		IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(SnippetContrubutor.ID_EXTENSION_POINT_PROVIDER);
21
		if (extensionPoint != null) {
22
			IExtension[] extensions = extensionPoint.getExtensions();
23
			for (int i = 0; i < extensions.length; i++) {
24
				IConfigurationElement[] configurationElements = extensions[i].getConfigurationElements();
25
				for (IConfigurationElement configurationElement : configurationElements) {
26
					SnippetContrubutor sc = new SnippetContrubutor(configurationElement);
27
					if (sc.getProvider() != null){
28
						list.add(sc.getProvider());
29
					}					
30
				}
31
				
32
			}
33
		}
34
		return list;
35
	}
36
	
37
	public static ISnippetProvider findProvider(String id) {
38
		List<ISnippetProvider> providers = getProviders();
39
		for (ISnippetProvider snippetProvider : providers) {
40
			if (snippetProvider.getId() != null && snippetProvider.getId().equals(id)){
41
				return snippetProvider;
42
			}
43
		}
44
		return new TextSnippetProvider();
45
	}
46
47
	public static ISnippetProvider getApplicableProvider(IEditorPart targetEditor) {
48
		SnippetContrubutor result = null;
49
		IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(SnippetContrubutor.ID_EXTENSION_POINT_PROVIDER);
50
		if (extensionPoint != null) {
51
			IExtension[] extensions = extensionPoint.getExtensions();
52
			for (int i = 0; i < extensions.length; i++) {
53
				IConfigurationElement[] configurationElements = extensions[i].getConfigurationElements();
54
				for (IConfigurationElement configurationElement : configurationElements) {
55
					SnippetContrubutor sc = new SnippetContrubutor(configurationElement);
56
					if (sc.isApplicable(targetEditor)){
57
						if (result == null){
58
							result = sc;
59
						} else if (result.getPrio() > sc.getPrio()){
60
							result = sc;
61
						}
62
					}					
63
				}
64
				
65
			}
66
		}
67
		if (result == null){
68
			 return null;
69
		}
70
		ISnippetProvider provider = result.getProvider();
71
		provider.setEditor(targetEditor);
72
		return provider;
73
	}
74
	
75
	
76
	
77
	
78
}

Return to bug 282114