KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > texteditor > templates > TemplatePreferencePage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation 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  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.texteditor.templates;
12
13 import java.io.BufferedInputStream JavaDoc;
14 import java.io.BufferedOutputStream JavaDoc;
15 import java.io.File JavaDoc;
16 import java.io.FileInputStream JavaDoc;
17 import java.io.FileNotFoundException JavaDoc;
18 import java.io.FileOutputStream JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.io.OutputStream JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import org.eclipse.swt.SWT;
29 import org.eclipse.swt.custom.StyledText;
30 import org.eclipse.swt.custom.VerifyKeyListener;
31 import org.eclipse.swt.events.FocusEvent;
32 import org.eclipse.swt.events.FocusListener;
33 import org.eclipse.swt.events.ModifyEvent;
34 import org.eclipse.swt.events.ModifyListener;
35 import org.eclipse.swt.events.SelectionEvent;
36 import org.eclipse.swt.events.SelectionListener;
37 import org.eclipse.swt.events.VerifyEvent;
38 import org.eclipse.swt.graphics.GC;
39 import org.eclipse.swt.graphics.Image;
40 import org.eclipse.swt.layout.GridData;
41 import org.eclipse.swt.layout.GridLayout;
42 import org.eclipse.swt.widgets.Button;
43 import org.eclipse.swt.widgets.Combo;
44 import org.eclipse.swt.widgets.Composite;
45 import org.eclipse.swt.widgets.Control;
46 import org.eclipse.swt.widgets.Event;
47 import org.eclipse.swt.widgets.FileDialog;
48 import org.eclipse.swt.widgets.Label;
49 import org.eclipse.swt.widgets.Listener;
50 import org.eclipse.swt.widgets.Menu;
51 import org.eclipse.swt.widgets.Shell;
52 import org.eclipse.swt.widgets.Table;
53 import org.eclipse.swt.widgets.TableColumn;
54 import org.eclipse.swt.widgets.Text;
55 import org.eclipse.swt.widgets.Widget;
56
57 import org.eclipse.jface.action.Action;
58 import org.eclipse.jface.action.GroupMarker;
59 import org.eclipse.jface.action.IAction;
60 import org.eclipse.jface.action.IMenuListener;
61 import org.eclipse.jface.action.IMenuManager;
62 import org.eclipse.jface.action.MenuManager;
63 import org.eclipse.jface.action.Separator;
64 import org.eclipse.jface.dialogs.Dialog;
65 import org.eclipse.jface.dialogs.IDialogSettings;
66 import org.eclipse.jface.dialogs.MessageDialog;
67 import org.eclipse.jface.dialogs.StatusDialog;
68 import org.eclipse.jface.preference.IPreferenceStore;
69 import org.eclipse.jface.preference.PreferencePage;
70 import org.eclipse.jface.resource.JFaceResources;
71 import org.eclipse.jface.viewers.CheckStateChangedEvent;
72 import org.eclipse.jface.viewers.CheckboxTableViewer;
73 import org.eclipse.jface.viewers.ColumnPixelData;
74 import org.eclipse.jface.viewers.ColumnWeightData;
75 import org.eclipse.jface.viewers.DoubleClickEvent;
76 import org.eclipse.jface.viewers.ICheckStateListener;
77 import org.eclipse.jface.viewers.IDoubleClickListener;
78 import org.eclipse.jface.viewers.ISelectionChangedListener;
79 import org.eclipse.jface.viewers.IStructuredSelection;
80 import org.eclipse.jface.viewers.ITableLabelProvider;
81 import org.eclipse.jface.viewers.LabelProvider;
82 import org.eclipse.jface.viewers.SelectionChangedEvent;
83 import org.eclipse.jface.viewers.StructuredSelection;
84 import org.eclipse.jface.viewers.TableViewer;
85 import org.eclipse.jface.viewers.Viewer;
86 import org.eclipse.jface.viewers.ViewerComparator;
87 import org.eclipse.jface.window.Window;
88
89 import org.eclipse.jface.text.Document;
90 import org.eclipse.jface.text.IDocument;
91 import org.eclipse.jface.text.ITextListener;
92 import org.eclipse.jface.text.ITextOperationTarget;
93 import org.eclipse.jface.text.ITextViewer;
94 import org.eclipse.jface.text.TextEvent;
95 import org.eclipse.jface.text.contentassist.ContentAssistant;
96 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
97 import org.eclipse.jface.text.contentassist.IContentAssistant;
98 import org.eclipse.jface.text.source.ISourceViewer;
99 import org.eclipse.jface.text.source.SourceViewer;
100 import org.eclipse.jface.text.source.SourceViewerConfiguration;
101 import org.eclipse.jface.text.templates.ContextTypeRegistry;
102 import org.eclipse.jface.text.templates.Template;
103 import org.eclipse.jface.text.templates.TemplateContextType;
104 import org.eclipse.jface.text.templates.TemplateException;
105 import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
106 import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter;
107 import org.eclipse.jface.text.templates.persistence.TemplateStore;
108
109 import org.eclipse.ui.IWorkbench;
110 import org.eclipse.ui.IWorkbenchPreferencePage;
111 import org.eclipse.ui.internal.texteditor.NLSUtility;
112 import org.eclipse.ui.internal.texteditor.TextEditorPlugin;
113 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
114 import org.eclipse.ui.texteditor.IUpdate;
115
116 /**
117  * A template preference page allows configuration of the templates for an
118  * editor. It provides controls for adding, removing and changing templates as
119  * well as enablement, default management and an optional formatter preference.
120  * <p>
121  * Subclasses need to provide a {@link TemplateStore} and a
122  * {@link ContextTypeRegistry} and should set the preference store. They may
123  * optionally override {@link #isShowFormatterSetting()}.
124  * </p>
125  *
126  * @since 3.0
127  */

128 public abstract class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
129
130     
131     /**
132      * Dialog to edit a template. Clients will usually instantiate, but
133      * may also extend.
134      *
135      * @since 3.3
136      */

