KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > compare > internal > patch > InputPatchPage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Sebastian Davids <sdavids@gmx.de> - layout tweaks
11  * Matt McCutchen <hashproduct+eclipse@gmail.com> - Bug 180358 [Apply Patch] Cursor jumps to beginning of filename field on keystroke
12  *******************************************************************************/

13 package org.eclipse.compare.internal.patch;
14
15 import java.io.*;
16
17 import org.eclipse.compare.internal.*;
18 import org.eclipse.core.resources.*;
19 import org.eclipse.core.runtime.IPath;
20 import org.eclipse.core.runtime.Path;
21 import org.eclipse.jface.dialogs.*;
22 import org.eclipse.jface.dialogs.Dialog;
23 import org.eclipse.jface.viewers.*;
24 import org.eclipse.jface.wizard.IWizardPage;
25 import org.eclipse.jface.wizard.WizardPage;
26 import org.eclipse.swt.SWT;
27 import org.eclipse.swt.dnd.Clipboard;
28 import org.eclipse.swt.dnd.TextTransfer;
29 import org.eclipse.swt.events.*;
30 import org.eclipse.swt.graphics.Point;
31 import org.eclipse.swt.layout.GridData;
32 import org.eclipse.swt.layout.GridLayout;
33 import org.eclipse.swt.widgets.*;
34 import org.eclipse.ui.PlatformUI;
35 import org.eclipse.ui.model.WorkbenchContentProvider;
36 import org.eclipse.ui.model.WorkbenchLabelProvider;
37 import org.eclipse.ui.views.navigator.ResourceComparator;
38
39 import com.ibm.icu.text.MessageFormat;
40
41 /* package */ class InputPatchPage extends WizardPage {
42
43     // constants
44
protected static final int SIZING_TEXT_FIELD_WIDTH= 250;
45     protected static final int COMBO_HISTORY_LENGTH= 5;
46     
47     // dialog store id constants
48
private final static String JavaDoc PAGE_NAME= "PatchWizardPage1"; //$NON-NLS-1$
49
private final static String JavaDoc STORE_PATCH_FILES_ID= PAGE_NAME+".PATCH_FILES"; //$NON-NLS-1$
50
private final static String JavaDoc STORE_INPUT_METHOD_ID= PAGE_NAME+".INPUT_METHOD"; //$NON-NLS-1$
51
private final static String JavaDoc STORE_WORKSPACE_PATH_ID= PAGE_NAME+".WORKSPACE_PATH"; //$NON-NLS-1$
52

53     //patch input constants
54
protected final static int CLIPBOARD= 1;
55     protected final static int FILE= 2;
56     protected final static int WORKSPACE= 3;
57
58     protected final static String JavaDoc INPUTPATCHPAGE_NAME= "InputPatchPage"; //$NON-NLS-1$
59

60     static final char SEPARATOR= System.getProperty("file.separator").charAt(0); //$NON-NLS-1$
61

62     private boolean fShowError= false;
63     private String JavaDoc fPatchSource;
64     private boolean fPatchRead= false;
65     private PatchWizard fPatchWizard;
66     private ActivationListener fActivationListener= new ActivationListener();
67
68     // SWT widgets
69
private Button fUseClipboardButton;
70     private Combo fPatchFileNameField;
71     private Button fPatchFileBrowseButton;
72     private Button fUsePatchFileButton;
73     private Button fUseWorkspaceButton;
74     private Label fWorkspaceSelectLabel;
75     private TreeViewer fTreeViewer;
76     
77     class ActivationListener extends ShellAdapter {
78         public void shellActivated(ShellEvent e) {
79             // allow error messages if the selected input actually has something selected in it
80
fShowError=true;
81             switch(getInputMethod()) {
82             case FILE:
83                 fShowError= (fPatchFileNameField.getText() != ""); //$NON-NLS-1$
84
break;
85                 
86             case WORKSPACE:
87                 fShowError= (!fTreeViewer.getSelection().isEmpty());
88                 break;
89             }
90             updateWidgetEnablements();
91         }
92     }
93     
94     InputPatchPage(PatchWizard pw) {
95         super(INPUTPATCHPAGE_NAME, PatchMessages.InputPatchPage_title, null);
96         fPatchWizard= pw;
97         setMessage(PatchMessages.InputPatchPage_message);
98     }
99     
100     /*
101      * Get a path from the supplied text widget.
102      * @return org.eclipse.core.runtime.IPath
103      */

104     protected IPath getPathFromText(Text textField) {
105         return (new Path(textField.getText())).makeAbsolute();
106     }
107
108     /* package */ String JavaDoc getPatchName() {
109         if (getInputMethod() == CLIPBOARD)
110             return PatchMessages.InputPatchPage_Clipboard;
111         return getPatchFilePath();
112     }
113     
114     public void createControl(Composite parent) {
115                 
116         Composite composite= new Composite(parent, SWT.NULL);
117         composite.setLayout(new GridLayout());
118         composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
119         setControl(composite);
120
121         initializeDialogUnits(parent);
122         
123         buildPatchFileGroup(composite);
124         
125         // by default, whatever was used last was selected or
126
// default to File if nothing has been selected
127
restoreWidgetValues();
128         
129         // see if there are any better options presently selected (i.e workspace
130
// or clipboard)
131
adjustToCurrentTarget();
132         
133         // No error for dialog opening
134
fShowError= false;
135         clearErrorMessage();
136         updateWidgetEnablements();
137         
138         Shell shell= getShell();
139         shell.addShellListener(fActivationListener);
140         
141         Dialog.applyDialogFont(composite);
142         PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ICompareContextIds.PATCH_INPUT_WIZARD_PAGE);
143     }
144
145     /**
146      * Returns the next page depending on what type of patch is being applied:
147      * i) If the patch is a Workspace patch then it will proceed right to the PreviewPatchPage
148      * ii) If the patch is a single project patch then it will proceed to the PatchTargetPage, which
149      * allows the user to specify where to root the patch
150      * @return PreviewPatchPage if multi-project patch, PatchTargetPage if single project patch
151      */

