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

Collapse All | Expand All

(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 19-25 Link Here
19
 org.eclipse.ui.texteditor.quickdiff,
19
 org.eclipse.ui.texteditor.quickdiff,
20
 org.eclipse.ui.texteditor.rulers,
20
 org.eclipse.ui.texteditor.rulers,
21
 org.eclipse.ui.texteditor.spelling,
21
 org.eclipse.ui.texteditor.spelling,
22
 org.eclipse.ui.texteditor.templates
22
 org.eclipse.ui.texteditor.templates,
23
 org.eclipse.ui.texteditor.templates.view
23
Require-Bundle: 
24
Require-Bundle: 
24
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
25
 org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
25
 org.eclipse.core.expressions;bundle-version="[3.2.0,4.0.0)",
26
 org.eclipse.core.expressions;bundle-version="[3.2.0,4.0.0)",
(-)src/org/eclipse/ui/texteditor/templates/TemplatePreferencePage.java (-1 / +2 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.ui.texteditor.templates;
12
package org.eclipse.ui.texteditor.templates;
12
13
Lines 136-142 Link Here
136
	 *
137
	 *
137
	 * @since 3.3
138
	 * @since 3.3
138
	 */
139
	 */
139
	protected static class EditTemplateDialog extends StatusDialog {
140
	public static class EditTemplateDialog extends StatusDialog {
140
141
141
		private class TextViewerAction extends Action implements IUpdate {
142
		private class TextViewerAction extends Action implements IUpdate {
142
143
(-)src/org/eclipse/ui/texteditor/templates/view/TemplatesPageMessages.java (+63 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.texteditor.templates.view;
13
14
import org.eclipse.osgi.util.NLS;
15
16
/**
17
 * Helper class to get NLSed messages.
18
 *
19
 * @since 3.0
20
 */
21
final class TemplatesPageMessages extends NLS {
22
23
	private static final String BUNDLE_NAME= TemplatesPageMessages.class.getName();
24
	private TemplatesPageMessages() {
25
		// Do not instantiate
26
	}
27
28
	// TemplatesView
29
	public static String TemplatesPage_column_context;
30
	public static String TemplatesPage_column_description;
31
	public static String TemplatesPage_column_name;
32
	public static String TemplatesPage_insert;
33
	public static String TemplatesPage_edit;
34
	public static String TemplatesPage_copy;
35
	public static String TemplatesPage_paste;
36
	public static String TemplatesPage_preference_page;
37
	public static String TemplatesPage_link_to_editor;
38
	public static String TemplatesPage_collapse_all;
39
	public static String TemplatesPage_new;
40
	public static String TemplatesPage_remove;
41
	public static String TemplatesPage_insert_tooltip;
42
	public static String TemplatesPage_edit_tooltip;
43
	public static String TemplatesPage_preference_page_tooltip;
44
	public static String TemplatesPage_link_to_editor_tooltip;
45
	public static String TemplatesPage_collapse_all_tooltip;
46
	public static String TemplatesPage_new_tooltip;
47
	public static String TemplatesPage_remove_tooltip;
48
	public static String TemplatesPage_preview;
49
	public static String TemplatesPage_question_create_new_message;
50
	public static String TemplatesPage_question_create_new_title;
51
	public static String TemplatesPage_save_error_message;
52
	public static String TemplatesPage_snippet;
53
	public static String TemplatesPage_paste_description;
54
	public static String TemplatesPage_remove_message_single;
55
	public static String TemplatesPage_remove_message_multi;
56
	public static String TemplatesPage_remove_title_single;
57
	public static String TemplatesPage_remove_title_multi;
58
59
	static {
60
		NLS.initializeMessages(BUNDLE_NAME, TemplatesPageMessages.class);
61
	}
62
63
}
(-)src/org/eclipse/ui/texteditor/templates/view/TemplatesPageMessages.properties (+41 lines)
Added Link Here
1
###############################################################################
2
# Copyright (c) 2007 Dakshinamurthy Karra and others.
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
6
# http://www.eclipse.org/legal/epl-v10.html
7
#
8
# Contributors:
9
#     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
###############################################################################
11
12
# templates page (view)
13
TemplatesPage_collapse_all=Collapse All
14
TemplatesPage_column_context=Context
15
TemplatesPage_column_description=Description
16
TemplatesPage_save_error_message=Error Saving the Templates
17
TemplatesPage_column_name=Name
18
TemplatesPage_edit=&Edit...
19
TemplatesPage_insert=&Insert...
20
TemplatesPage_copy=Copy
21
TemplatesPage_paste=Paste
22
TemplatesPage_preference_page=&Preferences...
23
TemplatesPage_paste_description=Pasted from editor
24
TemplatesPage_link_to_editor=Link with Editor
25
TemplatesPage_new=&New...
26
TemplatesPage_preview=Preview
27
TemplatesPage_snippet=snippet
28
TemplatesPage_question_create_new_message= The name of the template has been changed. Click 'Yes' to create an additional template with the new name or 'No' to rename the existing one.
29
TemplatesPage_remove_title_single=Removing Template
30
TemplatesPage_remove_title_multi=Removing Templates
31
TemplatesPage_remove_message_single=Are you sure you want to remove the selected template?
32
TemplatesPage_remove_message_multi=Are you sure you want to remove {0} selected templates?
33
TemplatesPage_question_create_new_title= Edit Template
34
TemplatesPage_remove=&Remove
35
TemplatesPage_insert_tooltip=Insert into Editor
36
TemplatesPage_edit_tooltip=Edit the Template
37
TemplatesPage_preference_page_tooltip=Show Preference Page
38
TemplatesPage_link_to_editor_tooltip=Link with Editor
39
TemplatesPage_collapse_all_tooltip=Collapse All
40
TemplatesPage_new_tooltip=Create a New Template
41
TemplatesPage_remove_tooltip=Remove the Template
(-)src/org/eclipse/ui/texteditor/templates/view/TemplatesPageImages.java (+161 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.texteditor.templates.view;
13
14
import java.net.URL;
15
16
import org.eclipse.core.runtime.FileLocator;
17
import org.eclipse.core.runtime.Path;
18
import org.eclipse.core.runtime.Platform;
19
import org.eclipse.jface.resource.ImageDescriptor;
20
import org.eclipse.jface.resource.ImageRegistry;
21
import org.eclipse.swt.graphics.Image;
22
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
23
import org.osgi.framework.Bundle;
24
25
/**
26
 * The images provided by the texteditor plugin
27
 * 
28
 * @since 3.4
29
 */
30
public class TemplatesPageImages {
31
32
	static final String PREFIX_ELCL = TextEditorPlugin.PLUGIN_ID + ".elcl."; //$NON-NLS-1$
33
	static final String PREFIX_DLCL = TextEditorPlugin.PLUGIN_ID + ".dlcl."; //$NON-NLS-1$
34
	static final String PREFIX_OBJ = TextEditorPlugin.PLUGIN_ID + ".obj."; //$NON-NLS-1$
35
36
	static final String IMG_ELCL_TEMPLATE_NEW = PREFIX_ELCL + "new_template.gif"; //$NON-NLS-1$
37
	static final String IMG_ELCL_TEMPLATE_DELETE = PREFIX_ELCL + "delete_template.gif"; //$NON-NLS-1$
38
	static final String IMG_ELCL_TEMPLATE_EDIT = PREFIX_ELCL + "edit_template.gif"; //$NON-NLS-1$
39
	static final String IMG_ELCL_TEMPLATE_INSERT = PREFIX_ELCL + "insert_template.gif"; //$NON-NLS-1$
40
	static final String IMG_ELCL_TEMPLATE_LINK = PREFIX_ELCL + "link_to_editor.gif"; //$NON-NLS-1$
41
	static final String IMG_ELCL_TEMPLATE_COLLAPSE_ALL = PREFIX_ELCL + "collapseall.gif"; //$NON-NLS-1$
42
	static final String IMG_DLCL_TEMPLATE_DELETE = PREFIX_DLCL + "delete_template.gif"; //$NON-NLS-1$
43
	static final String IMG_DLCL_TEMPLATE_EDIT = PREFIX_DLCL + "edit_template.gif"; //$NON-NLS-1$
44
	static final String IMG_DLCL_TEMPLATE_INSERT = PREFIX_DLCL + "insert_template.gif"; //$NON-NLS-1$
45
46
	static final String IMG_OBJ_PREVIEW = PREFIX_OBJ + "preview.gif"; //$NON-NLS-1$
47
	static final String IMG_OBJ_CONTEXT = PREFIX_OBJ + "context.gif"; //$NON-NLS-1$
48
	static final String IMG_OBJ_TEMPLATE = PREFIX_OBJ + "template_obj.gif"; //$NON-NLS-1$
49
50
	/**
51
	 * The image registry containing <code>Image</code>s.
52
	 */
53
	private static ImageRegistry imageRegistry;
54
55
	private static String ICONS_PATH = "$nl$/icons/full/"; //$NON-NLS-1$
56
57
	// Use IPath and toOSString to build the names to ensure they have the
58
	// slashes correct
59
	private final static String ELCL = ICONS_PATH + "elcl16/"; //$NON-NLS-1$
60
	private final static String DLCL = ICONS_PATH + "dlcl16/"; //$NON-NLS-1$
61
	private final static String OBJ = ICONS_PATH + "obj16/"; //$NON-NLS-1$
62
63
	/**
64
	 * Declare all images
65
	 */
66
	private static void declareImages() {
67
		// Ant Editor images
68
		declareRegistryImage(IMG_ELCL_TEMPLATE_NEW, ELCL + "new_template.gif"); //$NON-NLS-1$
69
		declareRegistryImage(IMG_ELCL_TEMPLATE_INSERT, ELCL + "insert_template.gif"); //$NON-NLS-1$
70
		declareRegistryImage(IMG_DLCL_TEMPLATE_INSERT, DLCL + "insert_template.gif"); //$NON-NLS-1$
71
		declareRegistryImage(IMG_ELCL_TEMPLATE_DELETE, ELCL + "delete_template.gif"); //$NON-NLS-1$
72
		declareRegistryImage(IMG_DLCL_TEMPLATE_DELETE, DLCL + "delete_template.gif"); //$NON-NLS-1$
73
		declareRegistryImage(IMG_ELCL_TEMPLATE_EDIT, ELCL + "edit_template.gif"); //$NON-NLS-1$
74
		declareRegistryImage(IMG_DLCL_TEMPLATE_EDIT, DLCL + "edit_template.gif"); //$NON-NLS-1$
75
		declareRegistryImage(IMG_ELCL_TEMPLATE_LINK, ELCL + "link_to_editor.gif"); //$NON-NLS-1$
76
		declareRegistryImage(IMG_ELCL_TEMPLATE_COLLAPSE_ALL, ELCL + "collapseall.gif"); //$NON-NLS-1$
77
78
		declareRegistryImage(IMG_OBJ_PREVIEW, OBJ + "preview.gif"); //$NON-NLS-1$
79
		declareRegistryImage(IMG_OBJ_CONTEXT, OBJ + "context.gif"); //$NON-NLS-1$
80
		declareRegistryImage(IMG_OBJ_TEMPLATE, OBJ + "template_obj.gif"); //$NON-NLS-1$
81
	}
82
83
	/**
84
	 * Declare an Image in the registry table.
85
	 * 
86
	 * @param key
87
	 *            The key to use when registering the image
88
	 * @param path
89
	 *            The path where the image can be found. This path is relative
90
	 *            to where this plugin class is found (i.e. typically the
91
	 *            packages directory)
92
	 */
93
	private final static void declareRegistryImage(String key, String path) {
94
		ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor();
95
		Bundle bundle = Platform.getBundle(TextEditorPlugin.PLUGIN_ID);
96
		URL url = null;
97
		if (bundle != null) {
98
			url = FileLocator.find(bundle, new Path(path), null);
99
			desc = ImageDescriptor.createFromURL(url);
100
		}
101
		imageRegistry.put(key, desc);
102
	}
103
104
	/**
105
	 * Returns the ImageRegistry.
106
	 * 
107
	 * @return image registry
108
	 */
109
	public static ImageRegistry getImageRegistry() {
110
		if (imageRegistry == null) {
111
			initializeImageRegistry();
112
		}
113
		return imageRegistry;
114
	}
115
116
	/**
117
	 * Initialize the image registry by declaring all of the required graphics.
118
	 * This involves creating JFace image descriptors describing how to
119
	 * create/find the image should it be needed. The image is not actually
120
	 * allocated until requested.
121
	 * 
122
	 * Prefix conventions Wizard Banners WIZBAN_ Preference Banners PREF_BAN_
123
	 * Property Page Banners PROPBAN_ Color toolbar CTOOL_ Enable toolbar ETOOL_
124
	 * Disable toolbar DTOOL_ Local enabled toolbar ELCL_ Local Disable toolbar
125
	 * DLCL_ Object large OBJL_ Object small OBJS_ View VIEW_ Product images
126
	 * PROD_ Misc images MISC_
127
	 * 
128
	 * Where are the images? The images (typically gifs) are found in the same
129
	 * location as this plugin class. This may mean the same package directory
130
	 * as the package holding this class. The images are declared using
131
	 * this.getClass() to ensure they are looked up via this plugin class.
132
	 * 
133
	 * @return the image registry
134
	 * @see org.eclipse.jface.resource.ImageRegistry
135
	 */
136
	public static ImageRegistry initializeImageRegistry() {
137
		imageRegistry = TextEditorPlugin.getDefault().getImageRegistry();
138
		declareImages();
139
		return imageRegistry;
140
	}
141
142
	/**
143
	 * Returns the <code>Image<code> identified by the given key,
144
	 * or <code>null</code> if it does not exist.
145
	 * @param key 
146
	 * @return the image
147
	 */
148
	public static Image getImage(String key) {
149
		return getImageRegistry().get(key);
150
	}
151
152
	/**
153
	 * Returns the <code>ImageDescriptor<code> identified by the given key,
154
	 * or <code>null</code> if it does not exist.
155
	 * @param key 
156
	 * @return the image descriptor
157
	 */
158
	public static ImageDescriptor getImageDescriptor(String key) {
159
		return getImageRegistry().getDescriptor(key);
160
	}
161
}
(-)src/org/eclipse/ui/texteditor/templates/view/TemplateTransfer.java (+96 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.texteditor.templates.view;
13
14
import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
15
import org.eclipse.swt.dnd.ByteArrayTransfer;
16
import org.eclipse.swt.dnd.TransferData;
17
18
/**
19
 * Transfer type used for clip board and DnD operations for template objects
20
 * 
21
 * @see TemplatesPage
22
 *
23
 * @since 3.4
24
 */
25
public class TemplateTransfer extends ByteArrayTransfer {
26
27
	private static TemplateTransfer instance;
28
29
	private static final String LOCAL_NAME = TemplateTransfer.class.getName()
30
			+ System.currentTimeMillis();
31
	private static final int LOCAL_TYPE = registerType(LOCAL_NAME);
32
33
	private static String[] names = null;
34
	private static int types[] = null;
35
36
	private TemplatePersistenceData[] fObject ;
37
	
38
	/**
39
	 * @return the registered Transfer instance
40
	 */
41
	public static TemplateTransfer getInstance() {
42
		if (instance == null) {
43
			instance = new TemplateTransfer();
44
			types = new int[] { LOCAL_TYPE };
45
			names = new String[] { LOCAL_NAME };
46
		}
47
		return instance;
48
	}
49
50
	/*
51
	 * (non-Javadoc)
52
	 * 
53
	 * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
54
	 */
55
	protected int[] getTypeIds() {
56
		return types;
57
	}
58
59
	/*
60
	 * (non-Javadoc)
61
	 * 
62
	 * @see org.eclipse.swt.dnd.Transfer#getTypeNames()
63
	 */
64
	protected String[] getTypeNames() {
65
		return names;
66
	}
67
68
	/*
69
	 * (non-Javadoc)
70
	 * 
71
	 * @see org.eclipse.swt.dnd.ByteArrayTransfer#javaToNative(java.lang.Object,
72
	 *      org.eclipse.swt.dnd.TransferData)
73
	 */
74
	protected void javaToNative(Object object, TransferData transferData) {
75
		if (object == null || !(object instanceof TemplatePersistenceData[])
76
				|| !isSupportedType(transferData)) {
77
			fObject = null ;
78
			return;
79
		}
80
		fObject = (TemplatePersistenceData[]) object ;
81
		super.javaToNative(LOCAL_NAME.getBytes(), transferData);
82
	}
83
84
	/*
85
	 * (non-Javadoc)
86
	 * 
87
	 * @see org.eclipse.swt.dnd.ByteArrayTransfer#nativeToJava(org.eclipse.swt.dnd.TransferData)
88
	 */
89
	protected Object nativeToJava(TransferData transferData) {
90
        Object result = super.nativeToJava(transferData);
91
        if (!(result instanceof byte[])
92
                || !LOCAL_NAME.equals(new String((byte[]) result)))
93
        	return null ;
94
		return fObject ;
95
	}
96
}
(-)src/org/eclipse/ui/texteditor/templates/view/TemplatesPage.java (+1392 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.texteditor.templates.view;
13
14
import java.io.IOException;
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.HashMap;
18
import java.util.Iterator;
19
import java.util.List;
20
21
import org.eclipse.jface.action.Action;
22
import org.eclipse.jface.action.IAction;
23
import org.eclipse.jface.action.IMenuListener;
24
import org.eclipse.jface.action.IMenuManager;
25
import org.eclipse.jface.action.IToolBarManager;
26
import org.eclipse.jface.action.MenuManager;
27
import org.eclipse.jface.action.Separator;
28
import org.eclipse.jface.dialogs.MessageDialog;
29
import org.eclipse.jface.layout.TreeColumnLayout;
30
import org.eclipse.jface.preference.IPreferenceStore;
31
import org.eclipse.jface.resource.JFaceResources;
32
import org.eclipse.jface.text.templates.ContextTypeRegistry;
33
import org.eclipse.jface.text.templates.Template;
34
import org.eclipse.jface.text.templates.TemplateContextType;
35
import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
36
import org.eclipse.jface.text.templates.persistence.TemplateStore;
37
import org.eclipse.jface.util.IPropertyChangeListener;
38
import org.eclipse.jface.util.PropertyChangeEvent;
39
import org.eclipse.jface.viewers.AbstractTreeViewer;
40
import org.eclipse.jface.viewers.ColumnPixelData;
41
import org.eclipse.jface.viewers.DoubleClickEvent;
42
import org.eclipse.jface.viewers.IDoubleClickListener;
43
import org.eclipse.jface.viewers.ISelectionChangedListener;
44
import org.eclipse.jface.viewers.IStructuredSelection;
45
import org.eclipse.jface.viewers.ITableLabelProvider;
46
import org.eclipse.jface.viewers.ITreeContentProvider;
47
import org.eclipse.jface.viewers.LabelProvider;
48
import org.eclipse.jface.viewers.SelectionChangedEvent;
49
import org.eclipse.jface.viewers.StructuredSelection;
50
import org.eclipse.jface.viewers.TreeViewer;
51
import org.eclipse.jface.viewers.Viewer;
52
import org.eclipse.jface.viewers.ViewerComparator;
53
import org.eclipse.swt.SWT;
54
import org.eclipse.swt.custom.CLabel;
55
import org.eclipse.swt.custom.SashForm;
56
import org.eclipse.swt.custom.ViewForm;
57
import org.eclipse.swt.dnd.Clipboard;
58
import org.eclipse.swt.dnd.DND;
59
import org.eclipse.swt.dnd.DragSourceAdapter;
60
import org.eclipse.swt.dnd.DragSourceEvent;
61
import org.eclipse.swt.dnd.DropTargetAdapter;
62
import org.eclipse.swt.dnd.DropTargetEvent;
63
import org.eclipse.swt.dnd.Transfer;
64
import org.eclipse.swt.events.ControlEvent;
65
import org.eclipse.swt.events.ControlListener;
66
import org.eclipse.swt.graphics.GC;
67
import org.eclipse.swt.graphics.Image;
68
import org.eclipse.swt.graphics.Point;
69
import org.eclipse.swt.layout.GridData;
70
import org.eclipse.swt.widgets.Composite;
71
import org.eclipse.swt.widgets.Control;
72
import org.eclipse.swt.widgets.Menu;
73
import org.eclipse.swt.widgets.Shell;
74
import org.eclipse.swt.widgets.Tree;
75
import org.eclipse.swt.widgets.TreeColumn;
76
import org.eclipse.swt.widgets.TreeItem;
77
import org.eclipse.ui.IActionBars;
78
import org.eclipse.ui.IWorkbenchActionConstants;
79
import org.eclipse.ui.IWorkbenchPartSite;
80
import org.eclipse.ui.actions.ActionFactory;
81
import org.eclipse.ui.dialogs.PreferencesUtil;
82
import org.eclipse.ui.dnd.IDragAndDropService;
83
import org.eclipse.ui.internal.texteditor.NLSUtility;
84
import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
85
import org.eclipse.ui.part.Page;
86
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
87
88
import com.ibm.icu.text.Collator;
89
90
/**
91
 * An abstract base class for template pages.
92
 * <p>
93
 * Clients who are defining an editor may elect to provide a corresponding
94
 * templates page. This templates page will be presented to the user via the
95
 * Templates View (the user decides whether their workbench window contains this
96
 * view) whenever that editor is active. This class should be subclassed by
97
 * clients.
98
 * </p>
99
 * <p>
100
 * Internally, a TemplatesPage uses the template store to display different
101
 * categories. A link to editor mode on the templates page allows to filtering
102
 * of the categories to only that are supported in this context.
103
 * </p>
104
 * 
105
 * @since 3.4
106
 */
107
public abstract class TemplatesPage extends Page {
108
109
	/**
110
	 * Sashform size
111
	 */
112
	private static final String SASH_SIZE_PREF_ID = TextEditorPlugin.PLUGIN_ID
113
			+ ".templates.templatesPage.sashSize"; //$NON-NLS-1$
114
	/**
115
	 * Tree columns widths
116
	 */
117
	private static final String COLUMN_NAME_WIDTH_PREF_ID = TextEditorPlugin.PLUGIN_ID
118
			+ ".templates.templatesPage.nameWidth"; //$NON-NLS-1$
119
	private static final String COLUMN_DESCRIPTION_WIDTH_PREF_ID = TextEditorPlugin.PLUGIN_ID
120
			+ ".templates.templatesPage.descriptionWidth"; //$NON-NLS-1$
121
	/**
122
	 * Link to editor action setting
123
	 */
124
	private static final String LINK_ACTION_PREF_ID = TextEditorPlugin.PLUGIN_ID
125
			+ ".templates.templatesPage.linkAction"; //$NON-NLS-1$
126
	
127
	/**
128
	 * Context expand/collapse setting prefix
129
	 */
130
	private static final String CONTEXT_COLLAPSE_PREF_ID = TextEditorPlugin.PLUGIN_ID
131
			+ "templates.templatesPage.context.expand."; //$NON-NLS-1$
132
	
133
	/**
134
	 * The ID for the popup menu for this templates page
135
	 */
136
	private static final String POPUP_MENU_ID = "org.eclipse.ui.texteditor.templates.PopupMenu"; //$NON-NLS-1$
137
138
	/**
139
	 * Default image for a template
140
	 */
141
	private static final Image DEFAULT_TEMPLATE_IMAGE = TemplatesPageImages
142
			.getImage(TemplatesPageImages.IMG_OBJ_TEMPLATE);
143
	/**
144
	 * Image for the context
145
	 */
146
	private static final Image CONTEXT_IMAGE = TemplatesPageImages
147
			.getImage(TemplatesPageImages.IMG_OBJ_CONTEXT);
148
149
	/**
150
	 * Drop support for the editor linked to this page. When a user drops a
151
	 * template into the active editor, the template is applied at the drop
152
	 * position.
153
	 */
154
	private final class EditorDropTarget extends DropTargetAdapter {
155
		/*
156
		 * (non-Javadoc)
157
		 * 
158
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
159
		 */
160
		public void dragEnter(DropTargetEvent event) {
161
			event.detail = DND.DROP_COPY;
162
		}
163
164
		/*
165
		 * (non-Javadoc)
166
		 * 
167
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragOperationChanged(org.eclipse.swt.dnd.DropTargetEvent)
168
		 */
169
		public void dragOperationChanged(DropTargetEvent event) {
170
			event.detail = DND.DROP_COPY;
171
		}
172
173
		/*
174
		 * (non-Javadoc)
175
		 * 
176
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragOver(org.eclipse.swt.dnd.DropTargetEvent)
177
		 */
178
		public void dragOver(DropTargetEvent event) {
179
			event.feedback |= DND.FEEDBACK_SCROLL;
180
			event.detail = DND.DROP_NONE;
181
			TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
182
			if (isEditorModifiable() && selectedTemplates.length == 1
183
					&& isValidTemplateForPosition(selectedTemplates[0].getTemplate(),
184
							new Point(event.x, event.y)))
185
				event.detail = DND.DROP_COPY;
186
		}
187
188
		/*
189
		 * (non-Javadoc)
190
		 * 
191
		 * @see org.eclipse.swt.dnd.DropTargetAdapter#drop(org.eclipse.swt.dnd.DropTargetEvent)
192
		 */
193
		public void drop(DropTargetEvent event) {
194
			TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
195
			insertTemplate(selectedTemplates[0].getTemplate(), new Point(event.x, event.y));
196
			// The highlight of the item is removed once the drop happens - restore it
197
			fTreeViewer.setSelection(new StructuredSelection(selectedTemplates), true);
198
		}
199
	}
200
201
	/**
202
	 * Comparator for the viewer. Sorts the templates by name and then
203
	 * description and context types by names.
204
	 */
205
	private static final class TemplateViewerComparator extends ViewerComparator {
206
		/*
207
		 * (non-Javadoc)
208
		 * 
209
		 * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer,
210
		 *      java.lang.Object, java.lang.Object)
211
		 */
212
		public int compare(Viewer viewer, Object object1, Object object2) {
213
			if ((object1 instanceof TemplatePersistenceData)
214
					&& (object2 instanceof TemplatePersistenceData)) {
215
				Template left = ((TemplatePersistenceData) object1).getTemplate();
216
				Template right = ((TemplatePersistenceData) object2).getTemplate();
217
				int result = Collator.getInstance().compare(left.getName(), right.getName());
218
				if (result != 0)
219
					return result;
220
				return Collator.getInstance().compare(left.getDescription(), right.getDescription());
221
			}
222
			if ((object1 instanceof TemplateContextType)
223
					&& (object2 instanceof TemplateContextType)) {
224
				return Collator.getInstance().compare(((TemplateContextType) object1).getName(), ((TemplateContextType) object1).getName());
225
			}
226
			return super.compare(viewer, object1, object2);
227
		}
228
229
		/*
230
		 * (non-Javadoc)
231
		 * 
232
		 * @see org.eclipse.jface.viewers.ViewerComparator#isSorterProperty(java.lang.Object,
233
		 *      java.lang.String)
234
		 */
235
		public boolean isSorterProperty(Object element, String property) {
236
			return false;
237
		}
238
	}
239
240
	/**
241
	 * Label provider for templates.
242
	 */
243
	private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {
244
		/*
245
		 * (non-Javadoc)
246
		 * 
247
		 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object,
248
		 *      int)
249
		 */
250
		public Image getColumnImage(Object element, int columnIndex) {
251
			if (columnIndex != 0)
252
				return null;
253
			if (element instanceof TemplateContextType)
254
				return CONTEXT_IMAGE;
255
			return getImageForTemplate(((TemplatePersistenceData) element).getTemplate());
256
		}
257
258
		/*
259
		 * (non-Javadoc)
260
		 * 
261
		 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object,
262
		 *      int)
263
		 */
264
		public String getColumnText(Object element, int columnIndex) {
265
			if (element instanceof TemplatePersistenceData)
266
				return getTemplateColumnText((TemplatePersistenceData) element, columnIndex);
267
			return getContextColumnText((TemplateContextType) element, columnIndex);
268
		}
269
270
		private String getTemplateColumnText(TemplatePersistenceData data, int columnIndex) {
271
			switch (columnIndex) {
272
			case 0:
273
				return data.getTemplate().getName();
274
			case 1:
275
				return data.getTemplate().getDescription();
276
			default:
277
				return ""; //$NON-NLS-1$
278
			}
279
		}
280
281
		private String getContextColumnText(TemplateContextType contextType, int columnIndex) {
282
			switch (columnIndex) {
283
			case 0:
284
				return contextType.getName();
285
			default:
286
				return ""; //$NON-NLS-1$
287
			}
288
		}
289
	}
290
291
	/**
292
	 * Content provider for templates. Provides all the enabled templates
293
	 * defined for this editor.
294
	 */
295
	private class TemplatesContentProvider implements ITreeContentProvider {
296
		/*
297
		 * (non-Javadoc)
298
		 * 
299
		 * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
300
		 */
301
		public Object[] getChildren(Object parentElement) {
302
			if (parentElement instanceof TemplatePersistenceData)
303
				return new Object[0];
304
			else if (parentElement instanceof TemplateContextType) {
305
				TemplateContextType contextType = (TemplateContextType) parentElement;
306
				return getTemplates(contextType.getId());
307
			}
308
			return null;
309
		}
310
311
		private TemplatePersistenceData[] getTemplates(String contextId) {
312
			List templateList = new ArrayList();
313
			TemplatePersistenceData[] datas = getTemplateStore().getTemplateData(false);
314
			for (int i = 0; i < datas.length; i++) {
315
				if (datas[i].isEnabled()
316
						&& datas[i].getTemplate().getContextTypeId().equals(contextId))
317
					templateList.add(datas[i]);
318
			}
319
			return (TemplatePersistenceData[]) templateList
320
					.toArray(new TemplatePersistenceData[templateList.size()]);
321
		}
322
323
		/*
324
		 * (non-Javadoc)
325
		 * 
326
		 * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
327
		 */
328
		public Object getParent(Object element) {
329
			if (element instanceof TemplatePersistenceData) {
330
				TemplatePersistenceData templateData = (TemplatePersistenceData) element;
331
				return getContextTypeRegistry().getContextType(
332
						templateData.getTemplate().getContextTypeId());
333
			}
334
			return null;
335
		}
336
337
		/*
338
		 * (non-Javadoc)
339
		 * 
340
		 * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
341
		 */
342
		public boolean hasChildren(Object element) {
343
			if (element instanceof TemplateContextType)
344
				return true;
345
			return false;
346
		}
347
348
		/*
349
		 * (non-Javadoc)
350
		 * 
351
		 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
352
		 */
353
		public Object[] getElements(Object inputElement) {
354
			List contextTypes = new ArrayList();
355
356
			for (Iterator iterator = getContextTypeRegistry().contextTypes(); iterator.hasNext();) {
357
				TemplateContextType contextType = (TemplateContextType) iterator.next();
358
				if (!fLinkWithEditorAction.isChecked() || isActiveContext(contextType))
359
					contextTypes.add(contextType);
360
			}
361
			return contextTypes.toArray(new TemplateContextType[contextTypes.size()]);
362
		}
363
364
		private boolean isActiveContext(TemplateContextType contextType) {
365
			return fActiveTypes == null || fActiveTypes.contains(contextType.getId());
366
		}
367
368
		/*
369
		 * (non-Javadoc)
370
		 * 
371
		 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
372
		 */
373
		public void dispose() {
374
		}
375
376
		/*
377
		 * (non-Javadoc)
378
		 * 
379
		 * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
380
		 *      java.lang.Object, java.lang.Object)
381
		 */
382
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
383
		}
384
	}
385
386
	/**
387
	 * Listener to monitor changes to template store
388
	 */
389
	private IPropertyChangeListener fTemplateChangeListener;
390
391
	/**
392
	 * Control for this pagebook view
393
	 */
394
	private SashForm fControl;
395
396
	/* Actions */
397
	private Action fInsertAction;
398
	private Action fAddAction;
399
	private Action fEditAction;
400
	private Action fRemoveAction;
401
	private Action fLinkWithEditorAction;
402
	private Action fCollapseAllAction;
403
	private Action fPreferencePageAction;
404
405
	/* Clipboard actions */
406
	private Action fPasteAction;
407
	private Action fCopyAction;
408
409
	/** Current active context types for the editor */
410
	private List fActiveTypes;
411
412
	/* Preference stores */
413
	/**
414
	 * Preference store to store the dialog setting for this page
415
	 */
416
	private IPreferenceStore fPreferenceStore;
417
418
	/* Controls */
419
	private Tree fTemplatesTree;
420
	private TreeViewer fTreeViewer;
421
	private Menu fContextMenu;
422
	
423
	/** Current selection */
424
	private TemplatePersistenceData[] fSelectedTemplates = new TemplatePersistenceData[0];
425
	protected HashMap fContextStateMap = new HashMap();
426
427
	/**
428
	 * Creates a new template view page.
429
	 */
430
	protected TemplatesPage() {
431
		super();
432
		setupPreferenceStore();
433
	}
434
435
	/*
436
	 * (non-Javadoc)
437
	 * 
438
	 * @see org.eclipse.ui.part.Page#createControl(org.eclipse.swt.widgets.Composite)
439
	 */
440
	public void createControl(Composite ancestor) {
441
		setupActions();
442
443
		fControl = new SashForm(ancestor, SWT.VERTICAL);
444
445
		createTemplateTree(fControl);
446
		createPatternForm(fControl);
447
448
		hookContextMenu();
449
		initializeDND();
450
		updateButtons();
451
452
		int sashSize = fPreferenceStore.getInt(SASH_SIZE_PREF_ID);
453
		fControl.setWeights(new int[] { sashSize, 100 - sashSize });
454
		fTemplateChangeListener = new IPropertyChangeListener() {
455
			public void propertyChange(PropertyChangeEvent event) {
456
				getShell().getDisplay().asyncExec(new Runnable() {
457
					public void run() {
458
						refresh();
459
					}
460
				});
461
			}
462
		};
463
		getTemplatePreferenceStore().addPropertyChangeListener(fTemplateChangeListener);
464
	}
465
466
	/*
467
	 * (non-Javadoc)
468
	 * 
469
	 * @see org.eclipse.ui.part.Page#setFocus()
470
	 */
471
	public void setFocus() {
472
	}
473
474
	/*
475
	 * (non-Javadoc)
476
	 * 
477
	 * @see org.eclipse.ui.part.Page#getControl()
478
	 */
479
	public Control getControl() {
480
		return fControl;
481
	}
482
483
	/*
484
	 * (non-Javadoc)
485
	 * 
486
	 * @see org.eclipse.ui.part.Page#dispose()
487
	 */
488
	public void dispose() {
489
		if (fContextMenu != null && !fContextMenu.isDisposed())
490
			fContextMenu.dispose();
491
		if (fTemplateChangeListener != null)
492
			getTemplatePreferenceStore().removePropertyChangeListener(fTemplateChangeListener);
493
		super.dispose();
494
	}
495
496
	/**
497
	 * Get the shell
498
	 * 
499
	 * @return the shell for this view site
500
	 */
501
	protected Shell getShell() {
502
		return getSite().getShell();
503
	}
504
505
	/**
506
	 * The caret position in the editor has moved into a new context type. It is
507
	 * the subclasses responsibility to see that this is called only when needed
508
	 * by keeping track of editor contents (eg. partitions).
509
	 * 
510
	 * @param ids
511
	 */
512
	protected final void updateContextTypes(String[] ids) {
513
		fActiveTypes = Arrays.asList(ids);
514
		if (fLinkWithEditorAction != null && fLinkWithEditorAction.isChecked())
515
			refresh();
516
	}
517
518
	/**
519
	 * Setup the editor site as a drop target. Should be invoked by the
520
	 * subclasses for the D&D to work with the editor.
521
	 * 
522
	 * @param site
523
	 * @param viewer
524
	 */
525
	protected void setupEditorDropTarget(IWorkbenchPartSite site, Control viewer) {
526
		IDragAndDropService dndService = (IDragAndDropService) site
527
				.getService(IDragAndDropService.class);
528
		EditorDropTarget editorDropTarget = new EditorDropTarget();
529
		dndService.addMergedDropTarget(viewer, DND.DROP_COPY, new Transfer[] { TemplateTransfer
530
				.getInstance() }, editorDropTarget);
531
	}
532
533
	/**
534
	 * Convert the clipboard contents into a template
535
	 * 
536
	 * @param clipBoard
537
	 * @return the template or null if contents are not valid
538
	 */
539
	protected Template getTemplateFromClipboard(Clipboard clipBoard) {
540
		TemplatePersistenceData[] contents = (TemplatePersistenceData[]) clipBoard.getContents(TemplateTransfer.getInstance());
541
		if (contents != null) {
542
			Template template = contents[0].getTemplate();
543
			return new Template(template.getName(), template.getDescription(),
544
					getContextTypeId(), template.getPattern(), true);
545
		}
546
		return null;
547
	}
548
549
	/**
550
	 * Get the image to be used for the given template. Clients can override to
551
	 * provide a different image.
552
	 * 
553
	 * @param template
554
	 * @return handle to the image
555
	 */
556
	protected Image getImageForTemplate(Template template) {
557
		return DEFAULT_TEMPLATE_IMAGE;
558
	}
559
560
	/**
561
	 * Subclasses should override and facilitate inserting the template code
562
	 * into the active editor.
563
	 * 
564
	 * @param template
565
	 * @param position
566
	 */
567
	abstract protected void insertTemplate(Template template, Point position);
568
569
	/**
570
	 * Get the context type registry for the associated editor.
571
	 * 
572
	 * @return the contextTypeRegistry
573
	 */
574
	abstract protected ContextTypeRegistry getContextTypeRegistry();
575
576
	/**
577
	 * Get the template store for the associated editor
578
	 * 
579
	 * @return the template store
580
	 */
581
	abstract protected TemplateStore getTemplateStore();
582
583
	/**
584
	 * Get the preference store used to create the template store returned by
585
	 * {@link TemplatesPage#getTemplateStore()}.
586
	 * 
587
	 * @return the preference store
588
	 */
589
	abstract protected IPreferenceStore getTemplatePreferenceStore();
590
591
	/**
592
	 * Check whether the template is valid for the given drop position
593
	 * 
594
	 * @param template
595
	 * @param position
596
	 * @return true if the template is valid
597
	 */
598
	abstract protected boolean isValidTemplateForPosition(Template template, Point position);
599
600
	/**
601
	 * Check whether the linked editor is modifiable
602
	 * 
603
	 * @return true if the editor is modifiable
604
	 */
605
	abstract protected boolean isEditorModifiable();
606
607
	/**
608
	 * Get the pattern data from the clipboard. This data will be stored for the
609
	 * template.
610
	 * 
611
	 * @param clipBoard
612
	 * @return pattern data or null if the clipboard does not have valid content
613
	 */
614
	abstract protected String getTemplateDataFromClipboard(Clipboard clipBoard);
615
616
	/**
617
	 * Get the preference page ID for the templates for the given editor.
618
	 * 
619
	 * @return id of the preference page, null if none exists
620
	 */
621
	abstract protected String getPreferencePageId();
622
623
	/**
624
	 * Creates the edit dialog. Subclasses may override this method to provide a
625
	 * custom dialog.
626
	 * 
627
	 * @param template
628
	 *            the template being edited
629
	 * @param edit
630
	 *            whether the dialog should be editable
631
	 * @param isNameModifiable
632
	 *            whether the template name may be modified
633
	 * @return the created or modified template, or <code>null</code> if the
634
	 *         editing failed
635
	 */
636
	abstract protected Template editTemplate(Template template, boolean edit,
637
			boolean isNameModifiable);
638
639
	/**
640
	 * Get the pattern viewer.
641
	 * 
642
	 * @param parent
643
	 * @return the viewer
644
	 */
645
	abstract protected Viewer createPatternViewer(Composite parent);
646
647
	/**
648
	 * Get the transfers supported by this editor.
649
	 * 
650
	 * @return array of transfers supported
651
	 */
652
	abstract protected Transfer[] getTransfers();
653
654
	/**
655
	 * Create the template pattern from a DnD operation.
656
	 * 
657
	 * @param transfer
658
	 * @param data
659
	 * @return pattern or null if the transfer is not supported
660
	 */
661
	abstract protected String getTemplateDataFromDrop(Transfer transfer, Object data);
662
663
	/**
664
	 * Update the pattern viewer to show the current template.
665
	 * 
666
	 * @param template
667
	 */
668
	abstract protected void updatePatternViewer(Template template);
669
670
	/**
671
	 * Setup the preference store
672
	 */
673
	private void setupPreferenceStore() {
674
		fPreferenceStore = TextEditorPlugin.getDefault().getPreferenceStore();
675
		fPreferenceStore.setDefault(LINK_ACTION_PREF_ID, true);
676
		fPreferenceStore.setDefault(SASH_SIZE_PREF_ID, 80);
677
	}
678
679
	/**
680
	 * Setup the menu, context menu and toolbar actions.
681
	 */
682
	private void setupActions() {
683
		createActions();
684
		IActionBars actionBars = getSite().getActionBars();
685
686
		actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(), fPasteAction);
687
		fPasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
688
		fPasteAction.setText(TemplatesPageMessages.TemplatesPage_paste);
689
		actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), fCopyAction);
690
		fCopyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
691
		fCopyAction.setText(TemplatesPageMessages.TemplatesPage_copy);
692
		fillToolbar(actionBars);
693
		fillMenu(actionBars);
694
	}
695
696
	/**
697
	 * Create all the actions
698
	 */
699
	private void createActions() {
700
		fInsertAction = new Action(TemplatesPageMessages.TemplatesPage_insert) {
701
			public void run() {
702
				TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
703
				insertTemplate(selectedTemplates[0].getTemplate(), null);
704
			}
705
		};
706
		fInsertAction.setImageDescriptor(TemplatesPageImages
707
				.getImageDescriptor(TemplatesPageImages.IMG_ELCL_TEMPLATE_INSERT));
708
		fInsertAction.setDisabledImageDescriptor(TemplatesPageImages
709
				.getImageDescriptor(TemplatesPageImages.IMG_DLCL_TEMPLATE_INSERT));
710
		fInsertAction.setToolTipText(TemplatesPageMessages.TemplatesPage_insert_tooltip);
711
712
		fAddAction = new Action(TemplatesPageMessages.TemplatesPage_new) {
713
			public void run() {
714
				addTemplate();
715
			}
716
		};
717
		fAddAction.setImageDescriptor(TemplatesPageImages
718
				.getImageDescriptor(TemplatesPageImages.IMG_ELCL_TEMPLATE_NEW));
719
		fAddAction.setToolTipText(TemplatesPageMessages.TemplatesPage_new_tooltip);
720
721
		fEditAction = new Action(TemplatesPageMessages.TemplatesPage_edit) {
722
			public void run() {
723
				editTemplate();
724
			}
725
		};
726
		fEditAction.setImageDescriptor(TemplatesPageImages
727
				.getImageDescriptor(TemplatesPageImages.IMG_ELCL_TEMPLATE_EDIT));
728
		fEditAction.setDisabledImageDescriptor(TemplatesPageImages
729
				.getImageDescriptor(TemplatesPageImages.IMG_DLCL_TEMPLATE_EDIT));
730
		fEditAction.setToolTipText(TemplatesPageMessages.TemplatesPage_edit_tooltip);
731
732
		fRemoveAction = new Action(TemplatesPageMessages.TemplatesPage_remove) {
733
			public void run() {
734
				removeTemplates();
735
			}
736
		};
737
		fRemoveAction.setImageDescriptor(TemplatesPageImages
738
				.getImageDescriptor(TemplatesPageImages.IMG_DLCL_TEMPLATE_DELETE));
739
		fRemoveAction.setImageDescriptor(TemplatesPageImages
740
				.getImageDescriptor(TemplatesPageImages.IMG_ELCL_TEMPLATE_DELETE));
741
		fRemoveAction.setToolTipText(TemplatesPageMessages.TemplatesPage_remove_tooltip);
742
743
		fLinkWithEditorAction = new Action(TemplatesPageMessages.TemplatesPage_link_to_editor,
744
				IAction.AS_CHECK_BOX) {
745
			public void run() {
746
				fPreferenceStore.setValue(LINK_ACTION_PREF_ID, fLinkWithEditorAction.isChecked());
747
				refresh();
748
			}
749
		};
750
		fLinkWithEditorAction.setImageDescriptor(TemplatesPageImages
751
				.getImageDescriptor(TemplatesPageImages.IMG_ELCL_TEMPLATE_LINK));
752
		fLinkWithEditorAction.setChecked(fPreferenceStore.getBoolean(LINK_ACTION_PREF_ID));
753
		fLinkWithEditorAction
754
				.setToolTipText(TemplatesPageMessages.TemplatesPage_link_to_editor_tooltip);
755
		fCollapseAllAction = new Action(TemplatesPageMessages.TemplatesPage_collapse_all) {
756
			public void run() {
757
				fTreeViewer.collapseAll();
758
			}
759
		};
760
		fCollapseAllAction.setImageDescriptor(TemplatesPageImages
761
				.getImageDescriptor(TemplatesPageImages.IMG_ELCL_TEMPLATE_COLLAPSE_ALL));
762
		fCollapseAllAction
763
				.setToolTipText(TemplatesPageMessages.TemplatesPage_collapse_all_tooltip);
764
765
		if (getPreferencePageId() != null) {
766
			fPreferencePageAction = new Action(
767
					TemplatesPageMessages.TemplatesPage_preference_page) {
768
				public void run() {
769
					showPreferencePage();
770
				}
771
			};
772
			fPreferencePageAction
773
					.setToolTipText(TemplatesPageMessages.TemplatesPage_preference_page_tooltip);
774
		}
775
776
		fPasteAction = new Action() {
777
			public void run() {
778
				final Template template = readClipboardContents();
779
				if (template != null)
780
					getShell().getDisplay().asyncExec(new Runnable() {
781
						public void run() {
782
							addTemplate(template);
783
						}
784
					});
785
			}
786
787
			private Template readClipboardContents() {
788
				Clipboard clipBoard = new Clipboard(getShell().getDisplay());
789
				String pattern = getTemplateDataFromClipboard(clipBoard);
790
				if (pattern != null)
791
					return new Template(createTemplateName(),
792
							TemplatesPageMessages.TemplatesPage_paste_description,
793
							getContextTypeId(), pattern, true);
794
				return getTemplateFromClipboard(clipBoard);
795
			}
796
		};
797
798
		fCopyAction = new Action() {
799
			public void run() {
800
				Clipboard clipBoard = new Clipboard(getShell().getDisplay());
801
				clipBoard.setContents(new Object[] { getSelectedTemplates() }, new Transfer[] { TemplateTransfer
802
						.getInstance() });
803
			}
804
		};
805
	}
806
807
	/**
808
	 * Fill the view menu
809
	 * 
810
	 * @param actionBars
811
	 */
812
	private void fillMenu(IActionBars actionBars) {
813
		IMenuManager menuManager = actionBars.getMenuManager();
814
815
		if (fPreferencePageAction != null) {
816
			menuManager.add(fPreferencePageAction);
817
			menuManager.add(new Separator());
818
		}
819
820
		menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
821
	}
822
823
	/**
824
	 * Fill the toolbar
825
	 * 
826
	 * @param actionBars
827
	 */
828
	private void fillToolbar(IActionBars actionBars) {
829
		IToolBarManager toolBarManager = actionBars.getToolBarManager();
830
		toolBarManager.add(fInsertAction);
831
		toolBarManager.add(fAddAction);
832
		toolBarManager.add(fEditAction);
833
		toolBarManager.add(fRemoveAction);
834
835
		toolBarManager.add(new Separator());
836
837
		toolBarManager.add(fLinkWithEditorAction);
838
		toolBarManager.add(fCollapseAllAction);
839
	}
840
841
	/**
842
	 * Hookup the context menu
843
	 */
844
	private void hookContextMenu() {
845
		MenuManager menuMgr = new MenuManager(POPUP_MENU_ID);
846
		menuMgr.setRemoveAllWhenShown(true);
847
		menuMgr.addMenuListener(new IMenuListener() {
848
			public void menuAboutToShow(IMenuManager manager) {
849
				fillContextMenu(manager);
850
			}
851
		});
852
		fContextMenu = menuMgr.createContextMenu(fTreeViewer.getControl());
853
		fTreeViewer.getControl().setMenu(fContextMenu);
854
		getSite().registerContextMenu(POPUP_MENU_ID, menuMgr, fTreeViewer);
855
	}
856
857
	/**
858
	 * Fill the context menu items
859
	 * 
860
	 * @param manager
861
	 */
862
	private void fillContextMenu(IMenuManager manager) {
863
		manager.add(fInsertAction);
864
		manager.add(new Separator());
865
		manager.add(fAddAction);
866
		manager.add(fEditAction);
867
		manager.add(fRemoveAction);
868
		manager.add(new Separator());
869
		manager.add(fCopyAction);
870
		manager.add(fPasteAction);
871
		// Other plug-ins can contribute there actions here
872
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
873
	}
874
875
	/**
876
	 * Create the tree to display templates
877
	 * @param parent 
878
	 */
879
	private void createTemplateTree(Composite parent) {
880
		Composite treeComposite = new Composite(parent, SWT.NONE);
881
		GridData data = new GridData(GridData.FILL_BOTH);
882
		treeComposite.setLayoutData(data);
883
884
		TreeColumnLayout columnLayout = new TreeColumnLayout();
885
		treeComposite.setLayout(columnLayout);
886
		fTemplatesTree = new Tree(treeComposite, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI
887
				| SWT.FULL_SELECTION);
888
		fTemplatesTree.setHeaderVisible(true);
889
		fTemplatesTree.setLinesVisible(true);
890
		GC gc = new GC(getShell());
891
		gc.setFont(JFaceResources.getDialogFont());
892
893
		TreeColumn columnName = new TreeColumn(fTemplatesTree, SWT.NONE);
894
		columnName.setText(TemplatesPageMessages.TemplatesPage_column_name);
895
		int minWidth = fPreferenceStore.getInt(COLUMN_NAME_WIDTH_PREF_ID);
896
		if (minWidth == 0)
897
			minWidth = gc.stringExtent("XXXXXXXXXXXXXXX").x; //$NON-NLS-1$
898
		columnLayout.setColumnData(columnName, new ColumnPixelData(minWidth, true));
899
		columnName.addControlListener(new ControlListener() {
900
			public void controlMoved(ControlEvent e) {
901
			}
902
903
			public void controlResized(ControlEvent e) {
904
				int nameWidth = ((TreeColumn) e.getSource()).getWidth();
905
				fPreferenceStore.setValue(COLUMN_NAME_WIDTH_PREF_ID, nameWidth);
906
			}
907
		});
908
909
		TreeColumn columnDescription = new TreeColumn(fTemplatesTree, SWT.NONE);
910
		columnDescription.setText(TemplatesPageMessages.TemplatesPage_column_description);
911
		minWidth = fPreferenceStore.getInt(COLUMN_DESCRIPTION_WIDTH_PREF_ID);
912
		if (minWidth == 0)
913
			minWidth = gc.stringExtent("XXXXXXXXXXXXXXXXXXXXXXXXX").x; //$NON-NLS-1$
914
		columnLayout.setColumnData(columnDescription, new ColumnPixelData(minWidth, false));
915
		columnDescription.addControlListener(new ControlListener() {
916
			public void controlMoved(ControlEvent e) {
917
			}
918
919
			public void controlResized(ControlEvent e) {
920
				int descriptionWidth = ((TreeColumn) e.getSource()).getWidth();
921
				fPreferenceStore.setValue(COLUMN_DESCRIPTION_WIDTH_PREF_ID, descriptionWidth);
922
			}
923
		});
924
925
		gc.dispose();
926
927
		createTreeViewer(fTemplatesTree);
928
	}
929
930
	/**
931
	 * Create the tree viewer and setup the providers
932
	 * @param templatesTree 
933
	 */
934
	private void createTreeViewer(Tree templatesTree) {
935
		fTreeViewer = new TreeViewer(fTemplatesTree);
936
		fTreeViewer.setLabelProvider(new TemplateLabelProvider());
937
		fTreeViewer.setContentProvider(new TemplatesContentProvider());
938
939
		fTreeViewer.setComparator(new TemplateViewerComparator());
940
		fTreeViewer.setInput(getTemplatePreferenceStore());
941
		fTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
942
			public void doubleClick(DoubleClickEvent e) {
943
				updateSelectedItems();
944
				TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
945
				insertTemplate(selectedTemplates[0].getTemplate(), null);
946
			}
947
		});
948
949
		fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
950
			public void selectionChanged(SelectionChangedEvent e) {
951
				updateSelectedItems();
952
				updateButtons();
953
			}
954
		});
955
		fTreeViewer.expandAll();
956
	}
957
958
	/**
959
	 * Setup the pattern viewer
960
	 * 
961
	 * @param parent
962
	 */
963
	private void createPatternForm(Composite parent) {
964
		ViewForm viewForm = new ViewForm(parent, SWT.NONE);
965
		viewForm.setBorderVisible(false);
966
		CLabel previewLabel = new CLabel(viewForm, SWT.NONE);
967
		previewLabel.setText(TemplatesPageMessages.TemplatesPage_preview);
968
		previewLabel.setImage(TemplatesPageImages.getImage(TemplatesPageImages.IMG_OBJ_PREVIEW));
969
		viewForm.setTopLeft(previewLabel);
970
971
		Viewer viewer = createPatternViewer(viewForm);
972
		viewForm.setContent(viewer.getControl());
973
		viewForm.addControlListener(new ControlListener() {
974
			public void controlMoved(ControlEvent e) {
975
			}
976
977
			public void controlResized(ControlEvent e) {
978
				int[] weights = fControl.getWeights();
979
				int sashSize = (int) (weights[0] * 100.0 / (weights[0] + weights[1]));
980
				fPreferenceStore.setValue(SASH_SIZE_PREF_ID, sashSize);
981
			}
982
		});
983
	}
984
985
	/**
986
	 * Update the selected items.
987
	 */
988
	private void updateSelectedItems() {
989
		setSelectedTemplates();
990
		TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
991
992
		if (selectedTemplates.length == 1)
993
			updatePatternViewer(selectedTemplates[0].getTemplate());
994
		else
995
			updatePatternViewer(null);
996
	}
997
998
	/**
999
	 * Show the preference page. The action is enabled only if
1000
	 * getPreferencePageId() returns non-null.
1001
	 */
1002
	private void showPreferencePage() {
1003
		PreferencesUtil.createPreferenceDialogOn(getShell(), getPreferencePageId(), null, null)
1004
				.open();
1005
	}
1006
1007
	/**
1008
	 * Update the state of the buttons
1009
	 */
1010
	private void updateButtons() {
1011
		TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
1012
		fCopyAction.setEnabled(selectedTemplates.length > 0);
1013
		fInsertAction.setEnabled(selectedTemplates.length == 1);
1014
		fEditAction.setEnabled(selectedTemplates.length == 1);
1015
		fRemoveAction.setEnabled(selectedTemplates.length > 0);
1016
	}
1017
1018
	/**
1019
	 * Set the selected templates
1020
	 */
1021
	private void setSelectedTemplates() {
1022
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
1023
1024
		Iterator it = selection.iterator();
1025
		TemplatePersistenceData[] data = new TemplatePersistenceData[selection.size()];
1026
		int i = 0 ;
1027
		try {
1028
			while (it.hasNext()) {
1029
				data[i++] = (TemplatePersistenceData) it.next();
1030
			}
1031
			fSelectedTemplates = data;
1032
		} catch (ClassCastException e) {
1033
			// A context also must have been selected - ignore the selection
1034
			fSelectedTemplates  = new TemplatePersistenceData[0];
1035
		}
1036
	}
1037
1038
	/**
1039
	 * Get the currently selected templates
1040
	 * 
1041
	 * @return selected tempaltes
1042
	 */
1043
	private TemplatePersistenceData[] getSelectedTemplates() {
1044
		return fSelectedTemplates ;
1045
	}
1046
	
1047
	/**
1048
	 * Add a template
1049
	 */
1050
	private void addTemplate() {
1051
		String id = getContextTypeId();
1052
		if (id != null) {
1053
			Template template = new Template("", "", id, "", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1054
1055
			addTemplate(template);
1056
		}
1057
	}
1058
1059
	/**
1060
	 * Get contextType of the selected template
1061
	 * 
1062
	 * @return contextType of the selected template or the first from the
1063
	 *         registry if no templates are selected
1064
	 */
1065
	private String getContextTypeId() {
1066
		IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
1067
		Object item ;
1068
1069
		if (selection.size() == 0)
1070
			return ((TemplateContextType) getContextTypeRegistry().contextTypes().next()).getId();
1071
1072
		if (selection.size() == 1) {
1073
			item = selection.getFirstElement();
1074
			if (item instanceof TemplatePersistenceData)
1075
				return ((TemplatePersistenceData)item).getTemplate().getContextTypeId() ;
1076
			return ((TemplateContextType)item).getId();
1077
		}
1078
		Iterator it = selection.iterator();
1079
		String contextId = null ;
1080
		while (it.hasNext()) {
1081
			item = it.next();
1082
			if (contextId == null)
1083
				contextId = getContextId(item);
1084
			else if (!contextId.equals(getContextId(item)))
1085
				return ((TemplateContextType) getContextTypeRegistry().contextTypes().next()).getId();
1086
		}
1087
		return contextId;
1088
	}
1089
1090
	private String getContextId(Object item) {
1091
		String contextId;
1092
		if (item instanceof TemplatePersistenceData)
1093
			contextId = ((TemplatePersistenceData)item).getTemplate().getContextTypeId();
1094
		else
1095
			contextId = ((TemplateContextType)item).getId();
1096
		return contextId;
1097
	}
1098
1099
	/**
1100
	 * Add a template. The dialog is filled with the values from the given
1101
	 * template.
1102
	 * 
1103
	 * @param template
1104
	 */
1105
	private void addTemplate(Template template) {
1106
		Template newTemplate;
1107
		newTemplate = editTemplate(template, false, true);
1108
		if (newTemplate != null) {
1109
			TemplatePersistenceData data = new TemplatePersistenceData(newTemplate, true);
1110
			getTemplateStore().add(data);
1111
			saveTemplateStore();
1112
			refresh();
1113
			fTreeViewer.setSelection(new StructuredSelection(data), true);
1114
		}
1115
	}
1116
1117
	/**
1118
	 * Save the template store
1119
	 */
1120
	private void saveTemplateStore() {
1121
		try {
1122
			getTemplateStore().save();
1123
		} catch (IOException e) {
1124
			e.printStackTrace();
1125
			MessageDialog.openError(getShell(),
1126
					TemplatesPageMessages.TemplatesPage_save_error_message, e.getMessage());
1127
		}
1128
	}
1129
1130
	/**
1131
	 * Edit the selected template
1132
	 */
1133
	private void editTemplate() {
1134
		Template oldTemplate = getSelectedTemplates()[0].getTemplate();
1135
		Template newTemplate = editTemplate(new Template(oldTemplate), true, true);
1136
		if (newTemplate != null) {
1137
			if (!newTemplate.getName().equals(oldTemplate.getName())
1138
					&& MessageDialog.openQuestion(getShell(),
1139
							TemplatesPageMessages.TemplatesPage_question_create_new_title,
1140
							TemplatesPageMessages.TemplatesPage_question_create_new_message)) {
1141
				TemplatePersistenceData templateData = new TemplatePersistenceData(newTemplate,
1142
						true);
1143
				getTemplateStore().add(templateData);
1144
				refresh();
1145
				fTreeViewer.setSelection(new StructuredSelection(templateData), true);
1146
			} else {
1147
				getSelectedTemplates()[0].setTemplate(newTemplate);
1148
			}
1149
		}
1150
		saveTemplateStore();
1151
	}
1152
1153
	/**
1154
	 * Move the selected template from one context to another
1155
	 * @param templates 
1156
	 * @param contextId 
1157
	 * 
1158
	 */
1159
	private void moveTemplates(TemplatePersistenceData[] templates, String contextId) {
1160
		for (int i = 0; i < templates.length; i++) {
1161
			Template t = templates[i].getTemplate();
1162
			templates[i].setTemplate(new Template(t.getName(), t.getDescription(), contextId, t.getPattern(), t.isAutoInsertable()));
1163
		}
1164
		saveTemplateStore();
1165
		fTreeViewer.setSelection(new StructuredSelection(templates), true);
1166
	}
1167
1168
	/**
1169
	 * Copy the selected templates to another context
1170
	 * @param templates 
1171
	 * @param contextId 
1172
	 * 
1173
	 */
1174
	private void copyTemplates(TemplatePersistenceData[] templates, String contextId) {
1175
		TemplatePersistenceData[] newTemplates = new TemplatePersistenceData[templates.length];
1176
		for (int i = 0; i < templates.length; i++) {
1177
			Template t = templates[i].getTemplate();
1178
			newTemplates[i] = new TemplatePersistenceData(new Template(t.getName(), t.getDescription(), contextId, t.getPattern(), t.isAutoInsertable()), true);
1179
			getTemplateStore().add(newTemplates[i]);
1180
		}
1181
		saveTemplateStore();
1182
		refresh();
1183
		fTreeViewer.setSelection(new StructuredSelection(newTemplates), true);
1184
	}
1185
1186
	/**
1187
	 * Remove one or more selected templates
1188
	 */
1189
	private void removeTemplates() {
1190
		String title ;
1191
		TemplatePersistenceData[] selectedTemplates = getSelectedTemplates();
1192
		if (selectedTemplates.length == 1)
1193
			title = TemplatesPageMessages.TemplatesPage_remove_title_single;
1194
		else
1195
			title = TemplatesPageMessages.TemplatesPage_remove_title_multi;
1196
		String message ;
1197
		if (selectedTemplates.length == 1)
1198
			message = TemplatesPageMessages.TemplatesPage_remove_message_single ;
1199
		else
1200
			message = NLSUtility.format(TemplatesPageMessages.TemplatesPage_remove_message_multi,
1201
				new Object[] { new Integer(selectedTemplates.length) });
1202
		if (!MessageDialog.openQuestion(getShell(), title, message))
1203
			return;
1204
		for (int i = 0; i < selectedTemplates.length; i++) {
1205
			getTemplateStore().delete(selectedTemplates[i]);
1206
		}
1207
		saveTemplateStore();
1208
		fTreeViewer.setSelection(new StructuredSelection(new Object[] {}), true);
1209
	}
1210
1211
	/**
1212
	 * Initialize drag and drop the template items
1213
	 */
1214
	private void initializeDND() {
1215
		DragSourceAdapter dragListener = new DragSourceAdapter() {
1216
			/*
1217
			 * (non-Javadoc)
1218
			 * 
1219
			 * @see org.eclipse.swt.dnd.DragSourceAdapter#dragStart(org.eclipse.swt.dnd.DragSourceEvent)
1220
			 */
1221
			public void dragStart(DragSourceEvent event) {
1222
				if (getSelectedTemplates().length == 0) {
1223
					event.doit = false;
1224
				}
1225
			}
1226
1227
			/*
1228
			 * (non-Javadoc)
1229
			 * 
1230
			 * @see org.eclipse.swt.dnd.DragSourceAdapter#dragSetData(org.eclipse.swt.dnd.DragSourceEvent)
1231
			 */
1232
			public void dragSetData(DragSourceEvent event) {
1233
				if (TemplateTransfer.getInstance().isSupportedType(event.dataType)) {
1234
					event.data = getSelectedTemplates() ;
1235
				}
1236
			}
1237
		};
1238
		fTreeViewer.addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] { TemplateTransfer
1239
				.getInstance() }, dragListener);
1240
		DropTargetAdapter dropListener = new DropTargetAdapter() {
1241
			Transfer[] transfers = getTransfers();
1242
			TemplateTransfer templateTransfer = TemplateTransfer.getInstance();
1243
1244
			/*
1245
			 * (non-Javadoc)
1246
			 * 
1247
			 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
1248
			 */
1249
			public void dragEnter(DropTargetEvent event) {
1250
				if (event.detail == DND.DROP_DEFAULT)
1251
					event.detail = DND.DROP_COPY;
1252
			}
1253
1254
			/*
1255
			 * (non-Javadoc)
1256
			 * 
1257
			 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragOperationChanged(org.eclipse.swt.dnd.DropTargetEvent)
1258
			 */
1259
			public void dragOperationChanged(DropTargetEvent event) {
1260
				if (event.detail == DND.DROP_DEFAULT)
1261
					event.detail = DND.DROP_COPY;
1262
			}
1263
1264
			/*
1265
			 * (non-Javadoc)
1266
			 * 
1267
			 * @see org.eclipse.swt.dnd.DropTargetAdapter#dragOver(org.eclipse.swt.dnd.DropTargetEvent)
1268
			 */
1269
			public void dragOver(DropTargetEvent event) {
1270
				event.feedback |= DND.FEEDBACK_SCROLL;
1271
				if (event.item == null) {
1272
					event.detail = DND.DROP_NONE;
1273
					return;
1274
				}
1275
				int index = 0;
1276
				boolean isTemplateTransfer = false;
1277
				while (index < event.dataTypes.length) {
1278
					int i = 0;
1279
					while (i < transfers.length) {
1280
						if (transfers[i].isSupportedType(event.dataTypes[index]))
1281
							break;
1282
						i++;
1283
					}
1284
					if (i < transfers.length)
1285
						break;
1286
					if (templateTransfer.isSupportedType(event.dataTypes[index])) {
1287
						isTemplateTransfer = true;
1288
						break;
1289
					}
1290
					index++;
1291
				}
1292
				if (index < event.dataTypes.length) {
1293
					event.currentDataType = event.dataTypes[index];
1294
					if (event.detail == DND.DROP_DEFAULT || !isTemplateTransfer)
1295
						event.detail = DND.DROP_COPY;
1296
					return;
1297
				}
1298
			}
1299
1300
			/*
1301
			 * (non-Javadoc)
1302
			 * 
1303
			 * @see org.eclipse.swt.dnd.DropTargetAdapter#drop(org.eclipse.swt.dnd.DropTargetEvent)
1304
			 */
1305
			public void drop(DropTargetEvent event) {
1306
				if (event.item == null)
1307
					return;
1308
				Object object = ((TreeItem) event.item).getData();
1309
				final String contextId;
1310
				if (object instanceof TemplateContextType)
1311
					contextId = ((TemplateContextType) object).getId();
1312
				else
1313
					contextId = ((TemplatePersistenceData) object).getTemplate().getContextTypeId();
1314
				for (int i = 0; i < transfers.length; i++) {
1315
					if (transfers[i].isSupportedType(event.currentDataType)) {
1316
						String text = getTemplateDataFromDrop(transfers[i], event.data);
1317
						final Template template = new Template(createTemplateName(),
1318
								TemplatesPageMessages.TemplatesPage_paste_description,
1319
								contextId, text, true);
1320
						getShell().getDisplay().asyncExec(new Runnable() {
1321
							public void run() {
1322
								addTemplate(template);
1323
							}
1324
						});
1325
						return;
1326
					}
1327
				}
1328
				if (templateTransfer.isSupportedType(event.currentDataType)) {
1329
					final TemplatePersistenceData[] templates = (TemplatePersistenceData[]) event.data;
1330
					final int dropType = event.detail;
1331
					getShell().getDisplay().asyncExec(new Runnable() {
1332
						public void run() {
1333
							if (dropType == DND.DROP_COPY)
1334
								copyTemplates(templates, contextId);
1335
							else
1336
								moveTemplates(templates, contextId);
1337
						}
1338
					});
1339
				}
1340
			}
1341
		};
1342
		Transfer[] transfers = new Transfer[getTransfers().length + 1];
1343
		System.arraycopy(getTransfers(), 0, transfers, 0, getTransfers().length);
1344
		transfers[getTransfers().length] = TemplateTransfer.getInstance();
1345
		fTreeViewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, transfers, dropListener);
1346
	}
1347
1348
	/**
1349
	 * Create a template name
1350
	 * 
1351
	 * @return a new template name
1352
	 */
1353
	private String createTemplateName() {
1354
		for (int i = 1; i < Integer.MAX_VALUE; i++) {
1355
			String name = TemplatesPageMessages.TemplatesPage_snippet + i;
1356
			if (getTemplateStore().findTemplate(name) == null)
1357
				return name;
1358
		}
1359
		return null;
1360
	}
1361
1362
	/**
1363
	 * Store the collapse state of a context
1364
	 */
1365
	private void storeCollapseState() {
1366
		TreeItem[] items = fTreeViewer.getTree().getItems();
1367
		for (int i = 0; i < items.length; i++) {
1368
			fPreferenceStore.setValue(CONTEXT_COLLAPSE_PREF_ID + ((TemplateContextType)items[i].getData()).getId(), !items[i].getExpanded());
1369
		}
1370
	}
1371
1372
	/**
1373
	 * Refresh the template tree contents
1374
	 */
1375
	private void refresh() {
1376
		storeCollapseState();
1377
		fTreeViewer.getTree().setRedraw(false);
1378
		try {
1379
			fTreeViewer.refresh();
1380
			TreeItem[] items = fTreeViewer.getTree().getItems();
1381
			for (int i = 0; i < items.length; i++) {
1382
				boolean isExpanded = !fPreferenceStore.getBoolean(CONTEXT_COLLAPSE_PREF_ID + ((TemplateContextType)items[i].getData()).getId());
1383
				if (isExpanded)
1384
					fTreeViewer.expandToLevel(items[i].getData(), AbstractTreeViewer.ALL_LEVELS);
1385
				else
1386
					fTreeViewer.collapseToLevel(items[i].getData(), AbstractTreeViewer.ALL_LEVELS);
1387
			}
1388
		} finally {
1389
			fTreeViewer.getTree().setRedraw(true);
1390
		}
1391
	}
1392
}
(-)src/org/eclipse/ui/texteditor/templates/view/TextEditorTemplatesPage.java (+347 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.texteditor.templates.view;
13
14
import org.eclipse.jface.action.Action;
15
import org.eclipse.jface.action.IAction;
16
import org.eclipse.jface.text.BadLocationException;
17
import org.eclipse.jface.text.Document;
18
import org.eclipse.jface.text.IDocument;
19
import org.eclipse.jface.text.IRegion;
20
import org.eclipse.jface.text.ITextViewerExtension5;
21
import org.eclipse.jface.text.source.ISourceViewer;
22
import org.eclipse.jface.text.source.SourceViewer;
23
import org.eclipse.jface.text.source.SourceViewerConfiguration;
24
import org.eclipse.jface.text.templates.Template;
25
import org.eclipse.jface.viewers.IPostSelectionProvider;
26
import org.eclipse.jface.viewers.ISelectionChangedListener;
27
import org.eclipse.jface.viewers.ISelectionProvider;
28
import org.eclipse.jface.viewers.SelectionChangedEvent;
29
import org.eclipse.jface.viewers.Viewer;
30
import org.eclipse.jface.window.Window;
31
import org.eclipse.swt.SWT;
32
import org.eclipse.swt.custom.StyledText;
33
import org.eclipse.swt.dnd.Clipboard;
34
import org.eclipse.swt.dnd.TextTransfer;
35
import org.eclipse.swt.dnd.Transfer;
36
import org.eclipse.swt.graphics.Point;
37
import org.eclipse.swt.widgets.Composite;
38
import org.eclipse.swt.widgets.Control;
39
import org.eclipse.swt.widgets.Event;
40
import org.eclipse.ui.texteditor.AbstractTextEditor;
41
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
42
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
43
import org.eclipse.ui.texteditor.templates.TemplatePreferencePage.EditTemplateDialog;
44
45
/**
46
 * A TemplatesPage implementation for Editors based on AbstractTextEditor.
47
 * 
48
 * @since 3.4
49
 */
50
public abstract class TextEditorTemplatesPage extends TemplatesPage {
51
	/**
52
	 * A post selection changed listener for the editor. Depending on the caret position
53
	 * updates the templates
54
	 */
55
	private final class SelectionChangedListener implements ISelectionChangedListener {
56
		/* (non-Javadoc)
57
		 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
58
		 */
59
		public void selectionChanged(SelectionChangedEvent event) {
60
			String[] contextTypes = getContextTypes() ;
61
			if (needUpdate(contextTypes)) {
62
				fCurrentContextTypes = contextTypes ;
63
				updateContextTypes(fCurrentContextTypes);
64
				return ;
65
			}
66
		}
67
68
		/**
69
		 * Check whether an update of the TemplatesPage is needed
70
		 * 
71
		 * @param contextTypes
72
		 * @return true if update is needed
73
		 */
74
		private boolean needUpdate(String[] contextTypes) {
75
			return fCurrentContextTypes == null || fCurrentContextTypes.length != contextTypes.length ||
76
			          contextTypeChanged(contextTypes);
77
		}
78
79
		/**
80
		 * Check whether there is any change in the context types needed
81
		 * 
82
		 * @param contextTypes
83
		 * @return true if any of the context types changed
84
		 */
85
		private boolean contextTypeChanged(String[] contextTypes) {
86
			for (int i = 0; i < contextTypes.length; i++) {
87
				if (!contextTypes[i].equals(fCurrentContextTypes[i]))
88
					return false ;
89
			}
90
			return true;
91
		}
92
	}
93
94
	/**
95
	 * The editor
96
	 */
97
	private final AbstractTextEditor fEditor;
98
	/**
99
	 * The SourceViewer attached to this editor
100
	 */
101
	private final ISourceViewer fViewer;
102
	/**
103
	 * The pattern viewer to be used with this view
104
	 */
105
	private SourceViewer fPatternViewer;
106
107
	/* Caches to improve performance while dropping a template */
108
	private int fCachedOffset;
109
	private boolean fCachedResult;
110
	private Point fCachedPosition;
111
	
112
	/**
113
	 * The current context types
114
	 */
115
	private String[] fCurrentContextTypes;
116
	/**
117
	 * The selection changed listener to monitor the editor selections
118
	 */
119
	private SelectionChangedListener fSelectionChangedListener;
120
	
121
	/**
122
	 * Paste action support
123
	 */
124
	private IAction fOldPasteAction;
125
	private IAction fPasteAction;
126
127
	/**
128
	 * Create a new TemplatesPage
129
	 * 
130
	 * @param editor
131
	 * @param viewer 
132
	 */
133
	public TextEditorTemplatesPage(AbstractTextEditor editor, ISourceViewer viewer) {
134
		super();
135
		fEditor= editor;
136
		fViewer= viewer;
137
		setupEditorDropTarget(fEditor.getSite(), (Control) fEditor.getAdapter(Control.class));
138
		setupSelectionProvider();
139
		setupPasteOperation();
140
	}
141
142
	/* (non-Javadoc)
143
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#dispose()
144
	 */
145
	public void dispose() {
146
		ISelectionProvider selectionProvider = fViewer.getSelectionProvider();
147
		if (selectionProvider instanceof IPostSelectionProvider)
148
			((IPostSelectionProvider)selectionProvider).removePostSelectionChangedListener(fSelectionChangedListener);
149
		else
150
			selectionProvider.removeSelectionChangedListener(fSelectionChangedListener);
151
		fEditor.setAction(ITextEditorActionConstants.PASTE, fOldPasteAction);
152
		super.dispose();
153
	}
154
155
	/**
156
	 * Get the editor associated with this view
157
	 * 
158
	 * @return the editor
159
	 */
160
	protected AbstractTextEditor getEditor() {
161
		return fEditor ;
162
	}
163
164
	/* (non-Javadoc)
165
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#isValidTemplateForPosition(org.eclipse.jface.text.templates.Template, org.eclipse.swt.graphics.Point)
166
	 */
167
	protected boolean isValidTemplateForPosition(Template template, Point position) {
168
		StyledText textWidget= (StyledText) fEditor.getAdapter(Control.class);
169
		IDocument document= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
170
		try {
171
			if (position.equals(fCachedPosition))
172
				return fCachedResult;
173
			fCachedPosition= position;
174
			int offset= getOffset(document, textWidget, textWidget.toControl(position.x, position.y));
175
			if (fCachedOffset == offset)
176
				return fCachedResult;
177
			fCachedOffset= offset;
178
			if (isValidTemplate(document, template, offset, 0))
179
				return fCachedResult= true;
180
		} catch (BadLocationException e) {
181
		}
182
		return fCachedResult= false;
183
	}
184
185
	/* (non-Javadoc)
186
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#isEditorModifiable()
187
	 */
188
	protected boolean isEditorModifiable() {
189
		return fEditor.isEditorInputModifiable();
190
	}
191
192
	/**
193
	 * Creates, configures and returns a source viewer to present the template
194
	 * pattern on the templates page. Clients may override to provide a custom
195
	 * source viewer featuring e.g. syntax coloring.
196
	 * 
197
	 * @param parent
198
	 *            the parent control
199
	 * @return a configured source viewer
200
	 */
201
	protected Viewer createPatternViewer(Composite parent) {
202
		if (parent == null)
203
			return fPatternViewer ;
204
		fPatternViewer = new SourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL
205
				| SWT.H_SCROLL);
206
		SourceViewerConfiguration configuration = new SourceViewerConfiguration();
207
		fPatternViewer.configure(configuration);
208
		IDocument document = new Document();
209
		fPatternViewer.setDocument(document);
210
		fPatternViewer.setEditable(false);
211
		return fPatternViewer;
212
	}
213
214
	/* (non-Javadoc)
215
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#updatePatternViewer(org.eclipse.jface.text.templates.Template)
216
	 */
217
	protected void updatePatternViewer(Template template) {
218
		if (template != null)
219
			fPatternViewer.getDocument().set(template.getPattern());
220
		else
221
			fPatternViewer.getDocument().set(""); //$NON-NLS-1$
222
	}
223
224
	/* (non-Javadoc)
225
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getTemplateDataFromClipboard(org.eclipse.swt.dnd.Clipboard)
226
	 */
227
	protected String getTemplateDataFromClipboard(Clipboard clipBoard) {
228
		String pattern = ((String) clipBoard.getContents(TextTransfer.getInstance()));
229
		if (pattern != null)
230
			return pattern.replaceAll("\\$", "\\$\\$");  //$NON-NLS-1$//$NON-NLS-2$
231
		return null ;
232
	}
233
234
	/* (non-Javadoc)
235
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getTemplateDataFromDrop(org.eclipse.swt.dnd.Transfer, java.lang.Object)
236
	 */
237
	protected String getTemplateDataFromDrop(Transfer transfer, Object data) {
238
		if (transfer instanceof TextTransfer)
239
			return ((String)data).replaceAll("\\$", "\\$\\$");  //$NON-NLS-1$//$NON-NLS-2$
240
		return null;
241
	}
242
243
	/* (non-Javadoc)
244
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getTransfers()
245
	 */
246
	protected Transfer[] getTransfers() {
247
		return new Transfer[] { TextTransfer.getInstance() };
248
	}
249
250
	/* (non-Javadoc)
251
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#editTemplate(org.eclipse.jface.text.templates.Template, boolean, boolean)
252
	 */
253
	protected Template editTemplate(Template template, boolean edit, boolean isNameModifiable) {
254
		EditTemplateDialog dialog = new EditTemplateDialog(getShell(), template, edit,
255
				isNameModifiable, getContextTypeRegistry());
256
		if (dialog.open() == Window.OK) {
257
			return dialog.getTemplate();
258
		}
259
		return null;
260
	}
261
262
	/**
263
	 * Get the context types supported at the current caret position of the editor
264
	 * 
265
	 * @return the ids of the context types
266
	 */
267
	protected abstract String[] getContextTypes() ;
268
269
	/**
270
	 * Check whether the given template is valid for the document at the given position
271
	 * 
272
	 * @param document
273
	 * @param template
274
	 * @param offset
275
	 * @param length
276
	 * @return true if the template is valid
277
	 */
278
	protected abstract boolean isValidTemplate(IDocument document, Template template, int offset, int length);
279
280
	/**
281
	 * Setup the paste operation
282
	 * 
283
	 * We get the editors Paste operation and sets up a new operation that checks for the clipboard contents for
284
	 * TemplateTransfer data.
285
	 */
286
	private void setupPasteOperation() {
287
		fOldPasteAction = fEditor.getAction(ITextEditorActionConstants.PASTE);
288
		fPasteAction = new Action(TemplatesPageMessages.TemplatesPage_paste) {
289
			public void run() {
290
				Clipboard clipBoard = new Clipboard(getShell().getDisplay());
291
				Template template = getTemplateFromClipboard(clipBoard);
292
				if (template != null)
293
					insertTemplate(template, null);
294
				else
295
					fOldPasteAction.run();
296
			}
297
			public void runWithEvent(Event event) {
298
				Clipboard clipBoard = new Clipboard(getShell().getDisplay());
299
				Template template = getTemplateFromClipboard(clipBoard);
300
				if (template != null)
301
					insertTemplate(template, null);
302
				else
303
					fOldPasteAction.runWithEvent(event);
304
			}
305
		};
306
		fPasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
307
		fEditor.setAction(ITextEditorActionConstants.PASTE, fPasteAction);
308
	}
309
310
	/**
311
	 * Setup a selection listener to monitor the editor
312
	 */
313
	private void setupSelectionProvider() {
314
		ISelectionProvider selectionProvider = fViewer.getSelectionProvider();
315
		fSelectionChangedListener = new SelectionChangedListener();
316
		if (selectionProvider instanceof IPostSelectionProvider)
317
			((IPostSelectionProvider)selectionProvider).addPostSelectionChangedListener(fSelectionChangedListener);
318
		else
319
			selectionProvider.addSelectionChangedListener(fSelectionChangedListener);
320
	}
321
322
	/**
323
	 * Get the document relative offset from the textwidget relative point
324
	 * 
325
	 * @param document
326
	 * @param textWidget
327
	 * @param point
328
	 * @return the offset
329
	 * @throws BadLocationException
330
	 */
331
	private int getOffset(IDocument document, StyledText textWidget, Point point) throws BadLocationException {
332
		int widgetCaret= fViewer.getTextWidget().getCaretOffset();
333
		if (fViewer instanceof ITextViewerExtension5) {
334
			ITextViewerExtension5 ext= (ITextViewerExtension5) fViewer;
335
			try {
336
				return ext.widgetOffset2ModelOffset(textWidget.getOffsetAtLocation(point));
337
			} catch (IllegalArgumentException e) {
338
				int docLineIndex= ext.widgetLine2ModelLine(textWidget.getLineIndex(point.y));
339
				String lineDelimiter= document.getLineDelimiter(docLineIndex);
340
				int delimLength= lineDelimiter == null ? 0 : lineDelimiter.length();
341
				return document.getLineOffset(docLineIndex) + document.getLineLength(docLineIndex) - delimLength;
342
			}
343
		}
344
		IRegion visible= fViewer.getVisibleRegion();
345
		return widgetCaret + visible.getOffset();
346
	}
347
}
(-)ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java (+24 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.ui.javaeditor;
12
package org.eclipse.jdt.internal.ui.javaeditor;
12
13
Lines 142-147 Link Here
142
143
143
import org.eclipse.ui.views.contentoutline.ContentOutline;
144
import org.eclipse.ui.views.contentoutline.ContentOutline;
144
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
145
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
146
import org.eclipse.ui.views.templates.ITemplatesPage;
145
147
146
import org.eclipse.jdt.core.IClassFile;
148
import org.eclipse.jdt.core.IClassFile;
147
import org.eclipse.jdt.core.ICompilationUnit;
149
import org.eclipse.jdt.core.ICompilationUnit;
Lines 197-202 Link Here
197
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
199
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
198
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
200
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
199
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
201
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
202
import org.eclipse.jdt.internal.ui.preferences.JavaTemplatesPage;
200
import org.eclipse.jdt.internal.ui.search.BreakContinueTargetFinder;
203
import org.eclipse.jdt.internal.ui.search.BreakContinueTargetFinder;
201
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
204
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
202
import org.eclipse.jdt.internal.ui.search.ImplementOccurrencesFinder;
205
import org.eclipse.jdt.internal.ui.search.ImplementOccurrencesFinder;
Lines 1336-1341 Link Here
1336
	protected JavaOutlinePage fOutlinePage;
1339
	protected JavaOutlinePage fOutlinePage;
1337
	/** Outliner context menu Id */
1340
	/** Outliner context menu Id */
1338
	protected String fOutlinerContextMenuId;
1341
	protected String fOutlinerContextMenuId;
1342
	/** The templates page
1343
     *
1344
     *  @since 3.4
1345
    */
1346
	private JavaTemplatesPage fTemplatesPage;
1347
	
1339
	/**
1348
	/**
1340
	 * The editor selection changed listener.
1349
	 * The editor selection changed listener.
1341
	 *
1350
	 *
Lines 1791-1796 Link Here
1791
			return fOutlinePage;
1800
			return fOutlinePage;
1792
		}
1801
		}
1793
1802
1803
		if (required.equals(ITemplatesPage.class)) {
1804
			return getTemplatesPage();
1805
		}
1806
1794
		if (IEncodingSupport.class.equals(required))
1807
		if (IEncodingSupport.class.equals(required))
1795
			return fEncodingSupport;
1808
			return fEncodingSupport;
1796
1809
Lines 1846-1851 Link Here
1846
	}
1859
	}
1847
1860
1848
	/**
1861
	/**
1862
     *  @since 3.4
1863
     */
1864
	private JavaTemplatesPage getTemplatesPage() {
1865
		if (fTemplatesPage == null) {
1866
			fTemplatesPage= new JavaTemplatesPage(this);
1867
1868
		}
1869
		return fTemplatesPage;
1870
	}
1871
1872
	/**
1849
	 * React to changed selection.
1873
	 * React to changed selection.
1850
	 *
1874
	 *
1851
	 * @since 3.0
1875
	 * @since 3.0
(-)ui/org/eclipse/jdt/internal/ui/JavaPerspectiveFactory.java (-1 / +5 lines)
Lines 7-12 Link Here
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
9
 *     IBM Corporation - initial API and implementation
10
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.ui;
12
package org.eclipse.jdt.internal.ui;
12
13
Lines 45-51 Link Here
45
		outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
46
		outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS);
46
		outputfolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
47
		outputfolder.addPlaceholder(IProgressConstants.PROGRESS_VIEW_ID);
47
		
48
		
48
		layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea);
49
		IFolderLayout outlineFolder = layout.createFolder("right", IPageLayout.RIGHT, (float)0.75, editorArea); //$NON-NLS-1$
50
		outlineFolder.addView(IPageLayout.ID_OUTLINE);
51
		outlineFolder.addView(IPageLayout.ID_TEMPLATES);
49
		
52
		
50
		layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
53
		layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
51
		layout.addActionSet(JavaUI.ID_ACTION_SET);
54
		layout.addActionSet(JavaUI.ID_ACTION_SET);
Lines 66-71 Link Here
66
69
67
		// views - standard workbench
70
		// views - standard workbench
68
		layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
71
		layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
72
		layout.addShowViewShortcut(IPageLayout.ID_TEMPLATES);
69
		layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
73
		layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
70
		layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
74
		layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
71
		layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
75
		layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
(-)ui/org/eclipse/jdt/internal/ui/preferences/JavaTemplatesPage.java (+392 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.jdt.internal.ui.preferences;
13
14
import org.eclipse.swt.SWT;
15
import org.eclipse.swt.graphics.Font;
16
import org.eclipse.swt.graphics.Image;
17
import org.eclipse.swt.graphics.Point;
18
import org.eclipse.swt.layout.GridData;
19
import org.eclipse.swt.widgets.Composite;
20
import org.eclipse.swt.widgets.Control;
21
22
import org.eclipse.jface.preference.IPreferenceStore;
23
import org.eclipse.jface.resource.JFaceResources;
24
import org.eclipse.jface.viewers.Viewer;
25
import org.eclipse.jface.window.Window;
26
27
import org.eclipse.jface.text.BadLocationException;
28
import org.eclipse.jface.text.Document;
29
import org.eclipse.jface.text.IDocument;
30
import org.eclipse.jface.text.ITextSelection;
31
import org.eclipse.jface.text.ITextViewerExtension;
32
import org.eclipse.jface.text.Position;
33
import org.eclipse.jface.text.Region;
34
import org.eclipse.jface.text.TextSelection;
35
import org.eclipse.jface.text.TextUtilities;
36
import org.eclipse.jface.text.source.ISourceViewer;
37
import org.eclipse.jface.text.templates.ContextTypeRegistry;
38
import org.eclipse.jface.text.templates.DocumentTemplateContext;
39
import org.eclipse.jface.text.templates.Template;
40
import org.eclipse.jface.text.templates.TemplateContextType;
41
import org.eclipse.jface.text.templates.persistence.TemplateStore;
42
43
import org.eclipse.ui.texteditor.templates.view.TextEditorTemplatesPage;
44
45
import org.eclipse.ui.views.templates.ITemplatesPage;
46
47
import org.eclipse.jdt.core.ICompilationUnit;
48
49
import org.eclipse.jdt.internal.corext.template.java.CompilationUnitContextType;
50
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
51
import org.eclipse.jdt.internal.corext.template.java.JavaContextType;
52
import org.eclipse.jdt.internal.corext.template.java.JavaDocContext;
53
import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType;
54
import org.eclipse.jdt.internal.corext.template.java.SWTContextType;
55
56
import org.eclipse.jdt.ui.PreferenceConstants;
57
import org.eclipse.jdt.ui.text.IJavaPartitions;
58
import org.eclipse.jdt.ui.text.JavaTextTools;
59
60
import org.eclipse.jdt.internal.ui.JavaPlugin;
61
import org.eclipse.jdt.internal.ui.JavaPluginImages;
62
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
63
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
64
import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
65
import org.eclipse.jdt.internal.ui.text.SimpleJavaSourceViewerConfiguration;
66
import org.eclipse.jdt.internal.ui.text.template.contentassist.TemplateProposal;
67
import org.eclipse.jdt.internal.ui.text.template.preferences.TemplateVariableProcessor;
68
69
/**
70
 * An implementation of TemplatesPage for JavaEditor
71
 */
72
public class JavaTemplatesPage extends TextEditorTemplatesPage implements ITemplatesPage {
73
74
	private static final String PREFERENCE_PAGE_ID= "org.eclipse.jdt.ui.preferences.JavaTemplatePreferencePage"; //$NON-NLS-1$
75
	private static final TemplateStore TEMPLATE_STORE= JavaPlugin.getDefault().getTemplateStore();
76
	private static final IPreferenceStore PREFERENCE_STORE= JavaPlugin.getDefault().getPreferenceStore();
77
	private static final ContextTypeRegistry TEMPLATE_CONTEXT_REGISTRY= JavaPlugin.getDefault().getTemplateContextRegistry();
78
	
79
	private TemplateVariableProcessor fTemplateProcessor;
80
	private JavaSourceViewer fPatternViewer;
81
82
	/**
83
	 * Create a new TemplatesPage for the JavaEditor
84
	 * 
85
	 * @param javaEditor
86
	 */
87
	public JavaTemplatesPage(JavaEditor javaEditor) {
88
		super(javaEditor, javaEditor.getViewer());
89
		fTemplateProcessor= new TemplateVariableProcessor();
90
		updateContextTypes(getContextTypes());
91
	}
92
93
	/* (non-Javadoc)
94
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#insertTemplate(org.eclipse.jface.text.templates.Template, org.eclipse.swt.graphics.Point)
95
	 */
96
	protected void insertTemplate(Template template, Point dropPosition) {
97
		if (!getJavaEditor().validateEditorInputState())
98
			return;
99
		ISourceViewer contextViewer= getJavaEditor().getViewer();
100
		ITextSelection textSelection= (ITextSelection) contextViewer.getSelectionProvider().getSelection();
101
		IDocument document= getJavaEditor().getDocumentProvider().getDocument(getJavaEditor().getEditorInput());
102
		if (!isValidTemplate(document, template, textSelection.getOffset(), textSelection.getLength()))
103
			return;
104
		beginCompoundChange(contextViewer);
105
		/*
106
		 * The Editor checks whether a completion for a word exists before it allows for the template to be
107
		 * applied. We pickup the current text at the selection position and replace it with the first char
108
		 * of the template name for this to succeed.
109
		 * Another advantage by this method is that the template replaces the selected text provided the
110
		 * selection by itself is not used in the template pattern.
111
		 */
112
		String savedText;
113
		try {
114
			savedText= document.get(textSelection.getOffset(), textSelection.getLength());
115
			if (savedText.length() == 0) {
116
				String prefix= getIdentifierPart(document, template, textSelection.getOffset(), textSelection.getLength());
117
				if (prefix.length() > 0 && !template.getName().startsWith(prefix.toString())) {
118
					return;
119
				}
120
				if (prefix.length() > 0) {
121
					contextViewer.setSelectedRange(textSelection.getOffset() - prefix.length(), prefix.length());
122
					textSelection= (ITextSelection) contextViewer.getSelectionProvider().getSelection();
123
				}
124
			}
125
			document.replace(textSelection.getOffset(), textSelection.getLength(), template.getName().substring(0, 1));
126
		} catch (BadLocationException e) {
127
			endCompoundChange(contextViewer);
128
			return;
129
		}
130
		Position position= new Position(textSelection.getOffset() + 1, 0);
131
		Region region= new Region(textSelection.getOffset() + 1, 0);
132
		contextViewer.getSelectionProvider().setSelection(new TextSelection(textSelection.getOffset(), 1));
133
		ICompilationUnit compilationUnit= (ICompilationUnit) EditorUtility.getEditorInputJavaElement(getJavaEditor(), true);
134
	
135
		TemplateContextType type= getContextTypeRegistry().getContextType(template.getContextTypeId());
136
		DocumentTemplateContext context= ((CompilationUnitContextType) type).createContext(document, position, compilationUnit);
137
		context.setVariable("selection", savedText); //$NON-NLS-1$
138
		if (context.getKey().length() == 0) {
139
			try {
140
				document.replace(textSelection.getOffset(), 1, savedText);
141
			} catch (BadLocationException e) {
142
				endCompoundChange(contextViewer);
143
				return;
144
			}
145
		}
146
		TemplateProposal proposal= new TemplateProposal(template, context, region, null);
147
		getJavaEditor().getSite().getPage().activate(getJavaEditor());
148
		proposal.apply(getJavaEditor().getViewer(), ' ', 0, region.getOffset());
149
		endCompoundChange(contextViewer);
150
	}
151
152
	/* (non-Javadoc)
153
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getContextTypeRegistry()
154
	 */
155
	protected ContextTypeRegistry getContextTypeRegistry() {
156
		return TEMPLATE_CONTEXT_REGISTRY;
157
	}
158
159
	/* (non-Javadoc)
160
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getTemplatePreferenceStore()
161
	 */
162
	protected IPreferenceStore getTemplatePreferenceStore() {
163
		return PREFERENCE_STORE;
164
	}
165
166
	/* (non-Javadoc)
167
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getTemplateStore()
168
	 */
169
	protected TemplateStore getTemplateStore() {
170
		return TEMPLATE_STORE;
171
	}
172
173
	/* (non-Javadoc)
174
	 * @see org.eclipse.ui.texteditor.templates.TextEditorTemplatesPage#isValidTemplate(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.templates.Template, int, int)
175
	 */
176
	protected boolean isValidTemplate(IDocument document, Template template, int offset, int length) {
177
		try {
178
			String[] contextIds= getContextIds(document, offset);
179
			for (int i= 0; i < contextIds.length; i++) {
180
				if (contextIds[i].equals(template.getContextTypeId())) {
181
					DocumentTemplateContext context= getContext(document, template, offset, length);
182
					return context.canEvaluate(template) || isTemplateAllowed(context, template);
183
				}
184
			}
185
		} catch (BadLocationException e) {
186
		}
187
		return false;
188
	}
189
190
	/* (non-Javadoc)
191
	 * @see org.eclipse.ui.texteditor.templates.TextEditorTemplatesPage#createPatternViewer(org.eclipse.swt.widgets.Composite)
192
	 */
193
	protected Viewer createPatternViewer(Composite parent) {
194
		if (parent == null)
195
			return fPatternViewer ;
196
		IDocument document= new Document();
197
		JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
198
		tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
199
		IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
200
		fPatternViewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store);
201
		SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(tools.getColorManager(), store, null, IJavaPartitions.JAVA_PARTITIONING, false);
202
		fPatternViewer.configure(configuration);
203
		fPatternViewer.setEditable(false);
204
		fPatternViewer.setDocument(document);
205
	
206
		Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
207
		fPatternViewer.getTextWidget().setFont(font);
208
		new JavaSourcePreviewerUpdater(fPatternViewer, configuration, store);
209
	
210
		Control control= fPatternViewer.getControl();
211
		GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
212
		control.setLayoutData(data);
213
	
214
		fPatternViewer.setEditable(false);
215
		return fPatternViewer;
216
	}
217
218
	/* (non-Javadoc)
219
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getImageForTemplate(org.eclipse.jface.text.templates.Template)
220
	 */
221
	protected Image getImageForTemplate(Template template) {
222
		if (template.getContextTypeId().equals(SWTContextType.ID))
223
			return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SWT_TEMPLATE);
224
		return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE);