137     protected static class EditTemplateDialog extends StatusDialog {
138
139         private class TextViewerAction extends Action implements IUpdate {
140
141             private int fOperationCode= -1;
142             private ITextOperationTarget fOperationTarget;
143
144             /**
145              * Creates a new action.
146              *
147              * @param viewer the viewer
148              * @param operationCode the opcode
149              */

150             public TextViewerAction(ITextViewer viewer, int operationCode) {
151                 fOperationCode= operationCode;
152                 fOperationTarget= viewer.getTextOperationTarget();
153                 update();
154             }
155
156             /**
157              * Updates the enabled state of the action.
158              * Fires a property change if the enabled state changes.
159              *
160              * @see Action#firePropertyChange(String, Object, Object)
161              */

162             public void update() {
163
164                 boolean wasEnabled= isEnabled();
165                 boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
166                 setEnabled(isEnabled);
167
168                 if (wasEnabled != isEnabled) {
169                     firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
170                 }
171             }
172
173             /**
174              * @see Action#run()
175              */

176             public void run() {
177                 if (fOperationCode != -1 && fOperationTarget != null) {
178                     fOperationTarget.doOperation(fOperationCode);
179                 }
180             }
181         }
182
183         private final Template fOriginalTemplate;
184
185         private Text fNameText;
186         private Text fDescriptionText;
187         private Combo fContextCombo;
188         private SourceViewer fPatternEditor;
189         private Button fInsertVariableButton;
190         private Button fAutoInsertCheckbox;
191         private boolean fIsNameModifiable;
192
193         private StatusInfo fValidationStatus;
194         private boolean fSuppressError= true; // #4354
195
private Map JavaDoc fGlobalActions= new HashMap JavaDoc(10);
196         private List JavaDoc fSelectionActions = new ArrayList JavaDoc(3);
197         private String JavaDoc[][] fContextTypes;
198
199         private ContextTypeRegistry fContextTypeRegistry;
200
201         private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor();
202
203         private Template fNewTemplate;
204
205         /**
206          * Creates a new dialog.
207          *
208          * @param parent the shell parent of the dialog
209          * @param template the template to edit
210          * @param edit whether this is a new template or an existing being edited
211          * @param isNameModifiable whether the name of the template may be modified
212          * @param registry the context type registry to use
213          */

214         public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, ContextTypeRegistry registry) {
215             super(parent);
216
217             setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
218
219             String JavaDoc title= edit
220                 ? TextEditorTemplateMessages.EditTemplateDialog_title_edit
221                 : TextEditorTemplateMessages.EditTemplateDialog_title_new;
222             setTitle(title);
223
224             fOriginalTemplate= template;
225             fIsNameModifiable= isNameModifiable;
226
227             List JavaDoc contexts= new ArrayList JavaDoc();
228             for (Iterator JavaDoc it= registry.contextTypes(); it.hasNext();) {
229                 TemplateContextType type= (TemplateContextType) it.next();
230                 contexts.add(new String JavaDoc[] { type.getId(), type.getName() });
231             }
232             fContextTypes= (String JavaDoc[][]) contexts.toArray(new String JavaDoc[contexts.size()][]);
233
234             fValidationStatus= new StatusInfo();
235
236             fContextTypeRegistry= registry;
237
238             TemplateContextType type= fContextTypeRegistry.getContextType(template.getContextTypeId());
239             fTemplateProcessor.setContextType(type);
240         }
241
242         /*
243          * @see org.eclipse.ui.texteditor.templates.StatusDialog#create()
244          */

245         public void create() {
246             super.create();
247             // update initial OK button to be disabled for new templates
248
boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
249             if (!valid) {
250                 StatusInfo status = new StatusInfo();
251                 status.setError(TextEditorTemplateMessages.EditTemplateDialog_error_noname);
252                 updateButtonsEnableState(status);
253             }
254         }
255
256         /*
257          * @see Dialog#createDialogArea(Composite)
258          */

