KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > refactoring > nls > ExternalizeWizardPage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 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.jdt.internal.ui.refactoring.nls;
12
13 import java.io.InputStream JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Collections JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Properties JavaDoc;
19
20 import org.eclipse.core.runtime.Assert;
21 import org.eclipse.core.runtime.IStatus;
22
23 import org.eclipse.core.resources.IFile;
24
25 import org.eclipse.swt.SWT;
26 import org.eclipse.swt.custom.SashForm;
27 import org.eclipse.swt.events.ModifyEvent;
28 import org.eclipse.swt.events.ModifyListener;
29 import org.eclipse.swt.events.MouseAdapter;
30 import org.eclipse.swt.events.MouseEvent;
31 import org.eclipse.swt.events.SelectionAdapter;
32 import org.eclipse.swt.events.SelectionEvent;
33 import org.eclipse.swt.events.SelectionListener;
34 import org.eclipse.swt.graphics.Font;
35 import org.eclipse.swt.graphics.Image;
36 import org.eclipse.swt.layout.FormAttachment;
37 import org.eclipse.swt.layout.FormData;
38 import org.eclipse.swt.layout.FormLayout;
39 import org.eclipse.swt.layout.GridData;
40 import org.eclipse.swt.layout.GridLayout;
41 import org.eclipse.swt.widgets.Button;
42 import org.eclipse.swt.widgets.Combo;
43 import org.eclipse.swt.widgets.Composite;
44 import org.eclipse.swt.widgets.Control;
45 import org.eclipse.swt.widgets.Label;
46 import org.eclipse.swt.widgets.Shell;
47 import org.eclipse.swt.widgets.Table;
48 import org.eclipse.swt.widgets.TableColumn;
49 import org.eclipse.swt.widgets.TableItem;
50 import org.eclipse.swt.widgets.Text;
51 import org.eclipse.swt.widgets.Widget;
52
53 import org.eclipse.jface.dialogs.Dialog;
54 import org.eclipse.jface.dialogs.IDialogSettings;
55 import org.eclipse.jface.dialogs.StatusDialog;
56 import org.eclipse.jface.preference.IPreferenceStore;
57 import org.eclipse.jface.resource.FontRegistry;
58 import org.eclipse.jface.resource.ImageDescriptor;
59 import org.eclipse.jface.resource.JFaceResources;
60 import org.eclipse.jface.viewers.CellEditor;
61 import org.eclipse.jface.viewers.ColumnLayoutData;
62 import org.eclipse.jface.viewers.ColumnPixelData;
63 import org.eclipse.jface.viewers.ColumnWeightData;
64 import org.eclipse.jface.viewers.ICellModifier;
65 import org.eclipse.jface.viewers.IFontProvider;
66 import org.eclipse.jface.viewers.ISelection;
67 import org.eclipse.jface.viewers.ISelectionChangedListener;
68 import org.eclipse.jface.viewers.IStructuredContentProvider;
69 import org.eclipse.jface.viewers.IStructuredSelection;
70 import org.eclipse.jface.viewers.ITableLabelProvider;
71 import org.eclipse.jface.viewers.LabelProvider;
72 import org.eclipse.jface.viewers.SelectionChangedEvent;
73 import org.eclipse.jface.viewers.StructuredSelection;
74 import org.eclipse.jface.viewers.TableLayout;
75 import org.eclipse.jface.viewers.TableViewer;
76 import org.eclipse.jface.viewers.TextCellEditor;
77 import org.eclipse.jface.viewers.Viewer;
78 import org.eclipse.jface.viewers.ViewerFilter;
79 import org.eclipse.jface.window.Window;
80 import org.eclipse.jface.wizard.IWizardPage;
81
82 import org.eclipse.jface.text.Document;
83 import org.eclipse.jface.text.IDocument;
84 import org.eclipse.jface.text.Region;
85 import org.eclipse.jface.text.source.SourceViewer;
86
87 import org.eclipse.ui.PlatformUI;
88
89 import org.eclipse.ltk.core.refactoring.RefactoringStatus;
90 import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
91
92 import org.eclipse.jdt.core.ICompilationUnit;
93 import org.eclipse.jdt.core.IJavaProject;
94 import org.eclipse.jdt.core.JavaModelException;
95
96 import org.eclipse.jdt.internal.corext.refactoring.nls.KeyValuePair;
97 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
98 import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution;
99
100 import org.eclipse.jdt.ui.JavaElementImageDescriptor;
101 import org.eclipse.jdt.ui.PreferenceConstants;
102 import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
103 import org.eclipse.jdt.ui.text.JavaTextTools;
104
105 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
106 import org.eclipse.jdt.internal.ui.JavaPlugin;
107 import org.eclipse.jdt.internal.ui.JavaPluginImages;
108 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
109 import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
110 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
111 import org.eclipse.jdt.internal.ui.util.SWTUtil;
112 import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
113 import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
114 import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
115 import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
116 import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
117
118 class ExternalizeWizardPage extends UserInputWizardPage {
119
120     private static final String JavaDoc[] PROPERTIES;
121     private static final String JavaDoc[] fgTitles;
122     private static final int STATE_PROP= 0;
123     private static final int VAL_PROP= 1;
124     private static final int KEY_PROP= 2;
125     private static final int SIZE= 3; //column counter
126
private static final int ROW_COUNT= 5;
127
128     public static final String JavaDoc PAGE_NAME= "NLSWizardPage1"; //$NON-NLS-1$
129
static {
130         PROPERTIES= new String JavaDoc[SIZE];
131         PROPERTIES[STATE_PROP]= "task"; //$NON-NLS-1$
132
PROPERTIES[KEY_PROP]= "key"; //$NON-NLS-1$
133
PROPERTIES[VAL_PROP]= "value"; //$NON-NLS-1$
134

135         fgTitles= new String JavaDoc[SIZE];
136         fgTitles[STATE_PROP]= ""; //$NON-NLS-1$
137
fgTitles[KEY_PROP]= NLSUIMessages.ExternalizeWizardPage_key;
138         fgTitles[VAL_PROP]= NLSUIMessages.ExternalizeWizardPage_value;
139     }
140
141     private class CellModifier implements ICellModifier {
142
143         /**
144          * @see ICellModifier#canModify(Object, String)
145          */

146         public boolean canModify(Object JavaDoc element, String JavaDoc property) {
147             if (property == null)
148                 return false;
149
150             if (!(element instanceof NLSSubstitution))
151                 return false;
152             
153             NLSSubstitution subst= (NLSSubstitution) element;
154             if (PROPERTIES[KEY_PROP].equals(property) && subst.getState() != NLSSubstitution.EXTERNALIZED) {
155                 return false;
156             }
157             
158             return true;
159         }
160
161         /**
162          * @see ICellModifier#getValue(Object, String)
163          */

164         public Object JavaDoc getValue(Object JavaDoc element, String JavaDoc property) {
165             if (element instanceof NLSSubstitution) {
166                 NLSSubstitution substitution= (NLSSubstitution) element;
167                 String JavaDoc res= null;
168                 if (PROPERTIES[KEY_PROP].equals(property)) {
169                     res= substitution.getKeyWithoutPrefix();
170                 } else if (PROPERTIES[VAL_PROP].equals(property)) {
171                     res= substitution.getValue();
172                 } else if (PROPERTIES[STATE_PROP].equals(property)) {
173                     return new Integer JavaDoc(substitution.getState());
174                 }
175                 if (res != null) {
176                     return unwindEscapeChars(res);
177                 }
178                 return ""; //$NON-NLS-1$
179
}
180             return ""; //$NON-NLS-1$
181
}
182
183         /**
184          * @see ICellModifier#modify(Object, String, Object)
185          */

186         public void modify(Object JavaDoc element, String JavaDoc property, Object JavaDoc value) {
187             if (element instanceof TableItem) {
188                 Object JavaDoc data= ((TableItem) element).getData();
189                 if (data instanceof NLSSubstitution) {
190                     NLSSubstitution substitution= (NLSSubstitution) data;
191                     if (PROPERTIES[KEY_PROP].equals(property)) {
192                         String JavaDoc string = (String JavaDoc)value;
193                         string = windEscapeChars(string);
194                         substitution.setKey(string);
195                     }
196                     if (PROPERTIES[VAL_PROP].equals(property)) {
197                         String JavaDoc string = (String JavaDoc)value;
198                         string = windEscapeChars(string);
199                         substitution.setValue(string);
200                     }
201                     if (PROPERTIES[STATE_PROP].equals(property)) {
202                         substitution.setState(((Integer JavaDoc) value).intValue());
203                         if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
204                             substitution.generateKey(fSubstitutions);
205                         }
206                     }
207                 }
208                 validateKeys(false);
209                 fTableViewer.update(data, null);
210             }
211         }
212     }
213
214     private class NLSSubstitutionLabelProvider extends LabelProvider implements ITableLabelProvider, IFontProvider {
215
216         private FontRegistry fFontRegistry;
217
218         public NLSSubstitutionLabelProvider() {
219             fFontRegistry= JFaceResources.getFontRegistry();
220         }
221
222         public String JavaDoc getColumnText(Object JavaDoc element, int columnIndex) {
223             String JavaDoc columnText= ""; //$NON-NLS-1$
224
if (element instanceof NLSSubstitution) {
225                 NLSSubstitution substitution= (NLSSubstitution) element;
226                 if (columnIndex == KEY_PROP) {
227                     if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
228                         columnText= substitution.getKey();
229                     }
230                 } else
231                     if ((columnIndex == VAL_PROP) && (substitution.getValue() != null)) {
232                         columnText= substitution.getValue();
233                     }
234             }
235             return unwindEscapeChars(columnText);
236         }
237
238         public Image getColumnImage(Object JavaDoc element, int columnIndex) {
239             if ((columnIndex == STATE_PROP) && (element instanceof NLSSubstitution)) {
240                 return getNLSImage((NLSSubstitution) element);
241             }
242
243             return null;
244         }
245
246         public Font getFont(Object JavaDoc element) {
247             if (element instanceof NLSSubstitution) {
248                 NLSSubstitution substitution= (NLSSubstitution) element;
249                 if (substitution.hasPropertyFileChange() || substitution.hasSourceChange()) {
250                     return fFontRegistry.getBold(JFaceResources.DIALOG_FONT);
251                 }
252             }
253             return null;
254         }
255
256         private Image getNLSImage(NLSSubstitution sub) {
257             if ((sub.getValue() == null) && (sub.getKey() != null)) {
258                 // Missing keys
259
JavaElementImageDescriptor imageDescriptor= new JavaElementImageDescriptor(getNLSImageDescriptor(sub.getState()), JavaElementImageDescriptor.WARNING, JavaElementImageProvider.SMALL_SIZE);
260                 return JavaPlugin.getImageDescriptorRegistry().get(imageDescriptor);
261             } else
262                 if (sub.isConflicting(fSubstitutions) || !isKeyValid(sub, null)) {
263                     JavaElementImageDescriptor imageDescriptor= new JavaElementImageDescriptor(getNLSImageDescriptor(sub.getState()), JavaElementImageDescriptor.ERROR, JavaElementImageProvider.SMALL_SIZE);
264                     return JavaPlugin.getImageDescriptorRegistry().get(imageDescriptor);
265                 } else {
266                     return getNLSImage(sub.getState());
267                 }
268         }
269
270         private Image getNLSImage(int task) {
271             switch (task) {
272                 case NLSSubstitution.EXTERNALIZED :
273                     return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_TRANSLATE);
274                 case NLSSubstitution.IGNORED :
275                     return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
276                 case NLSSubstitution.INTERNALIZED :
277                     return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_SKIP);
278                 default :
279                     Assert.isTrue(false);
280                     return null;
281             }
282         }
283
284         private ImageDescriptor getNLSImageDescriptor(int task) {
285             switch (task) {
286                 case NLSSubstitution.EXTERNALIZED :
287                     return JavaPluginImages.DESC_OBJS_NLS_TRANSLATE;
288                 case NLSSubstitution.IGNORED :
289                     return JavaPluginImages.DESC_OBJS_NLS_NEVER_TRANSLATE;
290                 case NLSSubstitution.INTERNALIZED :
291                     return JavaPluginImages.DESC_OBJS_NLS_SKIP;
292                 default :
293                     Assert.isTrue(false);
294                     return null;
295             }
296         }
297     }
298
299     private static String JavaDoc unwindEscapeChars(String JavaDoc s) {
300         if (s != null) {
301             StringBuffer JavaDoc sb= new StringBuffer JavaDoc(s.length());
302             int length= s.length();
303             for (int i= 0; i < length; i++) {
304                 char c= s.charAt(i);
305                 sb.append(getUnwoundString(c));
306             }
307             return sb.toString();
308         }
309         return null;
310     }
311
312     private static String JavaDoc getUnwoundString(char c) {
313         switch (c) {
314             case '\b' :
315                 return "\\b";//$NON-NLS-1$
316
case '\t' :
317                 return "\\t";//$NON-NLS-1$
318
case '\n' :
319                 return "\\n";//$NON-NLS-1$
320
case '\f' :
321                 return "\\f";//$NON-NLS-1$
322
case '\r' :
323                 return "\\r";//$NON-NLS-1$
324
case '\\' :
325                 return "\\\\";//$NON-NLS-1$
326
}
327         return String.valueOf(c);
328     }
329
330     private static String JavaDoc windEscapeChars(String JavaDoc s) {
331         if (s == null)
332             return null;
333
334         char aChar;
335         int len= s.length();
336         StringBuffer JavaDoc outBuffer= new StringBuffer JavaDoc(len);
337
338         for (int x= 0; x < len;) {
339             aChar= s.charAt(x++);
340             if (aChar == '\\') {
341                 aChar= s.charAt(x++);
342                 if (aChar == 'u') {
343                     // Read the xxxx
344
int value= 0;
345                     for (int i= 0; i < 4; i++) {
346                         aChar= s.charAt(x++);
347                         switch (aChar) {
348                             case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
349                                 value= (value << 4) + aChar - '0';
350                                 break;
351                             case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
352                                 value= (value << 4) + 10 + aChar - 'a';
353                                 break;
354                             case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
355                                 value= (value << 4) + 10 + aChar - 'A';
356                                 break;
357                             default:
358                                 throw new IllegalArgumentException JavaDoc("Malformed \\uxxxx encoding."); //$NON-NLS-1$
359
}
360                     }
361                     outBuffer.append((char) value);
362                 } else {
363                     if (aChar == 't') {
364                         outBuffer.append('\t');
365                     } else {
366                         if (aChar == 'r') {
367                             outBuffer.append('\r');
368                         } else {
369                             if (aChar == 'n') {
370                                 outBuffer.append('\n');
371                             } else {
372                                 if (aChar == 'f') {
373                                     outBuffer.append('\f');
374                                 } else {
375                                     outBuffer.append(aChar);
376                                 }
377                             }
378                         }
379                     }
380                 }
381             } else
382                 outBuffer.append(aChar);
383         }
384         return outBuffer.toString();
385     }
386     
387     private class NLSInputDialog extends StatusDialog implements IDialogFieldListener {
388         private StringDialogField fKeyField;
389         private StringDialogField fValueField;
390         private DialogField fMessageField;
391         private NLSSubstitution fSubstitution;
392
393         public NLSInputDialog(Shell parent, NLSSubstitution substitution) {
394             super(parent);
395             
396             setTitle(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Title);
397
398             fSubstitution= substitution;
399             
400             fMessageField= new DialogField();
401             if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
402                 fMessageField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_ext_Label);
403             } else {
404                 fMessageField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Label);
405             }
406
407             fKeyField= new StringDialogField();
408             fKeyField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Enter_key);
409             fKeyField.setDialogFieldListener(this);
410
411             fValueField= new StringDialogField();
412             fValueField.setLabelText(NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Enter_value);
413             fValueField.setDialogFieldListener(this);
414
415             if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
416                 fKeyField.setText(substitution.getKeyWithoutPrefix());
417             } else {
418                 fKeyField.setText(""); //$NON-NLS-1$
419
}
420
421             fValueField.setText(substitution.getValueNonEmpty());
422         }
423
424         public KeyValuePair getResult() {
425             KeyValuePair res= new KeyValuePair(fKeyField.getText(), fValueField.getText());
426             return res;
427         }
428
429         protected Control createDialogArea(Composite parent) {
430             Composite composite= (Composite) super.createDialogArea(parent);
431
432             Composite inner= new Composite(composite, SWT.NONE);
433             inner.setFont(composite.getFont());
434             
435             GridLayout layout= new GridLayout();
436             layout.marginHeight= 0;
437             layout.marginWidth= 0;
438             layout.numColumns= 2;
439             inner.setLayout(layout);
440
441             fMessageField.doFillIntoGrid(inner, 2);
442             
443             if (fSubstitution.getState() == NLSSubstitution.EXTERNALIZED) {
444                 fKeyField.doFillIntoGrid(inner, 2);
445                 LayoutUtil.setWidthHint(fKeyField.getTextControl(null), convertWidthInCharsToPixels(45));
446             }
447             
448             fValueField.doFillIntoGrid(inner, 2);
449             LayoutUtil.setWidthHint(fValueField.getTextControl(null), convertWidthInCharsToPixels(45));
450             LayoutUtil.setHorizontalGrabbing(fValueField.getTextControl(null));
451
452             fValueField.postSetFocusOnDialogField(parent.getDisplay());
453
454             applyDialogFont(composite);
455             return composite;
456         }
457
458         /* (non-Javadoc)
459          * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
460          */