152     public IWizardPage getNextPage() {
153
154         WorkspacePatcher patcher= ((PatchWizard) getWizard()).getPatcher();
155         
156         // Read in the patch
157
readInPatch();
158         
159         FileDiff[] diffs= patcher.getDiffs();
160         if (diffs == null || diffs.length == 0) {
161             String JavaDoc format= PatchMessages.InputPatchPage_NoDiffsFound_format;
162             String JavaDoc message= MessageFormat.format(format, new String JavaDoc[] { fPatchSource });
163             MessageDialog.openInformation(null,
164                 PatchMessages.InputPatchPage_PatchErrorDialog_title, message);
165             return this;
166         }
167
168         // guess prefix count
169
int guess= 0; // guessPrefix(diffs);
170
patcher.setStripPrefixSegments(guess);
171
172         // If this is a workspace patch we don't need to set a target as the targets will be figured out from
173
// all of the projects that make up the patch and continue on to final preview page
174
// else go on to target selection page
175
if (patcher.isWorkspacePatch()) {
176             return fPatchWizard.getPage(PreviewPatchPage2.PREVIEWPATCHPAGE_NAME);
177         }
178
179         return super.getNextPage();
180     }
181
182     /*
183      * Reads in the patch contents
184      */

185     public void readInPatch(){
186         WorkspacePatcher patcher= ((PatchWizard) getWizard()).getPatcher();
187         // Create a reader for the input
188
Reader reader= null;
189         try {
190             int inputMethod= getInputMethod();
191             if (inputMethod == CLIPBOARD) {
192                 Control c= getControl();
193                 if (c != null) {
194                     Clipboard clipboard= new Clipboard(c.getDisplay());
195                     Object JavaDoc o= clipboard.getContents(TextTransfer.getInstance());
196                     clipboard.dispose();
197                     if (o instanceof String JavaDoc)
198                         reader= new StringReader((String JavaDoc)o);
199                 }
200                 fPatchSource= PatchMessages.InputPatchPage_Clipboard_title;
201             } else if (inputMethod==FILE) {
202                 String JavaDoc patchFilePath= getPatchFilePath();
203                 if (patchFilePath != null) {
204                     try {
205                         reader= new FileReader(patchFilePath);
206                     } catch (FileNotFoundException ex) {
207                         MessageDialog.openError(null,
208                             PatchMessages.InputPatchPage_PatchErrorDialog_title,
209                             PatchMessages.InputPatchPage_PatchFileNotFound_message);
210                     }
211                 }
212                 fPatchSource= PatchMessages.InputPatchPage_PatchFile_title;
213             } else if (inputMethod==WORKSPACE) {
214                 // Get the selected patch file (tree will only allow for one selection)
215
IResource[] resources= Utilities.getResources(fTreeViewer.getSelection());
216                 IResource patchFile= resources[0];
217                 if (patchFile != null) {
218                     try {
219                         reader= new FileReader(patchFile.getRawLocation().toFile());
220                     } catch (FileNotFoundException ex) {
221                         MessageDialog.openError(null, PatchMessages.InputPatchPage_PatchErrorDialog_title, PatchMessages.InputPatchPage_PatchFileNotFound_message);
222                     } catch (NullPointerException JavaDoc nex) {
223                         //in case the path doesn't exist
224
MessageDialog.openError(null, PatchMessages.InputPatchPage_PatchErrorDialog_title, PatchMessages.InputPatchPage_PatchFileNotFound_message);
225                     }
226                 }
227                 fPatchSource= PatchMessages.InputPatchPage_WorkspacePatch_title;
228             }
229             
230             // parse the input
231
if (reader != null) {
232                 try {
233                     patcher.parse(new BufferedReader(reader));
234                     //report back to the patch wizard that the patch has been read in
235
fPatchWizard.patchReadIn();
236                     fPatchRead=true;
237                 } catch (Exception JavaDoc ex) {
238                     // Ignore. User will be informed of error since patcher contains no diffs
239
}
240             }
241         } finally {
242             if (reader != null) {
243                 try {
244                     reader.close();
245                 } catch (IOException x) {
246                     // silently ignored
247
}
248             }
249         }
250     }
251     
252     /* (non-JavaDoc)
253      * Method declared in IWizardPage.
254      */