225
	}
226
227
	/* (non-Javadoc)
228
	 * @see org.eclipse.ui.texteditor.templates.TextEditorTemplatesPage#editTemplate(org.eclipse.jface.text.templates.Template, boolean, boolean)
229
	 */
230
	protected Template editTemplate(Template template, boolean edit, boolean isNameModifiable) {
231
		EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, edit, isNameModifiable, getContextTypeRegistry());
232
		if (dialog.open() == Window.OK) {
233
			return dialog.getTemplate();
234
		}
235
		return null;
236
	}
237
238
	/* (non-Javadoc)
239
	 * @see org.eclipse.ui.texteditor.templates.TextEditorTemplatesPage#getContextTypes()
240
	 */
241
	protected String[] getContextTypes() {
242
		Point selectedRange= getJavaEditor().getViewer().getSelectedRange();
243
		int offset= selectedRange.x + selectedRange.y;
244
		try {
245
			IDocument document= getJavaEditor().getDocumentProvider().getDocument(getJavaEditor().getEditorInput());
246
			return getContextIds(document, offset);
247
		} catch (BadLocationException e) {
248
			return new String[0];
249
		}
250
	}
251
252
	/* (non-Javadoc)
253
	 * @see org.eclipse.ui.texteditor.templates.TextEditorTemplatesPage#updatePatternViewer(org.eclipse.jface.text.templates.Template)
254
	 */