461         public void dialogFieldChanged(DialogField field) {
462             IStatus keyStatus= validateKey(fKeyField.getText());
463             //IStatus valueStatus= StatusInfo.OK_STATUS; // no validation yet
464

465             //updateStatus(StatusUtil.getMoreSevere(valueStatus, keyStatus));
466
updateStatus(keyStatus);
467         }
468
469
470         private IStatus validateKey(String JavaDoc val) {
471             if (fSubstitution.getState() != NLSSubstitution.EXTERNALIZED) {
472                 return StatusInfo.OK_STATUS;
473             }
474             
475             if (val == null || val.length() == 0) {
476                 return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_empty_key);
477             }
478             
479             if (fNLSRefactoring.isEclipseNLS()) {
480                 if (!Character.isJavaIdentifierStart(val.charAt(0)))
481                     return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key);
482                 
483                 for (int i= 1, length= val.length(); i < length; i++) {
484                     if (!Character.isJavaIdentifierPart(val.charAt(i)))
485                         return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_EclipseNLS_key);
486                 }
487             } else {
488                 // validation so keys don't contain spaces
489
for (int i= 0; i < val.length(); i++) {
490                     if (Character.isWhitespace(val.charAt(i))) {
491                         return new StatusInfo(IStatus.ERROR, NLSUIMessages.ExternalizeWizardPage_NLSInputDialog_Error_invalid_key);
492                     }
493                 }
494             }
495             return StatusInfo.OK_STATUS;
496         }
497     }
498
499     private static final String JavaDoc SETTINGS_NLS_ACCESSORS= "nls_accessor_history"; //$NON-NLS-1$
500
private static final int SETTINGS_MAX_ENTRIES= 5;
501     
502     private Text fPrefixField;
503     private Button fIsEclipseNLS;
504     private Table fTable;
505     private TableViewer fTableViewer;
506     private SourceViewer fSourceViewer;
507
508     private final ICompilationUnit fCu;
509     private NLSSubstitution[] fSubstitutions;
510     private Button fExternalizeButton;
511     private Button fIgnoreButton;
512     private Button fInternalizeButton;
513     private Button fRevertButton;
514     private Button fEditButton;
515     private NLSRefactoring fNLSRefactoring;
516     private Button fRenameButton;
517     private Combo fAccessorClassField;
518     
519     private AccessorDescription[] fAccessorChoices;
520     private Button fFilterCheckBox;
521
522     public ExternalizeWizardPage(NLSRefactoring nlsRefactoring) {
523         super(PAGE_NAME);
524         fCu= nlsRefactoring.getCu();
525         fSubstitutions= nlsRefactoring.getSubstitutions();
526         fNLSRefactoring= nlsRefactoring;
527         fAccessorChoices= null;
528
529         setDescription(NLSUIMessages.ExternalizeWizardPage_description);
530         createDefaultExternalization(fSubstitutions, nlsRefactoring.getPrefix());
531     }
532
533     /*
534      * @see IDialogPage#createControl(Composite)
535      */