255     public boolean canFlipToNextPage() {
256         // we can't call getNextPage to determine if flipping is allowed since computing
257
// the next page is quite expensive. So we say yes if the page is complete.
258
return isPageComplete();
259     }
260     
261     private void setEnablePatchFile(boolean enable) {
262         fPatchFileNameField.setEnabled(enable);
263         fPatchFileBrowseButton.setEnabled(enable);
264     }
265
266     private void setEnableWorkspacePatch(boolean enable) {
267         fWorkspaceSelectLabel.setEnabled(enable);
268         fTreeViewer.getTree().setEnabled(enable);
269     }
270
271     /*
272      * Create the group for selecting the patch file
273      */

274     private void buildPatchFileGroup(Composite parent) {
275
276         final Composite composite= new Composite(parent, SWT.NULL);
277         GridLayout gridLayout= new GridLayout();
278         gridLayout.numColumns= 3;
279         composite.setLayout(gridLayout);
280         composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
281
282         // 1st row
283
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
284         gd.horizontalSpan= 3;
285         fUseClipboardButton= new Button(composite, SWT.RADIO);
286         fUseClipboardButton.setText(PatchMessages.InputPatchPage_UseClipboardButton_text);
287         fUseClipboardButton.setLayoutData(gd);
288
289         // 2nd row
290
fUsePatchFileButton= new Button(composite, SWT.RADIO);
291         fUsePatchFileButton.setText(PatchMessages.InputPatchPage_FileButton_text);
292
293         fPatchFileNameField= new Combo(composite, SWT.BORDER);
294         gd= new GridData(GridData.FILL_HORIZONTAL);
295         gd.widthHint= SIZING_TEXT_FIELD_WIDTH;
296         fPatchFileNameField.setLayoutData(gd);
297
298         fPatchFileBrowseButton= new Button(composite, SWT.PUSH);
299         fPatchFileBrowseButton.setText(PatchMessages.InputPatchPage_ChooseFileButton_text);
300         GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
301         int widthHint= convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
302         Point minSize= fPatchFileBrowseButton.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
303         data.widthHint= Math.max(widthHint, minSize.x);
304         fPatchFileBrowseButton.setLayoutData(data);
305
306         //3rd row
307
fUseWorkspaceButton= new Button(composite, SWT.RADIO);
308         fUseWorkspaceButton.setText(PatchMessages.InputPatchPage_UseWorkspaceButton_text);
309         gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
310         fUseWorkspaceButton.setLayoutData(gd);
311
312         addWorkspaceControls(parent);
313
314         // Add listeners
315
fUseClipboardButton.addSelectionListener(new SelectionAdapter() {
316             public void widgetSelected(SelectionEvent e) {
317                 if (!fUseClipboardButton.getSelection())
318                     return;
319                 
320                 clearErrorMessage();
321                 fShowError= true;
322                 int state= getInputMethod();
323                 setEnablePatchFile(state == FILE);
324                 setEnableWorkspacePatch(state == WORKSPACE);
325                 updateWidgetEnablements();
326             }
327         });
328         
329         fUsePatchFileButton.addSelectionListener(new SelectionAdapter() {
330             public void widgetSelected(SelectionEvent e) {
331                 if (!fUsePatchFileButton.getSelection())
332                     return;
333                 //If there is anything typed in at all
334
clearErrorMessage();
335                 fShowError= (fPatchFileNameField.getText() != ""); //$NON-NLS-1$
336
int state= getInputMethod();
337                 setEnablePatchFile(state==FILE);
338                 setEnableWorkspacePatch(state==WORKSPACE);
339                 updateWidgetEnablements();
340             }
341         });
342         fPatchFileNameField.addSelectionListener(new SelectionAdapter() {
343             public void widgetSelected(SelectionEvent e) {
344                 updateWidgetEnablements();
345             }
346         });
347         fPatchFileNameField.addModifyListener(new ModifyListener() {
348             public void modifyText(ModifyEvent e) {
349                 clearErrorMessage();
350                 fShowError= true;
351                 updateWidgetEnablements();
352             }
353         });
354         fPatchFileBrowseButton.addSelectionListener(new SelectionAdapter() {
355             public void widgetSelected(SelectionEvent e) {
356                 clearErrorMessage();
357                 fShowError= true;
358                 handlePatchFileBrowseButtonPressed();
359                 updateWidgetEnablements();
360             }
361         });
362         fUseWorkspaceButton.addSelectionListener(new SelectionAdapter() {
363             public void widgetSelected(SelectionEvent e) {
364                 if (!fUseWorkspaceButton.getSelection())
365                     return;
366                 clearErrorMessage();
367                 // If there is anything typed in at all
368
fShowError= (!fTreeViewer.getSelection().isEmpty());
369                 int state= getInputMethod();
370                 setEnablePatchFile(state == FILE);
371                 setEnableWorkspacePatch(state == WORKSPACE);
372                 updateWidgetEnablements();
373             }
374         });
375
376         fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
377             public void selectionChanged(SelectionChangedEvent event) {
378                 clearErrorMessage();
379                 updateWidgetEnablements();
380             }
381         });
382         
383         fTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
384             public void doubleClick(DoubleClickEvent event) {
385                 ISelection selection= event.getSelection();
386                 if (selection instanceof TreeSelection) {
387                     TreeSelection treeSel= (TreeSelection) selection;
388                     Object JavaDoc res= treeSel.getFirstElement();
389                     if (res != null) {
390                         if (res instanceof IProject || res instanceof IFolder) {
391                             if (fTreeViewer.getExpandedState(res))
392                                 fTreeViewer.collapseToLevel(res, 1);
393                             else
394                                 fTreeViewer.expandToLevel(res, 1);
395                         } else if (res instanceof IFile)
396                             fPatchWizard.showPage(getNextPage());
397                     }
398                 }
399             }
400         });
401     }
402
403     private void addWorkspaceControls(Composite composite) {
404
405         Composite newComp= new Composite(composite, SWT.NONE);
406         GridLayout layout= new GridLayout(1, false);
407         layout.marginLeft= 16; // align w/ lable of check button
408
newComp.setLayout(layout);
409         newComp.setLayoutData(new GridData(GridData.FILL_BOTH));
410             
411         fWorkspaceSelectLabel= new Label(newComp, SWT.LEFT);
412         fWorkspaceSelectLabel.setText(PatchMessages.InputPatchPage_WorkspaceSelectPatch_text);
413         
414         fTreeViewer= new TreeViewer(newComp, SWT.BORDER);
415         fTreeViewer.getTree().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
416
417         fTreeViewer.setLabelProvider(new WorkbenchLabelProvider());
418         fTreeViewer.setContentProvider(new WorkbenchContentProvider());
419         fTreeViewer.setComparator(new ResourceComparator(ResourceComparator.NAME));
420         fTreeViewer.setInput(ResourcesPlugin.getWorkspace().getRoot());
421     }
422
423
424     /**
425      * Updates the enable state of this page's controls.
426      */