259         protected Control createDialogArea(Composite ancestor) {
260             Composite parent= new Composite(ancestor, SWT.NONE);
261             GridLayout layout= new GridLayout();
262             layout.numColumns= 2;
263             parent.setLayout(layout);
264             parent.setLayoutData(new GridData(GridData.FILL_BOTH));
265
266             ModifyListener listener= new ModifyListener() {
267                 public void modifyText(ModifyEvent e) {
268                     doTextWidgetChanged(e.widget);
269                 }
270             };
271
272             if (fIsNameModifiable) {
273                 createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_name);
274
275                 Composite composite= new Composite(parent, SWT.NONE);
276                 composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
277                 layout= new GridLayout();
278                 layout.numColumns= 4;
279                 layout.marginWidth= 0;
280                 layout.marginHeight= 0;
281                 composite.setLayout(layout);
282
283                 fNameText= createText(composite);
284                 fNameText.addModifyListener(listener);
285                 fNameText.addFocusListener(new FocusListener() {
286
287                     public void focusGained(FocusEvent e) {
288                     }
289
290                     public void focusLost(FocusEvent e) {
291                         if (fSuppressError) {
292                             fSuppressError= false;
293                             updateButtons();
294                         }
295                     }
296                 });
297
298                 createLabel(composite, TextEditorTemplateMessages.EditTemplateDialog_context);
299                 fContextCombo= new Combo(composite, SWT.READ_ONLY);
300
301                 for (int i= 0; i < fContextTypes.length; i++) {
302                     fContextCombo.add(fContextTypes[i][1]);
303                 }
304
305                 fContextCombo.addModifyListener(listener);
306                 
307                 fAutoInsertCheckbox= createCheckbox(composite, TextEditorTemplateMessages.EditTemplateDialog_autoinsert);
308                 fAutoInsertCheckbox.setSelection(fOriginalTemplate.isAutoInsertable());
309             }
310
311             createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_description);
312
313             int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY;
314             fDescriptionText= new Text(parent, descFlags );
315             fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
316
317             fDescriptionText.addModifyListener(listener);
318
319             Label patternLabel= createLabel(parent, TextEditorTemplateMessages.EditTemplateDialog_pattern);
320             patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
321             fPatternEditor= createEditor(parent, fOriginalTemplate.getPattern());
322
323             Label filler= new Label(parent, SWT.NONE);
324             filler.setLayoutData(new GridData());
325
326             Composite composite= new Composite(parent, SWT.NONE);
327             layout= new GridLayout();
328             layout.marginWidth= 0;
329             layout.marginHeight= 0;
330             composite.setLayout(layout);
331             composite.setLayoutData(new GridData());
332
333             fInsertVariableButton= new Button(composite, SWT.NONE);
334             fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton));
335             fInsertVariableButton.setText(TextEditorTemplateMessages.EditTemplateDialog_insert_variable);
336             fInsertVariableButton.addSelectionListener(new SelectionListener() {
337                 public void widgetSelected(SelectionEvent e) {
338                     fPatternEditor.getTextWidget().setFocus();
339                     fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
340                 }
341
342                 public void widgetDefaultSelected(SelectionEvent e) {}
343             });
344
345             fDescriptionText.setText(fOriginalTemplate.getDescription());
346             if (fIsNameModifiable) {
347                 fNameText.setText(fOriginalTemplate.getName());
348                 fNameText.addModifyListener(listener);
349                 fContextCombo.select(getIndex(fOriginalTemplate.getContextTypeId()));
350             } else {
351                 fPatternEditor.getControl().setFocus();
352             }
353             initializeActions();
354
355             applyDialogFont(parent);
356             return composite;
357         }
358
359         private void doTextWidgetChanged(Widget w) {
360             if (w == fNameText) {
361                 fSuppressError= false;
362                 updateButtons();
363             } else if (w == fContextCombo) {
364                 String JavaDoc contextId= getContextId();
365                 fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId));
366             } else if (w == fDescriptionText) {
367                 // oh, nothing
368
}
369         }
370
371         private String JavaDoc getContextId() {
372             if (fContextCombo != null && !fContextCombo.isDisposed()) {
373                 String JavaDoc name= fContextCombo.getText();
374                 for (int i= 0; i < fContextTypes.length; i++) {
375                     if (name.equals(fContextTypes[i][1])) {
376                         return fContextTypes[i][0];
377                     }
378                 }
379             }
380
381             return fOriginalTemplate.getContextTypeId();
382         }
383
384         private void doSourceChanged(IDocument document) {
385             String JavaDoc text= document.get();
386             fValidationStatus.setOK();
387             TemplateContextType contextType= fContextTypeRegistry.getContextType(getContextId());
388             if (contextType != null) {
389                 try {
390                     contextType.validate(text);
391                 } catch (TemplateException e) {
392                     fValidationStatus.setError(e.getLocalizedMessage());
393                 }
394             }
395
396             updateUndoAction();
397             updateButtons();
398         }
399
400         private static GridData getButtonGridData(Button button) {
401             GridData data= new GridData(GridData.FILL_HORIZONTAL);
402             // TODO get some button hints.
403
// data.heightHint= SWTUtil.getButtonHeightHint(button);
404

405             return data;
406         }
407
408         private static Label createLabel(Composite parent, String JavaDoc name) {
409             Label label= new Label(parent, SWT.NULL);
410             label.setText(name);
411             label.setLayoutData(new GridData());
412
413             return label;
414         }
415
416         private static Text createText(Composite parent) {
417             Text text= new Text(parent, SWT.BORDER);
418             text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
419
420             return text;
421         }
422
423         private static Button createCheckbox(Composite parent, String JavaDoc name) {
424             Button button= new Button(parent, SWT.CHECK);
425             button.setText(name);
426             button.setLayoutData(new GridData());
427             
428             return button;
429         }
430         
431         private SourceViewer createEditor(Composite parent, String JavaDoc pattern) {
432             SourceViewer viewer= createViewer(parent);
433             viewer.setEditable(true);
434             
435             IDocument document= viewer.getDocument();
436             if (document != null)
437                 document.set(pattern);
438             else {
439                 document= new Document(pattern);
440                 viewer.setDocument(document);
441             }
442
443             int nLines= document.getNumberOfLines();
444             if (nLines < 5) {
445                 nLines= 5;
446             } else if (nLines > 12) {
447                 nLines= 12;
448             }
449
450             Control control= viewer.getControl();
451             GridData data= new GridData(GridData.FILL_BOTH);
452             data.widthHint= convertWidthInCharsToPixels(80);
453             data.heightHint= convertHeightInCharsToPixels(nLines);
454             control.setLayoutData(data);
455
456             viewer.addTextListener(new ITextListener() {
457                 public void textChanged(TextEvent event) {
458                     if (event .getDocumentEvent() != null)
459                         doSourceChanged(event.getDocumentEvent().getDocument());
460                 }
461             });
462
463             viewer.addSelectionChangedListener(new ISelectionChangedListener() {
464                 public void selectionChanged(SelectionChangedEvent event) {
465                     updateSelectionDependentActions();
466                 }
467             });
468
469             viewer.prependVerifyKeyListener(new VerifyKeyListener() {
470                 public void verifyKey(VerifyEvent event) {
471                     handleVerifyKeyPressed(event);
472                 }
473             });
474
475             return viewer;
476         }
477
478         /**
479          * Creates the viewer to be used to display the pattern. Subclasses may override.
480          *
481          * @param parent the parent composite of the viewer
482          * @return a configured <code>SourceViewer</code>
483          */