255
	protected void updatePatternViewer(Template template) {
256
		if (template == null) {
257
			fPatternViewer.getDocument().set(""); //$NON-NLS-1$
258
			return ;
259
		}
260
		String contextId= template.getContextTypeId();
261
		TemplateContextType type= getContextTypeRegistry().getContextType(contextId);
262
		fTemplateProcessor.setContextType(type);
263
	
264
		IDocument doc= fPatternViewer.getDocument();
265
	
266
		String start= null;
267
		if ("javadoc".equals(contextId)) { //$NON-NLS-1$
268
			start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
269
		} else
270
			start= ""; //$NON-NLS-1$
271
	
272
		doc.set(start + template.getPattern());
273
		int startLen= start.length();
274
		fPatternViewer.setDocument(doc, startLen, doc.getLength() - startLen);
275
	}
276
277
	/* (non-Javadoc)
278
	 * @see org.eclipse.ui.texteditor.templates.TemplatesPage#getPreferencePageId()
279
	 */
280
	protected String getPreferencePageId() {
281
		return PREFERENCE_PAGE_ID;
282
	}
283
284
	/**
285
	 * Helper function to return the JavaEditor
286
	 * 
287
	 * @return the editor
288
	 */
289
	private JavaEditor getJavaEditor() {
290
		return (JavaEditor)getEditor() ;
291
	}
