1 11 package org.eclipse.ui.texteditor.templates; 12 13 import java.io.BufferedInputStream ; 14 import java.io.BufferedOutputStream ; 15 import java.io.File ; 16 import java.io.FileInputStream ; 17 import java.io.FileNotFoundException ; 18 import java.io.FileOutputStream ; 19 import java.io.IOException ; 20 import java.io.InputStream ; 21 import java.io.OutputStream ; 22 import java.util.ArrayList ; 23 import java.util.HashMap ; 24 import java.util.Iterator ; 25 import java.util.List ; 26 import java.util.Map ; 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 128 public abstract class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { 129 130 131 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 150 public TextViewerAction(ITextViewer viewer, int operationCode) { 151 fOperationCode= operationCode; 152 fOperationTarget= viewer.getTextOperationTarget(); 153 update(); 154 } 155 156 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 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; private Map fGlobalActions= new HashMap (10); 196 private List fSelectionActions = new ArrayList (3); 197 private String [][] fContextTypes; 198 199 private ContextTypeRegistry fContextTypeRegistry; 200 201 private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor(); 202 203 private Template fNewTemplate; 204 205 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 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 contexts= new ArrayList (); 228 for (Iterator it= registry.contextTypes(); it.hasNext();) { 229 TemplateContextType type= (TemplateContextType) it.next(); 230 contexts.add(new String [] { type.getId(), type.getName() }); 231 } 232 fContextTypes= (String [][]) contexts.toArray(new String [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 245 public void create() { 246 super.create(); 247 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 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 contextId= getContextId(); 365 fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId)); 366 } else if (w == fDescriptionText) { 367 } 369 } 370 371 private String getContextId() { 372 if (fContextCombo != null && !fContextCombo.isDisposed()) { 373 String 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 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 405 return data; 406 } 407 408 private static Label createLabel(Composite parent, String 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 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 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 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 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); 546 fSelectionActions.add(ITextEditorActionConstants.CUT); 547 fSelectionActions.add(ITextEditorActionConstants.COPY); 548 fSelectionActions.add(ITextEditorActionConstants.PASTE); 549 550 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")); menu.appendToGroup("templates", (IAction) fGlobalActions.get("ContentAssistProposal")); } 577 578 private void updateSelectionDependentActions() { 579 Iterator iterator= fSelectionActions.iterator(); 580 while (iterator.hasNext()) 581 updateAction((String )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 actionId) { 591 IAction action= (IAction) fGlobalActions.get(actionId); 592 if (action instanceof IUpdate) 593 ((IUpdate) action).update(); 594 } 595 596 private int getIndex(String 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 627 protected void okPressed() { 628 String 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 640 public Template getTemplate() { 641 return fNewTemplate; 642 } 643 644 651 protected IContentAssistProcessor getTemplateProcessor() { 652 return fTemplateProcessor; 653 } 654 655 659 protected IDialogSettings getDialogBoundsSettings() { 660 String sectionName= getClass().getName() + "_dialogBounds"; 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 674 private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider { 675 676 679 public Image getColumnImage(Object element, int columnIndex) { 680 return null; 681 } 682 683 686 public String getColumnText(Object 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 : ""; default: 703 return ""; } 705 } 706 } 707 708 709 710 private static final String DEFAULT_FORMATTER_PREFERENCE_KEY= "org.eclipse.ui.texteditor.templates.preferences.format_templates"; 712 713 private CheckboxTableViewer fTableViewer; 714 715 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 725 private SourceViewer fPatternViewer; 726 727 private Button fFormatButton; 728 729 private TemplateStore fTemplateStore; 730 731 private ContextTypeRegistry fContextTypeRegistry; 732 733 734 737 protected TemplatePreferencePage() { 738 super(); 739 740 setDescription(TextEditorTemplateMessages.TemplatePreferencePage_message); 741 } 742 743 748 public TemplateStore getTemplateStore() { 749 return fTemplateStore; 750 } 751 752 757 public ContextTypeRegistry getContextTypeRegistry() { 758 return fContextTypeRegistry; 759 } 760 761 766 public void setTemplateStore(TemplateStore store) { 767 fTemplateStore= store; 768 } 769 770 775 public void setContextTypeRegistry(ContextTypeRegistry registry) { 776 fContextTypeRegistry= registry; 777 } 778 779 782 public void init(IWorkbench workbench) { 783 } 784 785 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 object1, Object 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 element, String 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 986 private int computeMinimumColumnWidth(GC gc, String string) { 987 return gc.stringExtent(string).x + 10; } 989 990 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 1012 protected boolean isShowFormatterSetting() { 1013 return true; 1014 } 1015 1016 private TemplatePersistenceData[] getEnabledTemplates() { 1017 List enabled= new ArrayList (); 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 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 1068 return data; 1069 } 1070 1071 private void selectionChanged1() { 1072 updateViewerInput(); 1073 1074 updateButtons(); 1075 } 1076 1077 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(""); } 1090 } 1091 1092 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 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 it= fContextTypeRegistry.contextTypes(); 1119 if (it.hasNext()) { 1120 Template template= new Template("", "", ((TemplateContextType) it.next()).getId(), "", true); 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 1143 protected Dialog createTemplateEditDialog(Template template, boolean edit, boolean isNameModifiable) { 1144 return new EditTemplateDialog(getShell(), template, edit, isNameModifiable, fContextTypeRegistry); 1145 } 1146 1147 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 [] 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 [] {TextEditorTemplateMessages.TemplatePreferencePage_import_extension}); 1203 String path= dialog.open(); 1204 1205 if (path == null) 1206 return; 1207 1208 try { 1209 TemplateReaderWriter reader= new TemplateReaderWriter(); 1210 File file= new File (path); 1211 if (file.exists()) { 1212 InputStream input= new BufferedInputStream (new FileInputStream (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 x) { 1223 } 1225 } 1226 } 1227 1228 fTableViewer.refresh(); 1229 fTableViewer.setAllChecked(false); 1230 fTableViewer.setCheckedElements(getEnabledTemplates()); 1231 1232 } catch (FileNotFoundException e) { 1233 openReadErrorDialog(); 1234 } catch (IOException e) { 1235 openReadErrorDialog(); 1236 } 1237 } 1238 1239 private void export() { 1240 IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); 1241 Object [] 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 [] {TextEditorTemplateMessages.TemplatePreferencePage_export_extension}); 1254 dialog.setFileName(TextEditorTemplateMessages.TemplatePreferencePage_export_filename); 1255 String path= dialog.open(); 1256 1257 if (path == null) 1258 return; 1259 1260 File file= new File (path); 1261 1262 if (file.isHidden()) { 1263 String title= TextEditorTemplateMessages.TemplatePreferencePage_export_error_title; 1264 String 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 title= TextEditorTemplateMessages.TemplatePreferencePage_export_error_title; 1271 String 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 output= null; 1278 try { 1279 output= new BufferedOutputStream (new FileOutputStream (file)); 1280 TemplateReaderWriter writer= new TemplateReaderWriter(); 1281 writer.save(templates, output); 1282 } catch (IOException e) { 1283 openWriteErrorDialog(); 1284 } finally { 1285 if (output != null) { 1286 try { 1287 output.close(); 1288 } catch (IOException e) { 1289 } 1291 } 1292 } 1293 } 1294 } 1295 1296 private boolean confirmOverwrite(File 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 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 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 1338 public void setVisible(boolean visible) { 1339 super.setVisible(visible); 1340 if (visible) 1341 setTitle(TextEditorTemplateMessages.TemplatePreferencePage_title); 1342 } 1343 1344 1347 protected void performDefaults() { 1348 if (isShowFormatterSetting()) { 1349 IPreferenceStore prefs= getPreferenceStore(); 1350 fFormatButton.setSelection(prefs.getDefaultBoolean(getFormatterPreferenceKey())); 1351 } 1352 1353 fTemplateStore.restoreDefaults(); 1354 1355 fTableViewer.refresh(); 1357 fTableViewer.setAllChecked(false); 1358 fTableViewer.setCheckedElements(getEnabledTemplates()); 1359 } 1360 1361 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 e) { 1373 openWriteErrorDialog(); 1374 } 1375 1376 return super.performOk(); 1377 } 1378 1379 1384 protected String getFormatterPreferenceKey() { 1385 return DEFAULT_FORMATTER_PREFERENCE_KEY; 1386 } 1387 1388 1391 public boolean performCancel() { 1392 try { 1393 fTemplateStore.load(); 1394 } catch (IOException e) { 1395 openReadErrorDialog(); 1396 return false; 1397 } 1398 return super.performCancel(); 1399 } 1400 1401 1404 private void openReadErrorDialog() { 1405 String title= TextEditorTemplateMessages.TemplatePreferencePage_error_read_title; 1406 String message= TextEditorTemplateMessages.TemplatePreferencePage_error_read_message; 1407 MessageDialog.openError(getShell(), title, message); 1408 } 1409 1410 1413 private void openWriteErrorDialog() { 1414 String title= TextEditorTemplateMessages.TemplatePreferencePage_error_write_title; 1415 String 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 |