536     public void createControl(Composite parent) {
537         initializeDialogUnits(parent);
538
539         Composite supercomposite= new Composite(parent, SWT.NONE);
540         supercomposite.setFont(parent.getFont());
541         supercomposite.setLayout(new GridLayout());
542
543         createIsEclipseNLSCheckbox(supercomposite);
544         
545         createKeyPrefixField(supercomposite);
546
547         SashForm composite= new SashForm(supercomposite, SWT.VERTICAL);
548         composite.setFont(supercomposite.getFont());
549
550         GridData data= new GridData(GridData.FILL_BOTH);
551         composite.setLayoutData(data);
552
553         createTableViewer(composite);
554         createSourceViewer(composite);
555         
556         createAccessorInfoComposite(supercomposite);
557
558         composite.setWeights(new int[]{65, 45});
559
560         validateKeys(false);
561         updateButtonStates(StructuredSelection.EMPTY);
562         
563         // promote control
564
setControl(supercomposite);
565         Dialog.applyDialogFont(supercomposite);
566         PlatformUI.getWorkbench().getHelpSystem().setHelp(supercomposite, IJavaHelpContextIds.EXTERNALIZE_WIZARD_KEYVALUE_PAGE);
567     }
568
569     /**
570      * @param supercomposite
571      */