292
	
293
	/**
294
	 * Undomanager - end compound change
295
	 * @param viewer
296
	 */
297
	private void endCompoundChange(ISourceViewer viewer) {
298
		if (viewer instanceof ITextViewerExtension)
299
			((ITextViewerExtension) viewer).getRewriteTarget().endCompoundChange();
300
	}
301
302
	/**
303
	 * Undomanager - begin a compound change
304
	 * @param viewer
305
	 */
306
	private void beginCompoundChange(ISourceViewer viewer) {
307
		if (viewer instanceof ITextViewerExtension)
308
			((ITextViewerExtension) viewer).getRewriteTarget().beginCompoundChange();
309
	}
310
311
	/**
312
	 * Check whether the template is allowed eventhough the context can't evaluate it. This is needed because
313
	 * the Dropping of a template is more lenient than ctl-space invoked code assist.
314
	 * 
315
	 * @param context
316
	 * @param template
317
	 * @return true if the template is allowed
318
	 */
319
	private boolean isTemplateAllowed(DocumentTemplateContext context, Template template) {
320
		int offset;
321
		try {
322
			if (template.getContextTypeId().equals(JavaDocContextType.ID)) {
323
				return (offset= context.getCompletionOffset()) > 0 && Character.isWhitespace(context.getDocument().getChar(offset - 1));
324
			} else {
325
				return ((offset= context.getCompletionOffset()) > 0 && !isTemplateNamePart(context.getDocument().getChar(offset - 1)));
326
			}
327
		} catch (BadLocationException e) {
328
		}
329
		return false;
330
	}