427     private void updateWidgetEnablements() {
428         
429         String JavaDoc error= null;
430
431         boolean gotPatch= false;
432         int inputMethod= getInputMethod();
433         if (inputMethod==CLIPBOARD) {
434             Control c= getControl();
435             if (c != null) {
436                 Clipboard clipboard= new Clipboard(c.getDisplay());
437                 Object JavaDoc o= clipboard.getContents(TextTransfer.getInstance());
438                 clipboard.dispose();
439                 if (o instanceof String JavaDoc) {
440                     String JavaDoc s= ((String JavaDoc) o).trim();
441                     if (s.length() > 0)
442                         gotPatch= true;
443                     else
444                         error= PatchMessages.InputPatchPage_ClipboardIsEmpty_message;
445                 } else
446                     error= PatchMessages.InputPatchPage_NoTextInClipboard_message;
447             } else
448                 error= PatchMessages.InputPatchPage_CouldNotReadClipboard_message;
449         } else if (inputMethod==FILE) {
450             String JavaDoc path= fPatchFileNameField.getText();
451             if (path != null && path.length() > 0) {
452                 File file= new File(path);
453                 gotPatch= file.exists() && file.isFile() && file.length() > 0;
454                 if (!gotPatch)
455                     error= PatchMessages.InputPatchPage_CannotLocatePatch_message + path;
456             } else {
457                 error= PatchMessages.InputPatchPage_NoFileName_message;
458             }
459         } else if (inputMethod == WORKSPACE) {
460             //Get the selected patch file (tree will only allow for one selection)
461
IResource[] resources= Utilities.getResources(fTreeViewer.getSelection());
462             if (resources != null && resources.length > 0) {
463                 IResource patchFile= resources[0];
464                 if (patchFile != null && patchFile.getType() == IResource.FILE) {
465                     File actualFile= patchFile.getRawLocation().toFile();
466                     gotPatch= actualFile.exists()&&actualFile.isFile()&&actualFile.length() > 0;
467                     if (!gotPatch)
468                         error= PatchMessages.InputPatchPage_FileSelectedNotPatch_message;
469                 }
470             } else {
471                 error= PatchMessages.InputPatchPage_NoFileName_message;
472             }
473         }
474
475         setPageComplete(gotPatch);
476
477         if (fShowError)
478             setErrorMessage(error);
479     }
480     
481     protected void handlePatchFileBrowseButtonPressed() {
482         FileDialog dialog= new FileDialog(getShell(), SWT.NONE);
483         dialog.setText(PatchMessages.InputPatchPage_SelectPatchFileDialog_title);
484         String JavaDoc patchFilePath= getPatchFilePath();
485         if (patchFilePath != null) {
486             int lastSegment= patchFilePath.lastIndexOf(SEPARATOR);
487             if (lastSegment > 0) {
488                 patchFilePath= patchFilePath.substring(0, lastSegment);
489             }
490         }
491         dialog.setFilterPath(patchFilePath);
492         String JavaDoc res= dialog.open();
493         if (res == null)
494             return;
495         
496         patchFilePath= dialog.getFileName();
497         IPath filterPath= new Path(dialog.getFilterPath());
498         IPath path= filterPath.append(patchFilePath).makeAbsolute();
499         patchFilePath= path.toOSString();
500         //fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString());
501

502         fPatchFileNameField.setText(patchFilePath);
503         //setSourceName(patchFilePath);
504
}
505     
506     /**
507      * Sets the source name of the import to be the supplied path.
508      * Adds the name of the path to the list of items in the
509      * source combo and selects it.
510      *
511      * @param path the path to be added
512      */