572     private void createAccessorInfoComposite(Composite supercomposite) {
573         Composite accessorComposite= new Composite(supercomposite, SWT.NONE);
574         accessorComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
575         GridLayout layout= new GridLayout(2, false);
576         layout.marginHeight= 0;
577         layout.marginWidth= 0;
578         accessorComposite.setLayout(layout);
579         
580         Composite composite= new Composite(accessorComposite, SWT.NONE);
581         composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
582         
583         layout= new GridLayout(1, true);
584         layout.marginHeight= 0;
585         layout.marginWidth= 0;
586         composite.setLayout(layout);
587         
588         Label accessorClassLabel= new Label(composite, SWT.NONE);
589         accessorClassLabel.setText(NLSUIMessages.ExternalizeWizardPage_accessorclass_label);
590         accessorClassLabel.setLayoutData(new GridData());
591         
592         
593         SelectionListener listener= new SelectionAdapter() {
594             public void widgetSelected(SelectionEvent e) {
595                 if (e.widget instanceof Button) {
596                     doConfigureButtonPressed();
597                 } else {
598                     doAccessorSelectionChanged();
599                 }
600             }
601         };
602         
603         
604         GridData data= new GridData(GridData.FILL_HORIZONTAL);
605         data.widthHint= convertWidthInCharsToPixels(30);
606         fAccessorClassField= new Combo(composite, SWT.READ_ONLY);
607         fAccessorClassField.setLayoutData(data);
608         fAccessorClassField.addSelectionListener(listener);
609         
610         
611         //new Label(composite, SWT.NONE); // placeholder
612

613         Button configure= new Button(accessorComposite, SWT.PUSH);
614         configure.setText(NLSUIMessages.ExternalizeWizardPage_configure_button);
615         data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_END);
616         data.widthHint= SWTUtil.getButtonWidthHint(configure);
617         configure.setLayoutData(data);
618
619         configure.addSelectionListener(listener);
620         
621         updateAccessorChoices();
622         
623     }
624     
625     protected void doAccessorSelectionChanged() {
626         int selectionIndex= fAccessorClassField.getSelectionIndex();
627         if (fAccessorChoices != null && selectionIndex < fAccessorChoices.length) {
628             AccessorDescription selected= fAccessorChoices[selectionIndex];
629             fNLSRefactoring.setAccessorClassName(selected.getAccessorClassName());
630             fNLSRefactoring.setAccessorClassPackage(selected.getAccessorClassPackage());
631             fNLSRefactoring.setResourceBundleName(selected.getResourceBundleName());
632             fNLSRefactoring.setResourceBundlePackage(selected.getResourceBundlePackage());
633             fNLSRefactoring.setIsEclipseNLS(fNLSRefactoring.detectIsEclipseNLS());
634             
635             NLSSubstitution.updateSubtitutions(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()), fNLSRefactoring.getAccessorClassName());
636             if (fIsEclipseNLS != null) {
637                 fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
638                 fIsEclipseNLS.setEnabled(willCreateAccessorClass());
639             }
640             validateKeys(true);
641         }
642     }
643     
644     private boolean willCreateAccessorClass() {
645         try {
646             return fNLSRefactoring.willCreateAccessorClass();
647         } catch (JavaModelException e) {
648             return false;
649         }
650     }
651
652     private void updateAccessorChoices() {
653         
654         AccessorDescription configured= new AccessorDescription(
655                 fNLSRefactoring.getAccessorClassName(),
656                 fNLSRefactoring.getAccessorClassPackage(),
657                 fNLSRefactoring.getResourceBundleName(),
658                 fNLSRefactoring.getResourceBundlePackage());
659         
660         ArrayList JavaDoc currChoices= new ArrayList JavaDoc();
661         ArrayList JavaDoc currLabels= new ArrayList JavaDoc();
662         
663         currChoices.add(configured);
664         currLabels.add(configured.getLabel());
665         
666         AccessorDescription[] choices= fAccessorChoices;
667         if (choices == null) {
668             choices= loadAccessorDescriptions();
669         }
670         
671         for (int i= 0; i < choices.length; i++) {
672             AccessorDescription curr= choices[i];
673             if (!curr.equals(configured)) {
674                 currChoices.add(curr);
675                 currLabels.add(curr.getLabel());
676             }
677         }
678         
679         String JavaDoc[] labels= (String JavaDoc[]) currLabels.toArray(new String JavaDoc[currLabels.size()]);
680         fAccessorChoices= (AccessorDescription[]) currChoices.toArray(new AccessorDescription[currChoices.size()]);
681         
682         fAccessorClassField.setItems(labels);
683         fAccessorClassField.select(0);
684     }
685     
686     
687     private AccessorDescription[] loadAccessorDescriptions() {
688         IDialogSettings section= JavaPlugin.getDefault().getDialogSettings().getSection(SETTINGS_NLS_ACCESSORS);
689         if (section == null) {
690             return new AccessorDescription[0];
691         }
692         ArrayList JavaDoc res= new ArrayList JavaDoc();
693         for (int i= 0; i < SETTINGS_MAX_ENTRIES; i++) {
694             IDialogSettings serializedDesc= section.getSection(String.valueOf(i));
695             if (serializedDesc != null) {
696                 AccessorDescription accessor= AccessorDescription.deserialize(serializedDesc);
697                 if (accessor != null) {
698                     res.add(accessor);
699                 }
700             }
701         }
702         return (AccessorDescription[]) res.toArray(new AccessorDescription[res.size()]);
703     }
704     
705     
706     
707     private void storeAccessorDescriptions() {
708         if (fAccessorChoices == null) {
709             return;
710         }
711         IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
712         IDialogSettings nlsSection= dialogSettings.getSection(SETTINGS_NLS_ACCESSORS);
713         if (nlsSection == null) {
714             nlsSection= dialogSettings.addNewSection(SETTINGS_NLS_ACCESSORS);
715         }
716         int nEntries= Math.min(SETTINGS_MAX_ENTRIES, fAccessorChoices.length);
717         for (int i= 0; i < nEntries; i++) {
718             IDialogSettings serializedDesc= nlsSection.addNewSection(String.valueOf(i));
719             fAccessorChoices[i].serialize(serializedDesc);
720         }
721     }
722     
723
724     private void doConfigureButtonPressed() {
725         NLSAccessorConfigurationDialog dialog= new NLSAccessorConfigurationDialog(getShell(), fNLSRefactoring);
726         if (dialog.open() == Window.OK) {
727             NLSSubstitution.updateSubtitutions(fSubstitutions, getProperties(fNLSRefactoring.getPropertyFileHandle()), fNLSRefactoring.getAccessorClassName());
728             if (fIsEclipseNLS != null) {
729                 fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
730                 fIsEclipseNLS.setEnabled(willCreateAccessorClass());
731             }
732             validateKeys(true);
733             updateAccessorChoices();
734         }
735     }
736
737     private Properties JavaDoc getProperties(IFile propertyFile) {
738         Properties JavaDoc props= new Properties JavaDoc();
739         try {
740             if (propertyFile.exists()) {
741                 InputStream JavaDoc is= propertyFile.getContents();
742                 props.load(is);
743                 is.close();
744             }
745         } catch (Exception JavaDoc e) {
746             // sorry no property
747
}
748         return props;
749     }
750
751     private void createTableViewer(Composite composite) {
752         createTableComposite(composite);
753
754         /*
755          * Feature of CellEditors - double click is ignored.
756          * The workaround is to register my own listener and force the desired
757          * behavior.
758          */

759         fTableViewer= new TableViewer(fTable) {
760             protected void hookControl(Control control) {
761                 super.hookControl(control);
762                 ((Table) control).addMouseListener(new MouseAdapter() {
763                     public void mouseDoubleClick(MouseEvent e) {
764                         if (getTable().getSelection().length == 0)
765                             return;
766                         TableItem item= getTable().getSelection()[0];
767                         if (item.getBounds(STATE_PROP).contains(e.x, e.y)) {
768                             List JavaDoc widgetSel= getSelectionFromWidget();
769                             if (widgetSel == null || widgetSel.size() != 1)
770                                 return;
771                             NLSSubstitution substitution= (NLSSubstitution) widgetSel.get(0);
772                             Integer JavaDoc value= (Integer JavaDoc) getCellModifier().getValue(substitution, PROPERTIES[STATE_PROP]);
773                             int newValue= MultiStateCellEditor.getNextValue(NLSSubstitution.STATE_COUNT, value.intValue());
774                             getCellModifier().modify(item, PROPERTIES[STATE_PROP], new Integer JavaDoc(newValue));
775                         }
776                     }
777                 });
778             }
779         };
780
781         fTableViewer.setUseHashlookup(true);
782
783         final CellEditor[] editors= createCellEditors();
784         fTableViewer.setCellEditors(editors);
785         fTableViewer.setColumnProperties(PROPERTIES);
786         fTableViewer.setCellModifier(new CellModifier());
787
788         fTableViewer.setContentProvider(new IStructuredContentProvider() {
789             public Object JavaDoc[] getElements(Object JavaDoc inputElement) {
790                 return fSubstitutions;
791             }
792             public void dispose() {
793             }
794             public void inputChanged(Viewer viewer, Object JavaDoc oldInput, Object JavaDoc newInput) {
795             }
796         });
797         fTableViewer.addFilter(new ViewerFilter() {
798             public boolean select(Viewer viewer, Object JavaDoc parentElement, Object JavaDoc element) {
799                 if (!fFilterCheckBox.getSelection()) {
800                     return true;
801                 }
802                 NLSSubstitution curr= (NLSSubstitution) element;
803                 return (curr.getInitialState() == NLSSubstitution.INTERNALIZED) || (curr.getInitialState() == NLSSubstitution.EXTERNALIZED && curr.getInitialValue() == null);
804             }
805         });
806         
807
808         fTableViewer.setLabelProvider(new NLSSubstitutionLabelProvider());
809         fTableViewer.setInput(new Object JavaDoc());
810
811         fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
812             public void selectionChanged(SelectionChangedEvent event) {
813                 ExternalizeWizardPage.this.selectionChanged(event);
814             }
815         });
816     }
817
818     private void createDefaultExternalization(NLSSubstitution[] substitutions, String JavaDoc defaultPrefix) {
819         for (int i= 0; i < substitutions.length; i++) {
820             NLSSubstitution substitution= substitutions[i];
821             if (substitution.getState() == NLSSubstitution.INTERNALIZED) {
822                 substitution.setState(NLSSubstitution.EXTERNALIZED);
823                 substitution.generateKey(substitutions);
824             }
825         }
826     }
827
828     private CellEditor[] createCellEditors() {
829         final CellEditor editors[]= new CellEditor[SIZE];
830         editors[STATE_PROP]= new MultiStateCellEditor(fTable, NLSSubstitution.STATE_COUNT, NLSSubstitution.DEFAULT);
831         editors[KEY_PROP]= new TextCellEditor(fTable);
832         editors[VAL_PROP]= new TextCellEditor(fTable);
833         return editors;
834     }
835
836     private void createSourceViewer(Composite parent) {
837         Composite c= new Composite(parent, SWT.NONE);
838         c.setLayoutData(new GridData(GridData.FILL_BOTH));
839         GridLayout gl= new GridLayout();
840         gl.marginHeight= 0;
841         gl.marginWidth= 0;
842         c.setLayout(gl);
843
844         Label l= new Label(c, SWT.NONE);
845         l.setText(NLSUIMessages.ExternalizeWizardPage_context);
846         l.setLayoutData(new GridData());
847
848         // source viewer
849
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
850         int styles= SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION;
851         IPreferenceStore store= JavaPlugin.getDefault().getCombinedPreferenceStore();
852         fSourceViewer= new JavaSourceViewer(c, null, null, false, styles, store);
853         fSourceViewer.configure(new JavaSourceViewerConfiguration(tools.getColorManager(), store, null, null));
854         fSourceViewer.getControl().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
855
856         try {
857
858             String JavaDoc contents= fCu.getBuffer().getContents();
859             IDocument document= new Document(contents);
860             tools.setupJavaDocumentPartitioner(document);
861
862             fSourceViewer.setDocument(document);
863             fSourceViewer.setEditable(false);
864
865             GridData gd= new GridData(GridData.FILL_BOTH);
866             gd.heightHint= convertHeightInCharsToPixels(10);
867             gd.widthHint= convertWidthInCharsToPixels(40);
868             fSourceViewer.getControl().setLayoutData(gd);
869
870         } catch (JavaModelException e) {
871             ExceptionHandler.handle(e, NLSUIMessages.ExternalizeWizardPage_exception_title, NLSUIMessages.ExternalizeWizardPage_exception_message);
872         }
873     }
874
875     private void createKeyPrefixField(Composite parent) {
876         Composite composite= new Composite(parent, SWT.NONE);
877         composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
878         GridLayout gl= new GridLayout();
879         gl.numColumns= 2;
880         gl.marginWidth= 0;
881         composite.setLayout(gl);
882
883         Label l= new Label(composite, SWT.NONE);
884         l.setText(NLSUIMessages.ExternalizeWizardPage_common_prefix);
885         l.setLayoutData(new GridData());
886
887         fPrefixField= new Text(composite, SWT.SINGLE | SWT.BORDER);
888         fPrefixField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
889         fPrefixField.setText(fNLSRefactoring.getPrefix());
890         fPrefixField.selectAll();
891
892         fPrefixField.addModifyListener(new ModifyListener() {
893             public void modifyText(ModifyEvent e) {
894                 fNLSRefactoring.setPrefix(fPrefixField.getText());
895                 validateKeys(true);
896             }
897         });
898     }
899     
900     private boolean isEclipseNLSAvailable() {
901         if (fNLSRefactoring == null || fNLSRefactoring.getCu() == null)
902             return false;
903         
904         IJavaProject jp= fNLSRefactoring.getCu().getJavaProject();
905         if (jp == null || !jp.exists())
906             return false;
907         
908         try {
909             return jp.findType("org.eclipse.osgi.util.NLS") != null; //$NON-NLS-1$
910
} catch (JavaModelException e) {
911             return false;
912         }
913     }
914     
915     private void createIsEclipseNLSCheckbox(Composite parent) {
916         if (fNLSRefactoring.isEclipseNLS() || isEclipseNLSAvailable()) {
917             fIsEclipseNLS= new Button(parent, SWT.CHECK);
918             fIsEclipseNLS.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
919             fIsEclipseNLS.setText(NLSUIMessages.ExternalizeWizardPage_isEclipseNLSCheckbox);
920             fIsEclipseNLS.setSelection(fNLSRefactoring.isEclipseNLS());
921             fIsEclipseNLS.setEnabled(willCreateAccessorClass());
922             fIsEclipseNLS.addSelectionListener(new SelectionAdapter() {
923                 public void widgetSelected(SelectionEvent e) {
924                     super.widgetDefaultSelected(e);
925                     boolean isEclipseNLS= fIsEclipseNLS.getSelection();
926                     fNLSRefactoring.setIsEclipseNLS(isEclipseNLS);
927                     if (isEclipseNLS) {
928                         fNLSRefactoring.setPrefix(fNLSRefactoring.getPrefix().replace('.', '_'));
929                     } else {
930                         fNLSRefactoring.setPrefix(fNLSRefactoring.getPrefix().replace('_', '.'));
931                     }
932                     fPrefixField.setText(fNLSRefactoring.getPrefix());
933                     validateKeys(true);
934                 }
935             });
936         }
937     }
938
939     private void validateKeys(boolean refreshTable) {
940         RefactoringStatus status= new RefactoringStatus();
941         checkInvalidKeys(status);
942         checkDuplicateKeys(status);
943         checkMissingKeys(status);
944         setPageComplete(status);
945         if (refreshTable)
946             fTableViewer.refresh(true);
947     }
948
949     private void checkInvalidKeys(RefactoringStatus status) {
950         for (int i= 0; i < fSubstitutions.length; i++) {
951             if (!isKeyValid(fSubstitutions[i], status))
952                 return;
953         }
954     }
955     
956     private boolean isKeyValid(NLSSubstitution substitution, RefactoringStatus status) {
957         if (substitution == null)
958             return false;
959         
960         if (substitution.getState() != NLSSubstitution.EXTERNALIZED)
961             return true;
962         
963         String JavaDoc key= substitution.getKey();
964         
965         if (fNLSRefactoring.isEclipseNLS()) {
966             if (key == null || key.length() == 0 || !Character.isJavaIdentifierStart(key.charAt(0))) {
967                 if (status != null)
968                     status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_EclipseNLS_keyInvalid);
969                 return false;
970             }
971             for (int i= 1, length= key.length(); i < length; i++) {
972                 if (!Character.isJavaIdentifierPart(key.charAt(i))) {
973                     if (status != null)
974                         status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_EclipseNLS_keyInvalid);
975                     return false;
976                 }
977             }
978         } else {
979             if (key == null || key.length() == 0) {
980                 if (status != null)
981                     status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_keyInvalid);
982                 return false;
983             }
984             // validation so keys don't contain spaces
985
for (int i= 0; i < key.length(); i++) {
986                 if (Character.isWhitespace(key.charAt(i))) {
987                     if (status != null)
988                         status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_keyInvalid);
989                     return false;
990                 }
991             }
992         }
993         
994         return true;
995     }
996     
997     private void checkDuplicateKeys(RefactoringStatus status) {
998         for (int i= 0; i < fSubstitutions.length; i++) {
999             NLSSubstitution substitution= fSubstitutions[i];
1000            if (conflictingKeys(substitution)) {
1001                status.addFatalError(NLSUIMessages.ExternalizeWizardPage_warning_conflicting);
1002                return;
1003            }
1004        }
1005    }
1006
1007    private void checkMissingKeys(RefactoringStatus status) {
1008        for (int i= 0; i < fSubstitutions.length; i++) {
1009            NLSSubstitution substitution= fSubstitutions[i];
1010            if ((substitution.getValue() == null) && (substitution.getKey() != null)) {
1011                status.addWarning(NLSUIMessages.ExternalizeWizardPage_warning_keymissing);
1012                return;
1013            }
1014        }
1015    }
1016
1017    private boolean conflictingKeys(NLSSubstitution substitution) {
1018        if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
1019            return substitution.isConflicting(fSubstitutions);
1020        }
1021        return false;
1022    }
1023
1024    private void createTableComposite(Composite parent) {
1025        Composite comp= new Composite(parent, SWT.NONE);
1026        comp.setFont(parent.getFont());
1027        
1028        comp.setLayoutData(new GridData(GridData.FILL_BOTH));
1029        
1030        FormLayout fl= new FormLayout();
1031        fl.marginWidth= 0;
1032        fl.marginHeight= 0;
1033        comp.setLayout(fl);
1034                
1035        Label l= new Label(comp, SWT.NONE);
1036        l.setText(NLSUIMessages.ExternalizeWizardPage_strings_to_externalize);
1037        FormData formData = new FormData();
1038        formData.left = new FormAttachment(0, 0);
1039        l.setLayoutData(formData);
1040        
1041        Control tableControl= createTable(comp);
1042        formData = new FormData();
1043        formData.top = new FormAttachment(l, 5);
1044        formData.left = new FormAttachment(0, 0);
1045        formData.right = new FormAttachment(100,0);
1046        formData.bottom = new FormAttachment(100,0);
1047        tableControl.setLayoutData(formData);
1048        
1049        fFilterCheckBox= new Button(comp, SWT.CHECK);
1050        fFilterCheckBox.setText(NLSUIMessages.ExternalizeWizardPage_filter_label);
1051        formData = new FormData();
1052        formData.right = new FormAttachment(100,0);
1053        fFilterCheckBox.setLayoutData(formData);
1054        fFilterCheckBox.addSelectionListener(new SelectionListener() {
1055            public void widgetSelected(SelectionEvent e) {
1056                doFilterCheckBoxPressed();
1057            }
1058
1059            public void widgetDefaultSelected(SelectionEvent e) {
1060            }
1061        });
1062        fFilterCheckBox.setSelection(hasNewOrMissingSubstitutions());
1063    }
1064    
1065    private boolean hasNewOrMissingSubstitutions() {
1066        for (int i= 0; i < fSubstitutions.length; i++) {
1067            NLSSubstitution curr= fSubstitutions[i];
1068            if (curr.getInitialState() == NLSSubstitution.INTERNALIZED) {
1069                return true;
1070            }
1071            if (curr.getInitialState() == NLSSubstitution.EXTERNALIZED && curr.getInitialValue() == null) {
1072                return true;
1073            }
1074        }
1075        return false;
1076    }
1077
1078    /**
1079     *
1080     */