331
332
	/**
333
	 * Checks whether the character is a valid character in Java template names
334
	 * 
335
	 * @param ch
336
	 * @return true or false
337
	 */
338
	private boolean isTemplateNamePart(char ch) {
339
		return !Character.isWhitespace(ch) && ch != '(' && ch != ')' && ch != '{' && ch != '}' && ch != ';';
340
	}
341
342
	/**
343
	 * Get context
344
	 * 
345
	 * @param document
346
	 * @param template
347
	 * @param offset
348
	 * @param length
349
	 * @return the context
350
	 */
351
	private DocumentTemplateContext getContext(IDocument document, Template template, final int offset, int length) {
352
		DocumentTemplateContext context;
353
		if (template.getContextTypeId().equals(JavaDocContextType.ID)) {
354
			context= new JavaDocContext(getContextTypeRegistry().getContextType(template.getContextTypeId()), document, new Position(offset, length), (ICompilationUnit) EditorUtility
355
					.getEditorInputJavaElement(getJavaEditor(), true));
356
		} else {
357
			context= new JavaContext(getContextTypeRegistry().getContextType(template.getContextTypeId()), document, new Position(offset, length), (ICompilationUnit) EditorUtility.getEditorInputJavaElement(
358
					getJavaEditor(), true));
359
		}
360
		return context;
361
	}