513     protected void setSourceName(String JavaDoc path) {
514     
515         if (path.length() > 0) {
516     
517             String JavaDoc[] currentItems= fPatchFileNameField.getItems();
518             int selectionIndex= -1;
519             for (int i= 0; i < currentItems.length; i++)
520                 if (currentItems[i].equals(path))
521                     selectionIndex= i;
522             
523             if (selectionIndex < 0) { // not found in history
524
int oldLength= currentItems.length;
525                 String JavaDoc[] newItems= new String JavaDoc[oldLength + 1];
526                 System.arraycopy(currentItems, 0, newItems, 0, oldLength);
527                 newItems[oldLength]= path;
528                 fPatchFileNameField.setItems(newItems);
529                 selectionIndex= oldLength;
530             }
531             fPatchFileNameField.select(selectionIndex);
532     
533             //resetSelection();
534
}
535     }
536     
537     /**
538      * The Finish button was pressed. Try to do the required work now and answer
539      * a boolean indicating success. If false is returned then the wizard will
540      * not close.
541      *
542      * @return boolean
543      */

544     public boolean finish() {
545 // if (!ensureSourceIsValid())
546
// return false;
547

548         saveWidgetValues();
549     
550 // Iterator resourcesEnum= getSelectedResources().iterator();
551
// List fileSystemObjects= new ArrayList();
552
// while (resourcesEnum.hasNext()) {
553
// fileSystemObjects.add(
554
// ((FileSystemElement) resourcesEnum.next()).getFileSystemObject());
555
// }
556
//
557
// if (fileSystemObjects.size() > 0)
558
// return importResources(fileSystemObjects);
559
//
560
// MessageDialog
561
// .openInformation(
562
// getContainer().getShell(),
563
// DataTransferMessages.getString("DataTransfer.information"), //$NON-NLS-1$
564
// DataTransferMessages.getString("FileImport.noneSelected")); //$NON-NLS-1$
565
//
566
// return false;
567

568         return true;
569     }
570     
571     /**
572      * Use the dialog store to restore widget values to the values that they held
573      * last time this wizard was used to completion
574      */