484         protected SourceViewer createViewer(Composite parent) {
485             SourceViewer viewer= new SourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
486             SourceViewerConfiguration configuration= new SourceViewerConfiguration() {
487                 public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
488
489                     ContentAssistant assistant= new ContentAssistant();
490                     assistant.enableAutoActivation(true);
491                     assistant.enableAutoInsert(true);
492                     assistant.setContentAssistProcessor(fTemplateProcessor, IDocument.DEFAULT_CONTENT_TYPE);
493                     return assistant;
494                 }
495             };
496             viewer.configure(configuration);
497             return viewer;
498         }
499
500         private void handleVerifyKeyPressed(VerifyEvent event) {
501             if (!event.doit)
502                 return;
503
504             if (event.stateMask != SWT.MOD1)
505                 return;
506
507             switch (event.character) {
508                 case ' ':
509                     fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
510                     event.doit= false;
511                     break;
512
513                 // CTRL-Z
514
case 'z' - 'a' + 1:
515                     fPatternEditor.doOperation(ITextOperationTarget.UNDO);
516                     event.doit= false;
517                     break;
518             }
519         }
520
521         private void initializeActions() {
522             TextViewerAction action= new TextViewerAction(fPatternEditor, ITextOperationTarget.UNDO);
523             action.setText(TextEditorTemplateMessages.EditTemplateDialog_undo);
524             fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
525
526             action= new TextViewerAction(fPatternEditor, ITextOperationTarget.CUT);
527             action.setText(TextEditorTemplateMessages.EditTemplateDialog_cut);
528             fGlobalActions.put(ITextEditorActionConstants.CUT, action);
529
530             action= new TextViewerAction(fPatternEditor, ITextOperationTarget.COPY);
531             action.setText(TextEditorTemplateMessages.EditTemplateDialog_copy);
532             fGlobalActions.put(ITextEditorActionConstants.COPY, action);
533
534             action= new TextViewerAction(fPatternEditor, ITextOperationTarget.PASTE);
535             action.setText(TextEditorTemplateMessages.EditTemplateDialog_paste);
536             fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
537
538             action= new TextViewerAction(fPatternEditor, ITextOperationTarget.SELECT_ALL);
539             action.setText(TextEditorTemplateMessages.EditTemplateDialog_select_all);
540             fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
541
542             action= new TextViewerAction(fPatternEditor, ISourceViewer.CONTENTASSIST_PROPOSALS);
543             action.setText(TextEditorTemplateMessages.EditTemplateDialog_content_assist);
544             fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
545

546             fSelectionActions.add(ITextEditorActionConstants.CUT);
547             fSelectionActions.add(ITextEditorActionConstants.COPY);
548             fSelectionActions.add(ITextEditorActionConstants.PASTE);
549
550             // create context menu
551
MenuManager manager= new MenuManager(null, null);
552             manager.setRemoveAllWhenShown(true);
553             manager.addMenuListener(new IMenuListener() {
554                 public void menuAboutToShow(IMenuManager mgr) {
555                     fillContextMenu(mgr);
556                 }
557             });
558
559             StyledText text= fPatternEditor.getTextWidget();
560             Menu menu= manager.createContextMenu(text);
561             text.setMenu(menu);
562         }
563
564         private void fillContextMenu(IMenuManager menu) {
565             menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
566             menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
567
568             menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
569             menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
570             menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
571             menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
572             menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
573
574             menu.add(new Separator("templates")); //$NON-NLS-1$
575
menu.appendToGroup("templates", (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ //$NON-NLS-2$
576
}
577
578         private void updateSelectionDependentActions() {
579             Iterator JavaDoc iterator= fSelectionActions.iterator();
580             while (iterator.hasNext())
581                 updateAction((String JavaDoc)iterator.next());
582         }
583
584         private void updateUndoAction() {
585             IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
586             if (action instanceof IUpdate)
587                 ((IUpdate) action).update();
588         }
589
590         private void updateAction(String JavaDoc actionId) {
591             IAction action= (IAction) fGlobalActions.get(actionId);
592             if (action instanceof IUpdate)
593                 ((IUpdate) action).update();
594         }
595
596         private int getIndex(String JavaDoc contextid) {
597
598             if (contextid == null)
599                 return -1;
600
601             for (int i= 0; i < fContextTypes.length; i++) {
602                 if (contextid.equals(fContextTypes[i][0])) {
603                     return i;
604                 }
605             }
606             return -1;
607         }
608
609         private void updateButtons() {
610             StatusInfo status;
611
612             boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
613             if (!valid) {
614                 status = new StatusInfo();
615                 if (!fSuppressError) {
616                     status.setError(TextEditorTemplateMessages.EditTemplateDialog_error_noname);
617                 }
618             } else {
619                 status= fValidationStatus;
620             }
621             updateStatus(status);
622         }
623
624         /*
625          * @since 3.1
626          */

627         protected void okPressed() {
628             String JavaDoc name= fNameText == null ? fOriginalTemplate.getName() : fNameText.getText();
629             boolean isAutoInsertable= fAutoInsertCheckbox != null && fAutoInsertCheckbox.getSelection();
630             fNewTemplate= new Template(name, fDescriptionText.getText(), getContextId(), fPatternEditor.getDocument().get(), isAutoInsertable);
631             super.okPressed();
632         }
633
634         /**
635          * Returns the created template.
636          *
637          * @return the created template
638          * @since 3.1
639          */

640         public Template getTemplate() {
641             return fNewTemplate;
642         }
643         
644         /**
645          * Returns the content assist processor that
646          * suggests template variables.
647          *
648          * @return the processor to suggest variables
649          * @since 3.3
650          */

651         protected IContentAssistProcessor getTemplateProcessor() {
652             return fTemplateProcessor;
653         }
654
655         /*
656          * @see org.eclipse.jface.dialogs.Dialog#getDialogBoundsSettings()
657          * @since 3.2
658          */

659         protected IDialogSettings getDialogBoundsSettings() {
660             String JavaDoc sectionName= getClass().getName() + "_dialogBounds"; //$NON-NLS-1$
661
IDialogSettings settings= TextEditorPlugin.getDefault().getDialogSettings();
662             IDialogSettings section= settings.getSection(sectionName);
663             if (section == null)
664                 section= settings.addNewSection(sectionName);
665             return section;
666         }
667
668     }
669     
670     
671     /**
672      * Label provider for templates.
673      */

674     private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {
675
676         /*
677          * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
678          */

679         public Image getColumnImage(Object JavaDoc element, int columnIndex) {
680             return null;
681         }
682
683         /*
684          * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
685          */

686         public String JavaDoc getColumnText(Object JavaDoc element, int columnIndex) {
687             TemplatePersistenceData data = (TemplatePersistenceData) element;
688             Template template= data.getTemplate();
689
690             switch (columnIndex) {
691                 case 0:
692                     return template.getName();
693                 case 1:
694                     TemplateContextType type= fContextTypeRegistry.getContextType(template.getContextTypeId());
695                     if (type != null)
696                         return type.getName();
697                     return template.getContextTypeId();
698                 case 2:
699                     return template.getDescription();
700                 case 3:
701                     return template.isAutoInsertable() ? TextEditorTemplateMessages.TemplatePreferencePage_on : ""; //$NON-NLS-1$
702
default:
703                     return ""; //$NON-NLS-1$
704
}
705         }
706     }
707
708
709     /** Qualified key for formatter preference. */
710     private static final String JavaDoc DEFAULT_FORMATTER_PREFERENCE_KEY= "org.eclipse.ui.texteditor.templates.preferences.format_templates"; //$NON-NLS-1$
711

712     /** The table presenting the templates. */
713     private CheckboxTableViewer fTableViewer;
714
715     /* buttons */
716     private Button fAddButton;
717     private Button fEditButton;
718     private Button fImportButton;
719     private Button fExportButton;
720     private Button fRemoveButton;
721     private Button fRestoreButton;
722     private Button fRevertButton;
723
724     /** The viewer displays the pattern of selected template. */
725     private SourceViewer fPatternViewer;
726     /** Format checkbox. This gets conditionally added. */
727     private Button fFormatButton;
728     /** The store for our templates. */
729     private TemplateStore fTemplateStore;
730     /** The context type registry. */
731     private ContextTypeRegistry fContextTypeRegistry;
732
733
734     /**
735      * Creates a new template preference page.
736      */

737     protected TemplatePreferencePage() {
738         super();
739
740         setDescription(TextEditorTemplateMessages.TemplatePreferencePage_message);
741     }
742
743     /**
744      * Returns the template store.
745      *
746      * @return the template store
747      */

748     public TemplateStore getTemplateStore() {
749         return fTemplateStore;
750     }
751
752     /**
753      * Returns the context type registry.
754      *
755      * @return the context type registry
756      */

757     public ContextTypeRegistry getContextTypeRegistry() {
758         return fContextTypeRegistry;
759     }
760
761     /**
762      * Sets the template store.
763      *
764      * @param store the new template store
765      */

766     public void setTemplateStore(TemplateStore store) {
767         fTemplateStore= store;
768     }
769
770     /**
771      * Sets the context type registry.
772      *
773      * @param registry the new context type registry
774      */

775     public void setContextTypeRegistry(ContextTypeRegistry registry) {
776         fContextTypeRegistry= registry;
777     }
778
779     /*
780      * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
781      */

782     public void init(IWorkbench workbench) {
783     }
784
785     /*
786      * @see PreferencePage#createContents(Composite)
787      */

788     protected Control createContents(Composite ancestor) {
789         Composite parent= new Composite(ancestor, SWT.NONE);
790         GridLayout layout= new GridLayout();
791         layout.numColumns= 2;
792         layout.marginHeight= 0;
793         layout.marginWidth= 0;
794         parent.setLayout(layout);
795
796         Composite innerParent= new Composite(parent, SWT.NONE);
797         GridLayout innerLayout= new GridLayout();
798         innerLayout.numColumns= 2;
799         innerLayout.marginHeight= 0;
800         innerLayout.marginWidth= 0;
801         innerParent.setLayout(innerLayout);
802         GridData gd= new GridData(GridData.FILL_BOTH);
803         gd.horizontalSpan= 2;
804         innerParent.setLayoutData(gd);
805
806         Composite tableComposite= new Composite(innerParent, SWT.NONE);
807         GridData data= new GridData(GridData.FILL_BOTH);
808         data.widthHint= 360;
809         data.heightHint= convertHeightInCharsToPixels(10);
810         tableComposite.setLayoutData(data);
811         
812         ColumnLayout columnLayout= new ColumnLayout();
813         tableComposite.setLayout(columnLayout);
814         Table table= new Table(tableComposite, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
815
816         table.setHeaderVisible(true);
817         table.setLinesVisible(true);
818
819         GC gc= new GC(getShell());
820         gc.setFont(JFaceResources.getDialogFont());
821         
822         TableColumn column1= new TableColumn(table, SWT.NONE);
823         column1.setText(TextEditorTemplateMessages.TemplatePreferencePage_column_name);
824         int minWidth= computeMinimumColumnWidth(gc, TextEditorTemplateMessages.TemplatePreferencePage_column_name);
825         columnLayout.addColumnData(new ColumnWeightData(2, minWidth, true));
826
827         TableColumn column2= new TableColumn(table, SWT.NONE);
828         column2.setText(TextEditorTemplateMessages.TemplatePreferencePage_column_context);
829         minWidth= computeMinimumColumnWidth(gc, TextEditorTemplateMessages.TemplatePreferencePage_column_context);
830         columnLayout.addColumnData(new ColumnWeightData(1, minWidth, true));
831
832         TableColumn column3= new TableColumn(table, SWT.NONE);
833         column3.setText(TextEditorTemplateMessages.TemplatePreferencePage_column_description);
834         minWidth= computeMinimumColumnWidth(gc, TextEditorTemplateMessages.TemplatePreferencePage_column_description);
835         columnLayout.addColumnData(new ColumnWeightData(3, minWidth, true));
836
837         TableColumn column4= new TableColumn(table, SWT.NONE);
838         column4.setAlignment(SWT.CENTER);
839         column4.setText(TextEditorTemplateMessages.TemplatePreferencePage_column_autoinsert);
840         minWidth= computeMinimumColumnWidth(gc, TextEditorTemplateMessages.TemplatePreferencePage_column_autoinsert);
841         minWidth= Math.max(minWidth, computeMinimumColumnWidth(gc, TextEditorTemplateMessages.TemplatePreferencePage_on));
842         columnLayout.addColumnData(new ColumnPixelData(minWidth, false, false));
843         
844         gc.dispose();
845
846         fTableViewer= new CheckboxTableViewer(table);
847         fTableViewer.setLabelProvider(new TemplateLabelProvider());
848         fTableViewer.setContentProvider(new TemplateContentProvider());
849
850         fTableViewer.setComparator(new ViewerComparator() {
851             public int compare(Viewer viewer, Object JavaDoc object1, Object JavaDoc object2) {
852                 if ((object1 instanceof TemplatePersistenceData) && (object2 instanceof TemplatePersistenceData)) {
853                     Template left= ((TemplatePersistenceData) object1).getTemplate();
854                     Template right= ((TemplatePersistenceData) object2).getTemplate();
855                     int result= left.getName().compareToIgnoreCase(right.getName());
856                     if (result != 0)
857                         return result;
858                     return left.getDescription().compareToIgnoreCase(right.getDescription());
859                 }
860                 return super.compare(viewer, object1, object2);
861             }
862
863             public boolean isSorterProperty(Object JavaDoc element, String JavaDoc property) {
864                 return true;
865             }
866         });
867
868         fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
869             public void doubleClick(DoubleClickEvent e) {
870                 edit();
871             }
872         });
873
874         fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
875             public void selectionChanged(SelectionChangedEvent e) {
876                 selectionChanged1();
877             }
878         });
879
880         fTableViewer.addCheckStateListener(new ICheckStateListener() {
881             public void checkStateChanged(CheckStateChangedEvent event) {
882                 TemplatePersistenceData d= (TemplatePersistenceData) event.getElement();
883                 d.setEnabled(event.getChecked());
884             }
885         });
886
887         Composite buttons= new Composite(innerParent, SWT.NONE);
888         buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
889         layout= new GridLayout();
890         layout.marginHeight= 0;
891         layout.marginWidth= 0;
892         buttons.setLayout(layout);
893
894         fAddButton= new Button(buttons, SWT.PUSH);
895         fAddButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_new);
896         fAddButton.setLayoutData(getButtonGridData(fAddButton));
897         fAddButton.addListener(SWT.Selection, new Listener() {
898             public void handleEvent(Event e) {
899                 add();
900             }
901         });
902
903         fEditButton= new Button(buttons, SWT.PUSH);
904         fEditButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_edit);
905         fEditButton.setLayoutData(getButtonGridData(fEditButton));
906         fEditButton.addListener(SWT.Selection, new Listener() {
907             public void handleEvent(Event e) {
908                 edit();
909             }
910         });
911
912         fRemoveButton= new Button(buttons, SWT.PUSH);
913         fRemoveButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_remove);
914         fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton));
915         fRemoveButton.addListener(SWT.Selection, new Listener() {
916             public void handleEvent(Event e) {
917                 remove();
918             }
919         });
920
921         createSeparator(buttons);
922
923         fRestoreButton= new Button(buttons, SWT.PUSH);
924         fRestoreButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_restore);
925         fRestoreButton.setLayoutData(getButtonGridData(fRestoreButton));
926         fRestoreButton.addListener(SWT.Selection, new Listener() {
927             public void handleEvent(Event e) {
928                 restoreDeleted();
929             }
930         });
931
932         fRevertButton= new Button(buttons, SWT.PUSH);
933         fRevertButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_revert);
934         fRevertButton.setLayoutData(getButtonGridData(fRevertButton));
935         fRevertButton.addListener(SWT.Selection, new Listener() {
936             public void handleEvent(Event e) {
937                 revert();
938             }
939         });
940
941         createSeparator(buttons);
942
943         fImportButton= new Button(buttons, SWT.PUSH);
944         fImportButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_import);
945         fImportButton.setLayoutData(getButtonGridData(fImportButton));
946         fImportButton.addListener(SWT.Selection, new Listener() {
947             public void handleEvent(Event e) {
948                 import_();
949             }
950         });
951
952         fExportButton= new Button(buttons, SWT.PUSH);
953         fExportButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_export);
954         fExportButton.setLayoutData(getButtonGridData(fExportButton));
955         fExportButton.addListener(SWT.Selection, new Listener() {
956             public void handleEvent(Event e) {
957                 export();
958             }
959         });
960
961         fPatternViewer= doCreateViewer(parent);
962
963         if (isShowFormatterSetting()) {
964             fFormatButton= new Button(parent, SWT.CHECK);
965             fFormatButton.setText(TextEditorTemplateMessages.TemplatePreferencePage_use_code_formatter);
966             GridData gd1= new GridData();
967             gd1.horizontalSpan= 2;
968             fFormatButton.setLayoutData(gd1);
969             fFormatButton.setSelection(getPreferenceStore().getBoolean(getFormatterPreferenceKey()));
970         }
971
972         fTableViewer.setInput(fTemplateStore);
973         fTableViewer.setAllChecked(false);
974         fTableViewer.setCheckedElements(getEnabledTemplates());
975
976         updateButtons();
977         Dialog.applyDialogFont(parent);
978         innerParent.layout();
979         
980         return parent;
981     }
982
983     /*
984      * @since 3.2
985      */