362
363
	/**
364
	 * Get the active contexts for the given position in the document
365
	 * 
366
	 * @param document
367
	 * @param offset
368
	 * @return an array of valid context id
369
	 * @throws BadLocationException
370
	 */
371
	private String[] getContextIds(IDocument document, int offset) throws BadLocationException {
372
		String partition= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
373
		String[] ids= new String[] { JavaContextType.ID, SWTContextType.ID };
374
		if (partition.equals(IJavaPartitions.JAVA_DOC))
375
			ids= new String[] { JavaDocContextType.ID };
376
		return ids;
377
	}
378
379
	/**
380
	 * Get the java identifier terminated at the given offset
381
	 * 
382
	 * @param document 
383
	 * @param template 
384
	 * @param offset
385
	 * @param length 
386
	 * @return the identifier part
387
	 * @throws BadLocationException
388
	 */
389
	private String getIdentifierPart(IDocument document, Template template, int offset, int length) throws BadLocationException {
390
		return getContext(document, template, offset, length).getKey();
391
	}
392
}
(-)META-INF/MANIFEST.MF (-1 / +2 lines)
Lines 11-17 Link Here
11
 org.eclipse.ui.internal.views.contentoutline;x-internal:=true,
11
 org.eclipse.ui.internal.views.contentoutline;x-internal:=true,