575     private void restoreWidgetValues() {
576
577         int inputMethod= FILE;
578
579         IDialogSettings settings= getDialogSettings();
580         if (settings != null) {
581
582             try {
583                 inputMethod= settings.getInt(STORE_INPUT_METHOD_ID);
584             } catch (NumberFormatException JavaDoc ex) {
585                 //OK - no value stored in settings; just use CLIPBOARD
586
}
587
588             // set filenames history
589
String JavaDoc[] sourceNames= settings.getArray(STORE_PATCH_FILES_ID);
590             if (sourceNames != null)
591                 for (int i= 0; i < sourceNames.length; i++)
592                     if (sourceNames[i] != null && sourceNames[i].length() > 0)
593                         fPatchFileNameField.add(sourceNames[i]);
594             
595             // set patch file path
596
String JavaDoc patchFilePath= settings.get(STORE_PATCH_FILES_ID);
597             if (patchFilePath != null)
598                 setSourceName(patchFilePath);
599             
600             // If the previous apply patch was used with a clipboard, we need to check
601
// if there is a valid patch on the clipboard. This will be done in adjustToCurrentTarget()
602
// so just set it to FILE now and, if there exists a patch on the clipboard, then clipboard
603
// will be selected automatically
604
if (inputMethod == CLIPBOARD){
605                 inputMethod= FILE;
606                 fPatchFileNameField.deselectAll();
607             }
608             
609             //set the workspace patch selection
610
String JavaDoc workspaceSetting= settings.get(STORE_WORKSPACE_PATH_ID);
611             if (workspaceSetting != null && workspaceSetting.length() > 0) {
612                 // See if this resource still exists in the workspace
613
try {
614                     IPath path= new Path(workspaceSetting);
615                     IFile targetFile= ResourcesPlugin.getWorkspace().getRoot().getFile(path);
616                     if (fTreeViewer != null && targetFile.exists()){
617                         fTreeViewer.expandToLevel(targetFile, 0);
618                         fTreeViewer.setSelection(new StructuredSelection(targetFile));
619                     }
620                 } catch (RuntimeException JavaDoc e) {
621                     // Ignore. The setting was invalid
622
}
623             } else {
624                 //check to see if the current input is set to workspace - if it is switch it
625
//back to clipboard since there is no corresponding element to go along with
626
//the tree viewer
627
if (inputMethod == WORKSPACE)
628                     inputMethod= FILE;
629             }
630         }
631
632         // set radio buttons state
633
setInputButtonState(inputMethod);
634     }
635     
636     /**
637      * Since Finish was pressed, write widget values to the dialog store so that they
638      * will persist into the next invocation of this wizard page
639      */