986     private int computeMinimumColumnWidth(GC gc, String JavaDoc string) {
987         return gc.stringExtent(string).x + 10; // pad 10 to accommodate table header trimmings
988
}
989
990     /**
991      * Creates a separator between buttons
992      * @param parent
993      * @return a separator
994      */

995     private Label createSeparator(Composite parent) {
996         Label separator= new Label(parent, SWT.NONE);
997         separator.setVisible(false);
998         GridData gd= new GridData();
999         gd.horizontalAlignment= GridData.FILL;
1000        gd.verticalAlignment= GridData.BEGINNING;
1001        gd.heightHint= 4;
1002        separator.setLayoutData(gd);
1003        return separator;
1004    }
1005
1006    /**
1007     * Returns whether the formatter preference checkbox should be shown.
1008     *
1009     * @return <code>true</code> if the formatter preference checkbox should
1010     * be shown, <code>false</code> otherwise
1011     */

1012    protected boolean isShowFormatterSetting() {
1013        return true;
1014    }
1015
1016    private TemplatePersistenceData[] getEnabledTemplates() {
1017        List JavaDoc enabled= new ArrayList JavaDoc();
1018        TemplatePersistenceData[] datas= fTemplateStore.getTemplateData(false);
1019        for (int i= 0; i < datas.length; i++) {
1020            if (datas[i].isEnabled())
1021                enabled.add(datas[i]);
1022        }
1023        return (TemplatePersistenceData[]) enabled.toArray(new TemplatePersistenceData[enabled.size()]);
1024    }
1025
1026    private SourceViewer doCreateViewer(Composite parent) {
1027        Label label= new Label(parent, SWT.NONE);
1028        label.setText(TextEditorTemplateMessages.TemplatePreferencePage_preview);
1029        GridData data= new GridData();
1030        data.horizontalSpan= 2;
1031        label.setLayoutData(data);
1032
1033        SourceViewer viewer= createViewer(parent);
1034        viewer.setEditable(false);
1035
1036        Control control= viewer.getControl();
1037        data= new GridData(GridData.FILL_BOTH);
1038        data.horizontalSpan= 2;
1039        data.heightHint= convertHeightInCharsToPixels(5);
1040        control.setLayoutData(data);
1041
1042        return viewer;
1043    }
1044
1045    /**
1046     * Creates, configures and returns a source viewer to present the template
1047     * pattern on the preference page. Clients may override to provide a custom
1048     * source viewer featuring e.g. syntax coloring.
1049     *
1050     * @param parent the parent control
1051     * @return a configured source viewer
1052     */