12
 org.eclipse.ui.internal.views.properties;x-internal:=true,
12
 org.eclipse.ui.internal.views.properties;x-internal:=true,
13
 org.eclipse.ui.views.contentoutline,
13
 org.eclipse.ui.views.contentoutline,
14
 org.eclipse.ui.views.properties
14
 org.eclipse.ui.views.properties,
15
 org.eclipse.ui.views.templates
15
Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.2.0,4.0.0)",
16
 org.eclipse.help;bundle-version="[3.2.0,4.0.0)",
17
 org.eclipse.help;bundle-version="[3.2.0,4.0.0)",
17
 org.eclipse.ui;bundle-version="[3.2.0,4.0.0)"
18
 org.eclipse.ui;bundle-version="[3.2.0,4.0.0)"
(-)plugin.properties (-1 / +2 lines)
Lines 7-16 Link Here
7
#
7
#
8
# Contributors:
8
# Contributors:
9
#     IBM Corporation - initial API and implementation
9
#     IBM Corporation - initial API and implementation
10
#     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
###############################################################################
11
###############################################################################
11
pluginName= Views
12
pluginName= Views
12
providerName= Eclipse.org
13
providerName= Eclipse.org
13
14
14
Views.PropertySheet = Properties
15
Views.PropertySheet = Properties
15
Views.ContentOutline = Outline
16
Views.ContentOutline = Outline
16
17
Views.Templates = Templates
(-)plugin.xml (+7 lines)
Lines 18-23 Link Here
18
            class="org.eclipse.ui.views.contentoutline.ContentOutline"