640     void saveWidgetValues() {
641         IDialogSettings settings= getDialogSettings();
642         if (settings != null) {
643
644             settings.put(STORE_INPUT_METHOD_ID, getInputMethod());
645             settings.put(STORE_PATCH_FILES_ID, getPatchFilePath());
646             
647             // update source names history
648
String JavaDoc[] sourceNames= settings.getArray(STORE_PATCH_FILES_ID);
649             if (sourceNames == null)
650                 sourceNames= new String JavaDoc[0];
651     
652             sourceNames= addToHistory(sourceNames, getPatchFilePath());
653             settings.put(STORE_PATCH_FILES_ID, sourceNames);
654             
655             // save the workspace selection
656
settings.put(STORE_WORKSPACE_PATH_ID, getWorkspacePath());
657             
658         }
659     }
660     
661     private String JavaDoc getWorkspacePath() {
662         if (fTreeViewer != null){
663             IResource[] resources= Utilities.getResources(fTreeViewer.getSelection());
664             if (resources.length > 0) {
665                 IResource patchFile= resources[0];
666                 return patchFile.getFullPath().toString();
667             }
668             
669         }
670         return ""; //$NON-NLS-1$
671
}
672
673     // static helpers
674

675     /**
676      * Checks to see if the file that has been selected for Apply Patch
677      * is actually a patch
678      * @return true if the file selected to run Apply Patch on in the workspace is a patch file
679      * or if the clipboard contains a patch
680      */