1053    protected SourceViewer createViewer(Composite parent) {
1054        SourceViewer viewer= new SourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
1055        SourceViewerConfiguration configuration= new SourceViewerConfiguration();
1056        viewer.configure(configuration);
1057        IDocument document= new Document();
1058        viewer.setDocument(document);
1059        return viewer;
1060    }
1061
1062    private static GridData getButtonGridData(Button button) {
1063        GridData data= new GridData(GridData.FILL_HORIZONTAL);
1064        // TODO replace SWTUtil
1065
// data.widthHint= SWTUtil.getButtonWidthHint(button);
1066
// data.heightHint= SWTUtil.getButtonHeightHint(button);
1067

1068        return data;
1069    }
1070
1071    private void selectionChanged1() {
1072        updateViewerInput();
1073
1074        updateButtons();
1075    }
1076
1077    /**
1078     * Updates the pattern viewer.
1079     */

1080    protected void updateViewerInput() {
1081        IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1082
1083        if (selection.size() == 1) {
1084            TemplatePersistenceData data= (TemplatePersistenceData) selection.getFirstElement();
1085            Template template= data.getTemplate();
1086            fPatternViewer.getDocument().set(template.getPattern());
1087        } else {
1088            fPatternViewer.getDocument().set(""); //$NON-NLS-1$
1089
}
1090    }
1091
1092    /**
1093     * Updates the buttons.
1094     */