1081    protected void doFilterCheckBoxPressed() {
1082        fTableViewer.refresh();
1083    }
1084
1085    private Control createTable(Composite parent) {
1086        Composite c= new Composite(parent, SWT.NONE);
1087        GridLayout gl= new GridLayout();
1088        gl.numColumns= 2;
1089        gl.marginWidth= 0;
1090        gl.marginHeight= 0;
1091        c.setLayout(gl);
1092
1093
1094        fTable= new Table(c, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.BORDER);
1095        fTable.setFont(parent.getFont());
1096        
1097        GridData tableGD= new GridData(GridData.FILL_BOTH);
1098        tableGD.heightHint= SWTUtil.getTableHeightHint(fTable, ROW_COUNT);
1099        //tableGD.widthHint= 40;
1100
fTable.setLayoutData(tableGD);
1101
1102        fTable.setLinesVisible(true);
1103
1104        TableLayout layout= new TableLayout();
1105        fTable.setLayout(layout);
1106        fTable.setHeaderVisible(true);
1107
1108        ColumnLayoutData[] columnLayoutData= new ColumnLayoutData[SIZE];
1109        columnLayoutData[STATE_PROP]= new ColumnPixelData(18, false, true);
1110        columnLayoutData[KEY_PROP]= new ColumnWeightData(40, true);
1111        columnLayoutData[VAL_PROP]= new ColumnWeightData(40, true);
1112
1113        for (int i= 0; i < fgTitles.length; i++) {
1114            TableColumn tc= new TableColumn(fTable, SWT.NONE, i);
1115            tc.setText(fgTitles[i]);
1116            layout.addColumnData(columnLayoutData[i]);
1117            tc.setResizable(columnLayoutData[i].resizable);
1118        }
1119
1120        createButtonComposite(c);
1121        return c;
1122    }
1123
1124    private void createButtonComposite(Composite parent) {
1125        Composite buttonComp= new Composite(parent, SWT.NONE);
1126        GridLayout gl= new GridLayout();
1127        gl.marginHeight= 0;
1128        gl.marginWidth= 0;
1129        buttonComp.setLayout(gl);
1130        buttonComp.setLayoutData(new GridData(GridData.FILL_VERTICAL));
1131        
1132        SelectionAdapter adapter= new SelectionAdapter() {
1133            public void widgetSelected(SelectionEvent e) {
1134                handleButtonPressed(e.widget);
1135            }
1136        };
1137
1138        fExternalizeButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Externalize_Selected, adapter);
1139        fIgnoreButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Ignore_Selected, adapter);
1140        fInternalizeButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Internalize_Selected, adapter);
1141
1142        new Label(buttonComp, SWT.NONE); // separator
1143