681     private boolean adjustToCurrentTarget() {
682         // readjust selection if there is a patch selected in the workspace or on the clipboard
683
// check workspace first
684
IResource patchTarget= fPatchWizard.getTarget();
685         if (patchTarget instanceof IFile) {
686             Reader reader= null;
687             try {
688                 try {
689                     reader= new FileReader(patchTarget.getRawLocation().toFile());
690                     if (isPatchFile(reader)) {
691                         // set choice to workspace
692
setInputButtonState(WORKSPACE);
693                         if (fTreeViewer != null && patchTarget.exists()) {
694                             fTreeViewer.expandToLevel(patchTarget, 0);
695                             fTreeViewer.setSelection(new StructuredSelection(patchTarget));
696                         }
697                         return true;
698                     }
699                 } catch (FileNotFoundException ex) {
700                     // silently ignored
701
} catch (NullPointerException JavaDoc nex) {
702                     // silently ignored
703
}
704
705             } finally {
706                 if (reader != null) {
707                     try {
708                         reader.close();
709                     } catch (IOException x) {
710                         // silently ignored
711
}
712                 }
713             }
714         }
715         // check out clipboard contents
716
Reader reader = null;
717         Control c = getControl();
718         if (c != null) {
719             Clipboard clipboard = new Clipboard(c.getDisplay());
720             Object JavaDoc o = clipboard.getContents(TextTransfer.getInstance());
721             clipboard.dispose();
722             try {
723                 if (o instanceof String JavaDoc) {
724                     reader = new StringReader((String JavaDoc) o);
725                     if (isPatchFile(reader)) {
726                         setInputButtonState(CLIPBOARD);
727                         return true;
728                     }
729                 }
730             } finally {
731                 if (reader != null) {
732                     try {
733                         reader.close();
734                     } catch (IOException x) {
735                         // silently ignored
736
}
737                 }
738             }
739         }
740         return false;
741     }
742     
743     
744
745     private boolean isPatchFile(Reader reader) {
746         WorkspacePatcher patcher= ((PatchWizard) getWizard()).getPatcher();
747
748         try {
749             patcher.parse(new BufferedReader(reader));
750         } catch (Exception JavaDoc ex) {
751             return false;
752         }
753
754         FileDiff[] diffs= patcher.getDiffs();
755         if (diffs == null || diffs.length == 0)
756             return false;
757         return true;
758     }
759     
760     /*
761      * Clears the dialog message box
762      */

763     private void clearErrorMessage(){
764         setErrorMessage(null);
765     }
766     
767     private void setInputButtonState(int state) {
768
769         switch (state) {
770         case CLIPBOARD:
771             fUseClipboardButton.setSelection(true);
772             fUsePatchFileButton.setSelection(false);
773             fUseWorkspaceButton.setSelection(false);
774             break;
775
776         case FILE:
777             fUseClipboardButton.setSelection(false);
778             fUsePatchFileButton.setSelection(true);
779             fUseWorkspaceButton.setSelection(false);
780             break;
781
782         case WORKSPACE:
783             fUseClipboardButton.setSelection(false);
784             fUsePatchFileButton.setSelection(false);
785             fUseWorkspaceButton.setSelection(true);
786             break;
787         }
788
789         setEnablePatchFile(state == FILE);
790         setEnableWorkspacePatch(state == WORKSPACE);
791     }
792
793     protected int getInputMethod() {
794         if (fUseClipboardButton.getSelection())
795             return CLIPBOARD;
796         if (fUsePatchFileButton.getSelection())
797             return FILE;
798         return WORKSPACE;
799     }
800
801     private String JavaDoc getPatchFilePath() {
802         if (fPatchFileNameField != null)
803             return fPatchFileNameField.getText();
804         return ""; //$NON-NLS-1$
805
}
806
807     /*
808      * Adds an entry to a history, while taking care of duplicate history items
809      * and excessively long histories. The assumption is made that all histories
810      * should be of length <code>COMBO_HISTORY_LENGTH</code>.
811      *
812      * @param history the current history
813      * @param newEntry the entry to add to the history
814      */

815     protected static String JavaDoc[] addToHistory(String JavaDoc[] history, String JavaDoc newEntry) {
816         java.util.ArrayList JavaDoc l= new java.util.ArrayList JavaDoc(java.util.Arrays.asList(history));
817
818         l.remove(newEntry);
819         l.add(0,newEntry);
820     
821         // since only one new item was added, we can be over the limit
822
// by at most one item
823
if (l.size() > COMBO_HISTORY_LENGTH)
824             l.remove(COMBO_HISTORY_LENGTH);
825         
826         return (String JavaDoc[]) l.toArray(new String JavaDoc[l.size()]);
827     }
828
829     public boolean isPatchRead() {
830         return fPatchRead;
831     }
832 }
833
834
Popular Tags