18
            class="org.eclipse.ui.views.contentoutline.ContentOutline"
19
            id="org.eclipse.ui.views.ContentOutline">
19
            id="org.eclipse.ui.views.ContentOutline">
20
      </view>
20
      </view>
21
      <view
22
            name="%Views.Templates"
23
            icon="$nl$/icons/full/eview16/templates.gif"
24
            category="org.eclipse.ui"
25
            class="org.eclipse.ui.views.templates.TemplatesView"
26
            id="org.eclipse.ui.views.Templates">
27
      </view>
21
   </extension>
28
   </extension>
22
   
29
   
23
</plugin>
30
</plugin>
(-)src/org/eclipse/ui/views/templates/TemplatesView.java (+184 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.views.templates;
13
14
import org.eclipse.swt.widgets.Composite;
15
import org.eclipse.ui.IEditorPart;
16
import org.eclipse.ui.IWorkbenchPage;
17
import org.eclipse.ui.IWorkbenchPart;
18
import org.eclipse.ui.PlatformUI;
19
import org.eclipse.ui.internal.views.ViewsPlugin;
20
import org.eclipse.ui.internal.views.templates.TemplatesMessages;
21
import org.eclipse.ui.part.IContributedContentsView;
22
import org.eclipse.ui.part.IPage;
23
import org.eclipse.ui.part.MessagePage;
24
import org.eclipse.ui.part.PageBook;
25
import org.eclipse.ui.part.PageBookView;
26
27
/**
28
 * Main class for the Templates View.
29
 * <p>
30
 * This standard view has id <code>"org.eclipse.ui.views.TemplatesView"</code>.
31
 * </p>
32
 * When a <b>templates view</b> notices an editor being activated, it 
33
 * asks the editor whether it has a <b>template page</b> to include
34
 * in the templates view. This is done using <code>getAdapter</code>:
35
 * <pre>
36
 * IEditorPart editor = ...;
37
 * ITemplatePage templatePage = (ITemplatePage) editor.getAdapter(ITemplatePage.class);
38
 * if (templatePage != null) {
39
 *    // editor wishes to contribute templatePage to templates view
40
 * }
41
 * </pre>
42
 * If the editor supports a templates page, the editor instantiates
43
 * and configures the page, and returns it. This page is then added to the 
44
 * templates view (a pagebook which presents one page at a time) and 
45
 * immediately made the current page (the templates view need not be
46
 * visible). If the editor does not support a template page, the templates
47
 * view shows a special default page which makes it clear to the user
48
 * that the templates view is disengaged. When the templates view notices a
49
 * different editor being activated, it flips to the editor's corresponding
50
 * template page. When the templates view notices an editor being
51
 * closed, it may destroy the editor's corresponding content outline page.
52
 * </p>
53
 * <p>
54
 * The workbench will automatically instantiate this class when a templates
55
 * view is needed for a workbench window. This class was not intended
56
 * to be instantiated or subclassed by clients.
57
 * </p>
58
 *
59
 * @since 3.4
60
 */
61
public class TemplatesView extends PageBookView {
62
    /**
63
     * The plugin prefix.
64
     */
65
    public static final String PREFIX = PlatformUI.PLUGIN_ID + "."; //$NON-NLS-1$
66
67
    /**
68
     * Help context id used for the templates view
69
     */
70
    public static final String TEMPLATES_VIEW_HELP_CONTEXT_ID = PREFIX
71
            + "templates_view_context";//$NON-NLS-1$
72
73
    /**
74
     * Message to show on the default page.
75
     */
76
    private static final String DEFAULT_TEXT = TemplatesMessages.Templates_defaultMessage; 
77
78
    /**
79
     * Creates a templates view
80
     */
81
    public TemplatesView() {
82
        super();
83
    }
84
85
    /* (non-Javadoc)
86
     * Method declared on PageBookView.
87
     */
88
    protected IPage createDefaultPage(PageBook book) {
89
        MessagePage page = new MessagePage();
90
        initPage(page);
91
        page.createControl(book);
92
        page.setMessage(DEFAULT_TEXT);
93
        return page;
94
    }
95
96
    /**
97
     * The <code>PageBookView</code> implementation of this <code>IWorkbenchPart</code>
98
     * method creates a <code>PageBook</code> control with its default page showing.
99
     */
100
    public void createPartControl(Composite parent) {
101
        super.createPartControl(parent);
102
        PlatformUI.getWorkbench().getHelpSystem().setHelp(getPageBook(),
103
                TEMPLATES_VIEW_HELP_CONTEXT_ID);
104
    }
105
106
    /* (non-Javadoc)
107
     * Method declared on PageBookView.
108
     */
109
    protected PageRec doCreatePage(IWorkbenchPart part) {
110
        // Try to get template page.
111
        Object obj = ViewsPlugin.getAdapter(part, ITemplatesPage.class, false);
112
        if (obj instanceof ITemplatesPage) {
113
            ITemplatesPage page = (ITemplatesPage) obj;
114
			initPage(page);
115
            page.createControl(getPageBook());
116
            return new PageRec(part, page);
117
        }
118
        // There is no template page
119
        return null;
120
    }
121
122
    /* (non-Javadoc)
123
     * Method declared on PageBookView.
124
     */
125
    protected void doDestroyPage(IWorkbenchPart part, PageRec rec) {
126
        ITemplatesPage page = (ITemplatesPage) rec.page;
127
        page.dispose();
128
        rec.dispose();
129
    }
130
131
    /* (non-Javadoc)
132
     * Method declared on IAdaptable.
133
     */
134
    public Object getAdapter(Class key) {
135
        if (key == IContributedContentsView.class) {
136
			return new IContributedContentsView() {
137
                public IWorkbenchPart getContributingPart() {
138
                    return getContributingEditor();
139
                }
140
            };
141
		}
142
        return super.getAdapter(key);
143
    }
144
145
    /* (non-Javadoc)
146
     * Method declared on PageBookView.
147
     */
148
    protected IWorkbenchPart getBootstrapPart() {
149
        IWorkbenchPage page = getSite().getPage();
150
        if (page != null) {
151
			return page.getActiveEditor();
152
		}
153
154
        return null;
155
    }
156
157
    /**
158
     * Returns the editor which contributed the current 
159
     * page to this view.
160
     *
161
     * @return the editor which contributed the current page
162
     * or <code>null</code> if no editor contributed the current page
163
     */
164
    private IWorkbenchPart getContributingEditor() {
165
        return getCurrentContributingPart();
166
    }
167
168
    /* (non-Javadoc)
169
     * Method declared on PageBookView.
170
     * We only want to track editors.
171
     */
172
    protected boolean isImportant(IWorkbenchPart part) {
173
        //We only care about editors
174
        return (part instanceof IEditorPart);
175
    }
176
177
    /* (non-Javadoc)
178
     * Method declared on IViewPart.
179
     * Treat this the same as part activation.
180
     */
181
    public void partBroughtToTop(IWorkbenchPart part) {
182
        partActivated(part);
183
    }
184
}
(-)src/org/eclipse/ui/internal/views/templates/TemplatesMessages.java (+33 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.internal.views.templates;
13
14
import org.eclipse.osgi.util.NLS;
15
16
/**
17
 * TemplatesMessages is the message class for the messages used in the templates view.
18
 */
19
public class TemplatesMessages extends NLS {
20
	private static final String BUNDLE_NAME = "org.eclipse.ui.internal.views.templates.TemplatesMessages"; //$NON-NLS-1$
21
	
22
	/**
23
	 * Default message for an empty templates view 
24
	 */
25
	public static String Templates_defaultMessage;
26
	static {
27
		// initialize resource bundle
28
		NLS.initializeMessages(BUNDLE_NAME, TemplatesMessages.class);
29
	}
30
31
	private TemplatesMessages() {
32
	}
33
}
(-)src/org/eclipse/ui/internal/views/templates/TemplatesMessages.properties (+11 lines)
Added Link Here
1
###############################################################################
2
# Copyright (c) 2000, 2007 Dakshinamurthy Karra and others.
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
6
# http://www.eclipse.org/legal/epl-v10.html
7
# 
8
# Contributors:
9
#     Dakshinamurthy Karra - initial API and implementation
10
###############################################################################
11
Templates_defaultMessage=Templates are not available.
(-)src/org/eclipse/ui/views/templates/ITemplatesPage.java (+25 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2007 Dakshinamurthy Karra and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
10
 *******************************************************************************/
11
12
package org.eclipse.ui.views.templates;
13
14
import org.eclipse.ui.part.IPageBookViewPage;
15
16
/**
17
 * Interface for a template page. This interface defines
18
 * the minimum requirement for pages within the templates view, namely
19
 * they must be pages (implement <code>IPageBookViewPage</code>).
20
 *
21
 * @see TemplatesView
22
 * @since 3.4
23
 */
24
public interface ITemplatesPage extends IPageBookViewPage {
25
}
(-)Eclipse UI/org/eclipse/ui/IPageLayout.java (+6 lines)
Lines 10-15 Link Here
10
 *     Chris Gross <schtoo@schtoo.com> 
10
 *     Chris Gross <schtoo@schtoo.com> 
11
 *     - Fix for 99155 - allow standalone view placeholders
11
 *     - Fix for 99155 - allow standalone view placeholders
12
 *     Chris Gross chris.gross@us.ibm.com Bug 107443
12
 *     Chris Gross chris.gross@us.ibm.com Bug 107443
13
 *     Dakshinamurthy Karra (Jalian Systems) - Templates View - https://bugs.eclipse.org/bugs/show_bug.cgi?id=69581
13
 *******************************************************************************/
14
 *******************************************************************************/
14
package org.eclipse.ui;
15
package org.eclipse.ui;
15
16
Lines 92-97 Link Here
92
    public static String ID_OUTLINE = "org.eclipse.ui.views.ContentOutline"; //$NON-NLS-1$
93
    public static String ID_OUTLINE = "org.eclipse.ui.views.ContentOutline"; //$NON-NLS-1$
93
94
94
    /**
95
    /**
96
     * The view id for the workbench's Templates standard component.
97
     */
98
    public static String ID_TEMPLATES = "org.eclipse.ui.views.Templates"; //$NON-NLS-1$
99
100
    /**
95
     * The view id for the workbench's Bookmark Navigator standard component.
101
     * The view id for the workbench's Bookmark Navigator standard component.
96
     */
102
     */
97
    public static String ID_BOOKMARKS = "org.eclipse.ui.views.BookmarkView"; //$NON-NLS-1$
103
    public static String ID_BOOKMARKS = "org.eclipse.ui.views.BookmarkView"; //$NON-NLS-1$

Return to bug 69581