1144        fEditButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Edit_key_and_value, adapter);
1145        fRevertButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Revert_Selected, adapter);
1146        fRenameButton= createTaskButton(buttonComp, NLSUIMessages.ExternalizeWizardPage_Rename_Keys, adapter);
1147
1148        fEditButton.setEnabled(false);
1149        fRenameButton.setEnabled(false);
1150        buttonComp.pack();
1151    }
1152
1153    /**
1154     * @param widget
1155     */

1156    protected void handleButtonPressed(Widget widget) {
1157        if (widget == fExternalizeButton) {
1158            setSelectedTasks(NLSSubstitution.EXTERNALIZED);
1159        } else if (widget == fIgnoreButton) {
1160            setSelectedTasks(NLSSubstitution.IGNORED);
1161        } else if (widget == fInternalizeButton) {
1162            setSelectedTasks(NLSSubstitution.INTERNALIZED);
1163        } else if (widget == fEditButton) {
1164            openEditButton(fTableViewer.getSelection());
1165        } else if (widget == fRevertButton) {
1166            revertStateOfSelection();
1167        } else if (widget == fRenameButton) {
1168            openRenameDialog();
1169        }
1170    }
1171
1172    /**
1173     *
1174     */

1175    private void openRenameDialog() {
1176        IStructuredSelection sel= (IStructuredSelection) fTableViewer.getSelection();
1177        List JavaDoc elementsToRename= getExternalizedElements(sel);
1178        RenameKeysDialog dialog= new RenameKeysDialog(getShell(), elementsToRename);
1179        if (dialog.open() == Window.OK) {
1180            fTableViewer.refresh();
1181            updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
1182        }
1183    }
1184
1185    private void revertStateOfSelection() {
1186        List JavaDoc selection= getSelectedTableEntries();
1187        for (Iterator JavaDoc iter= selection.iterator(); iter.hasNext();) {
1188            NLSSubstitution substitution= (NLSSubstitution) iter.next();
1189            substitution.revert();
1190        }
1191        fTableViewer.refresh();
1192        updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
1193    }
1194    
1195    private Button createTaskButton(Composite parent, String JavaDoc label, SelectionAdapter adapter) {
1196        Button button= new Button(parent, SWT.PUSH);
1197        button.setText(label);
1198        button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
1199        SWTUtil.setButtonDimensionHint(button);
1200        button.addSelectionListener(adapter);
1201        return button;
1202    }
1203
1204    private void openEditButton(ISelection selection) {
1205        try {
1206            IStructuredSelection sel= (IStructuredSelection) fTableViewer.getSelection();
1207            NLSSubstitution substitution= (NLSSubstitution) sel.getFirstElement();
1208            if (substitution == null) {
1209                return;
1210            }
1211            
1212            NLSInputDialog dialog= new NLSInputDialog(getShell(), substitution);
1213            if (dialog.open() == Window.CANCEL)
1214                return;
1215            KeyValuePair kvPair= dialog.getResult();
1216            if (substitution.getState() == NLSSubstitution.EXTERNALIZED) {
1217                substitution.setKey(kvPair.getKey());
1218            }
1219            substitution.setValue(kvPair.getValue());
1220            validateKeys(false);
1221        } finally {
1222            fTableViewer.refresh();
1223            fTableViewer.getControl().setFocus();
1224            fTableViewer.setSelection(selection);
1225        }
1226    }
1227
1228    private List JavaDoc getSelectedTableEntries() {
1229        ISelection sel= fTableViewer.getSelection();
1230        if (sel instanceof IStructuredSelection)
1231            return((IStructuredSelection) sel).toList();
1232        else
1233            return Collections.EMPTY_LIST;
1234    }
1235
1236    private void setSelectedTasks(int state) {
1237        Assert.isTrue(state == NLSSubstitution.EXTERNALIZED || state == NLSSubstitution.IGNORED || state == NLSSubstitution.INTERNALIZED);
1238        List JavaDoc selected= getSelectedTableEntries();
1239        String JavaDoc[] props= new String JavaDoc[]{PROPERTIES[STATE_PROP]};
1240        for (Iterator JavaDoc iter= selected.iterator(); iter.hasNext();) {
1241            NLSSubstitution substitution= (NLSSubstitution) iter.next();
1242            substitution.setState(state);
1243            if ((substitution.getState() == NLSSubstitution.EXTERNALIZED) && substitution.hasStateChanged()) {
1244                substitution.generateKey(fSubstitutions);
1245            }
1246        }
1247        fTableViewer.update(selected.toArray(), props);
1248        fTableViewer.getControl().setFocus();
1249        updateButtonStates((IStructuredSelection) fTableViewer.getSelection());
1250    }
1251
1252    private void selectionChanged(SelectionChangedEvent event) {
1253        IStructuredSelection selection= (IStructuredSelection) event.getSelection();
1254        updateButtonStates(selection);
1255        updateSourceView(selection);
1256    }
1257
1258    private void updateSourceView(IStructuredSelection selection) {
1259        NLSSubstitution first= (NLSSubstitution) selection.getFirstElement();
1260        if (first != null) {
1261            Region region= first.getNLSElement().getPosition();
1262            fSourceViewer.setSelectedRange(region.getOffset(), region.getLength());
1263            fSourceViewer.revealRange(region.getOffset(), region.getLength());
1264        }
1265    }
1266
1267    private void updateButtonStates(IStructuredSelection selection) {
1268        fExternalizeButton.setEnabled(true);
1269        fIgnoreButton.setEnabled(true);
1270        fInternalizeButton.setEnabled(true);
1271        fRevertButton.setEnabled(true);
1272
1273        if (containsOnlyElementsOfSameState(NLSSubstitution.EXTERNALIZED, selection)) {
1274            fExternalizeButton.setEnabled(false);
1275        }
1276
1277        if (containsOnlyElementsOfSameState(NLSSubstitution.IGNORED, selection)) {
1278            fIgnoreButton.setEnabled(false);
1279        }
1280
1281        if (containsOnlyElementsOfSameState(NLSSubstitution.INTERNALIZED, selection)) {
1282            fInternalizeButton.setEnabled(false);
1283        }
1284
1285        if (!containsElementsWithChange(selection)) {
1286            fRevertButton.setEnabled(false);
1287        }
1288        
1289        fRenameButton.setEnabled(getExternalizedElements(selection).size() > 1);
1290        fEditButton.setEnabled(selection.size() == 1);
1291    }
1292
1293    private boolean containsElementsWithChange(IStructuredSelection selection) {
1294        for (Iterator JavaDoc iter= selection.iterator(); iter.hasNext();) {
1295            NLSSubstitution substitution= (NLSSubstitution) iter.next();
1296            if (substitution.hasPropertyFileChange() || substitution.hasSourceChange()) {
1297                return true;
1298            }
1299        }
1300        return false;
1301    }
1302        
1303    private List JavaDoc getExternalizedElements(IStructuredSelection selection) {
1304        ArrayList JavaDoc res= new ArrayList JavaDoc();
1305        for (Iterator JavaDoc iter= selection.iterator(); iter.hasNext();) {
1306            NLSSubstitution substitution= (NLSSubstitution) iter.next();
1307            if (substitution.getState() == NLSSubstitution.EXTERNALIZED && !substitution.hasStateChanged()) {
1308                res.add(substitution);
1309            }
1310        }
1311        return res;
1312    }
1313
1314    private boolean containsOnlyElementsOfSameState(int state, IStructuredSelection selection) {
1315        for (Iterator JavaDoc iter= selection.iterator(); iter.hasNext();) {
1316            NLSSubstitution substitution= (NLSSubstitution) iter.next();
1317            if (substitution.getState() != state) {
1318                return false;
1319            }
1320        }
1321        return true;
1322    }
1323
1324    public boolean performFinish() {
1325        return super.performFinish();
1326    }
1327
1328    public IWizardPage getNextPage() {
1329        return super.getNextPage();
1330    }
1331
1332    public void dispose() {
1333        storeAccessorDescriptions();
1334        //widgets will be disposed. only need to null'em
1335
fPrefixField= null;
1336        fSourceViewer= null;
1337        fTable= null;
1338        fTableViewer= null;
1339        fEditButton= null;
1340        super.dispose();
1341    }
1342}
1343
Popular Tags