1095    protected void updateButtons() {
1096        IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1097        int selectionCount= selection.size();
1098        int itemCount= fTableViewer.getTable().getItemCount();
1099        boolean canRestore= fTemplateStore.getTemplateData(true).length != fTemplateStore.getTemplateData(false).length;
1100        boolean canRevert= false;
1101        for (Iterator JavaDoc it= selection.iterator(); it.hasNext();) {
1102            TemplatePersistenceData data= (TemplatePersistenceData) it.next();
1103            if (data.isModified()) {
1104                canRevert= true;
1105                break;
1106            }
1107        }
1108
1109        fEditButton.setEnabled(selectionCount == 1);
1110        fExportButton.setEnabled(selectionCount > 0);
1111        fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount);
1112        fRestoreButton.setEnabled(canRestore);
1113        fRevertButton.setEnabled(canRevert);
1114    }
1115
1116    private void add() {
1117
1118        Iterator JavaDoc it= fContextTypeRegistry.contextTypes();
1119        if (it.hasNext()) {
1120            Template template= new Template("", "", ((TemplateContextType) it.next()).getId(), "", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1121

1122            Template newTemplate= editTemplate(template, false, true);
1123            if (newTemplate != null) {
1124                TemplatePersistenceData data= new TemplatePersistenceData(newTemplate, true);
1125                fTemplateStore.add(data);
1126                fTableViewer.refresh();
1127                fTableViewer.setChecked(data, true);
1128                fTableViewer.setSelection(new StructuredSelection(data));
1129            }
1130        }
1131    }
1132
1133    /**
1134     * Creates the edit dialog. Subclasses may override this method to provide a
1135     * custom dialog.
1136     *
1137     * @param template the template being edited
1138     * @param edit whether the dialog should be editable
1139     * @param isNameModifiable whether the template name may be modified
1140     * @return an <code>EditTemplateDialog</code> which will be opened.
1141     * @deprecated not called any longer as of 3.1 - use {@link #editTemplate(Template, boolean, boolean)}
1142     */

1143    protected Dialog createTemplateEditDialog(Template template, boolean edit, boolean isNameModifiable) {
1144        return new EditTemplateDialog(getShell(), template, edit, isNameModifiable, fContextTypeRegistry);
1145    }
1146
1147    /**
1148     * Creates the edit dialog. Subclasses may override this method to provide a
1149     * custom dialog.
1150     *
1151     * @param template the template being edited
1152     * @param edit whether the dialog should be editable
1153     * @param isNameModifiable whether the template name may be modified
1154     * @return the created or modified template, or <code>null</code> if the edition failed
1155     * @since 3.1
1156     */

1157    protected Template editTemplate(Template template, boolean edit, boolean isNameModifiable) {
1158        EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, edit, isNameModifiable, fContextTypeRegistry);
1159        if (dialog.open() == Window.OK) {
1160            return dialog.getTemplate();
1161        }
1162        return null;
1163    }
1164
1165    private void edit() {
1166        IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1167
1168        Object JavaDoc[] objects= selection.toArray();
1169        if ((objects == null) || (objects.length != 1))
1170            return;
1171
1172        TemplatePersistenceData data= (TemplatePersistenceData) selection.getFirstElement();
1173        edit(data);
1174    }
1175
1176    private void edit(TemplatePersistenceData data) {
1177        Template oldTemplate= data.getTemplate();
1178        Template newTemplate= editTemplate(new Template(oldTemplate), true, true);
1179        if (newTemplate != null) {
1180
1181            if (!newTemplate.getName().equals(oldTemplate.getName()) &&
1182                MessageDialog.openQuestion(getShell(),
1183                TextEditorTemplateMessages.TemplatePreferencePage_question_create_new_title,
1184                TextEditorTemplateMessages.TemplatePreferencePage_question_create_new_message))
1185            {
1186                data= new TemplatePersistenceData(newTemplate, true);
1187                fTemplateStore.add(data);
1188                fTableViewer.refresh();
1189            } else {
1190                data.setTemplate(newTemplate);
1191                fTableViewer.refresh(data);
1192            }
1193            selectionChanged1();
1194            fTableViewer.setChecked(data, data.isEnabled());
1195            fTableViewer.setSelection(new StructuredSelection(data));
1196        }
1197    }
1198
1199    private void import_() {
1200        FileDialog dialog= new FileDialog(getShell());
1201        dialog.setText(TextEditorTemplateMessages.TemplatePreferencePage_import_title);
1202        dialog.setFilterExtensions(new String JavaDoc[] {TextEditorTemplateMessages.TemplatePreferencePage_import_extension});
1203        String JavaDoc path= dialog.open();
1204
1205        if (path == null)
1206            return;
1207
1208        try {
1209            TemplateReaderWriter reader= new TemplateReaderWriter();
1210            File JavaDoc file= new File JavaDoc(path);
1211            if (file.exists()) {
1212                InputStream JavaDoc input= new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(file));
1213                try {
1214                    TemplatePersistenceData[] datas= reader.read(input, null);
1215                    for (int i= 0; i < datas.length; i++) {
1216                        TemplatePersistenceData data= datas[i];
1217                        fTemplateStore.add(data);
1218                    }
1219                } finally {
1220                    try {
1221                        input.close();
1222                    } catch (IOException JavaDoc x) {
1223                        // ignore
1224
}
1225                }
1226            }
1227
1228            fTableViewer.refresh();
1229            fTableViewer.setAllChecked(false);
1230            fTableViewer.setCheckedElements(getEnabledTemplates());
1231
1232        } catch (FileNotFoundException JavaDoc e) {
1233            openReadErrorDialog();
1234        } catch (IOException JavaDoc e) {
1235            openReadErrorDialog();
1236        }
1237    }
1238
1239    private void export() {
1240        IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1241        Object JavaDoc[] templates= selection.toArray();
1242
1243        TemplatePersistenceData[] datas= new TemplatePersistenceData[templates.length];
1244        for (int i= 0; i != templates.length; i++)
1245            datas[i]= (TemplatePersistenceData) templates[i];
1246
1247        export(datas);
1248    }
1249
1250    private void export(TemplatePersistenceData[] templates) {
1251        FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
1252        dialog.setText(TextEditorTemplateMessages.TemplatePreferencePage_export_title);
1253        dialog.setFilterExtensions(new String JavaDoc[] {TextEditorTemplateMessages.TemplatePreferencePage_export_extension});
1254        dialog.setFileName(TextEditorTemplateMessages.TemplatePreferencePage_export_filename);
1255        String JavaDoc path= dialog.open();
1256
1257        if (path == null)
1258            return;
1259
1260        File JavaDoc file= new File JavaDoc(path);
1261
1262        if (file.isHidden()) {
1263            String JavaDoc title= TextEditorTemplateMessages.TemplatePreferencePage_export_error_title;
1264            String JavaDoc message= NLSUtility.format(TextEditorTemplateMessages.TemplatePreferencePage_export_error_hidden, file.getAbsolutePath());
1265            MessageDialog.openError(getShell(), title, message);
1266            return;
1267        }
1268
1269        if (file.exists() && !file.canWrite()) {
1270            String JavaDoc title= TextEditorTemplateMessages.TemplatePreferencePage_export_error_title;
1271            String JavaDoc message= NLSUtility.format(TextEditorTemplateMessages.TemplatePreferencePage_export_error_canNotWrite, file.getAbsolutePath());
1272            MessageDialog.openError(getShell(), title, message);
1273            return;
1274        }
1275
1276        if (!file.exists() || confirmOverwrite(file)) {
1277            OutputStream JavaDoc output= null;
1278            try {
1279                output= new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(file));
1280                TemplateReaderWriter writer= new TemplateReaderWriter();
1281                writer.save(templates, output);
1282            } catch (IOException JavaDoc e) {
1283                openWriteErrorDialog();
1284            } finally {
1285                if (output != null) {
1286                    try {
1287                        output.close();
1288                    } catch (IOException JavaDoc e) {
1289                        // ignore
1290
}
1291                }
1292            }
1293        }
1294    }
1295
1296    private boolean confirmOverwrite(File JavaDoc file) {
1297        return MessageDialog.openQuestion(getShell(),
1298            TextEditorTemplateMessages.TemplatePreferencePage_export_exists_title,
1299            NLSUtility.format(TextEditorTemplateMessages.TemplatePreferencePage_export_exists_message, file.getAbsolutePath()));
1300    }
1301
1302    private void remove() {
1303        IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1304
1305        Iterator JavaDoc elements= selection.iterator();
1306        while (elements.hasNext()) {
1307            TemplatePersistenceData data= (TemplatePersistenceData) elements.next();
1308            fTemplateStore.delete(data);
1309        }
1310
1311        fTableViewer.refresh();
1312    }
1313
1314    private void restoreDeleted() {
1315        fTemplateStore.restoreDeleted();
1316        fTableViewer.refresh();
1317        fTableViewer.setCheckedElements(getEnabledTemplates());
1318        updateButtons();
1319    }
1320
1321    private void revert() {
1322        IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
1323
1324        Iterator JavaDoc elements= selection.iterator();
1325        while (elements.hasNext()) {
1326            TemplatePersistenceData data= (TemplatePersistenceData) elements.next();
1327            data.revert();
1328        }
1329
1330        fTableViewer.refresh();
1331        selectionChanged1();
1332        fTableViewer.setChecked(getEnabledTemplates(), true);
1333    }
1334
1335    /*
1336     * @see Control#setVisible(boolean)
1337     */

1338    public void setVisible(boolean visible) {
1339        super.setVisible(visible);
1340        if (visible)
1341            setTitle(TextEditorTemplateMessages.TemplatePreferencePage_title);
1342    }
1343
1344    /*
1345     * @see PreferencePage#performDefaults()
1346     */

1347    protected void performDefaults() {
1348        if (isShowFormatterSetting()) {
1349            IPreferenceStore prefs= getPreferenceStore();
1350            fFormatButton.setSelection(prefs.getDefaultBoolean(getFormatterPreferenceKey()));
1351        }
1352
1353        fTemplateStore.restoreDefaults();
1354
1355        // refresh
1356
fTableViewer.refresh();
1357        fTableViewer.setAllChecked(false);
1358        fTableViewer.setCheckedElements(getEnabledTemplates());
1359    }
1360
1361    /*
1362     * @see PreferencePage#performOk()
1363     */

1364    public boolean performOk() {
1365        if (isShowFormatterSetting()) {
1366            IPreferenceStore prefs= getPreferenceStore();
1367            prefs.setValue(getFormatterPreferenceKey(), fFormatButton.getSelection());
1368        }
1369
1370        try {
1371            fTemplateStore.save();
1372        } catch (IOException JavaDoc e) {
1373            openWriteErrorDialog();
1374        }
1375
1376        return super.performOk();
1377    }
1378
1379    /**
1380     * Returns the key to use for the formatter preference.
1381     *
1382     * @return the formatter preference key
1383     */

1384    protected String JavaDoc getFormatterPreferenceKey() {
1385        return DEFAULT_FORMATTER_PREFERENCE_KEY;
1386    }
1387
1388    /*
1389     * @see PreferencePage#performCancel()
1390     */

1391    public boolean performCancel() {
1392        try {
1393            fTemplateStore.load();
1394        } catch (IOException JavaDoc e) {
1395            openReadErrorDialog();
1396            return false;
1397        }
1398        return super.performCancel();
1399    }
1400
1401    /*
1402     * @since 3.2
1403     */

1404    private void openReadErrorDialog() {
1405        String JavaDoc title= TextEditorTemplateMessages.TemplatePreferencePage_error_read_title;
1406        String JavaDoc message= TextEditorTemplateMessages.TemplatePreferencePage_error_read_message;
1407        MessageDialog.openError(getShell(), title, message);
1408    }
1409
1410    /*
1411     * @since 3.2
1412     */

1413    private void openWriteErrorDialog() {
1414        String JavaDoc title= TextEditorTemplateMessages.TemplatePreferencePage_error_write_title;
1415        String JavaDoc message= TextEditorTemplateMessages.TemplatePreferencePage_error_write_message;
1416        MessageDialog.openError(getShell(), title, message);
1417    }
1418
1419    protected SourceViewer getViewer() {
1420        return fPatternViewer;
1421    }
1422
1423    protected TableViewer getTableViewer() {
1424        return fTableViewer;
1425    }
1426}
1427
Popular Tags