KickJava   Java API By Example, From Geeks To Geeks.

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


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  * Sebastian Davids <sdavids@gmx.de> - layout tweaks
11  *******************************************************************************/

12 package org.eclipse.compare.internal.patch;
13
14 import java.io.ByteArrayInputStream JavaDoc;
15 import java.io.InputStream JavaDoc;
16 import java.lang.reflect.InvocationTargetException JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20
21 import org.eclipse.compare.CompareConfiguration;
22 import org.eclipse.compare.CompareUI;
23 import org.eclipse.compare.CompareViewerSwitchingPane;
24 import org.eclipse.compare.IEncodedStreamContentAccessor;
25 import org.eclipse.compare.ITypedElement;
26 import org.eclipse.compare.Splitter;
27 import org.eclipse.compare.internal.ICompareContextIds;
28 import org.eclipse.compare.internal.Utilities;
29 import org.eclipse.compare.structuremergeviewer.DiffNode;
30 import org.eclipse.compare.structuremergeviewer.Differencer;
31 import org.eclipse.compare.structuremergeviewer.ICompareInput;
32 import org.eclipse.core.resources.IFile;
33 import org.eclipse.core.resources.IProject;
34 import org.eclipse.core.resources.IWorkspace;
35 import org.eclipse.core.resources.ResourcesPlugin;
36 import org.eclipse.core.runtime.IPath;
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.jface.dialogs.Dialog;
39 import org.eclipse.jface.dialogs.IDialogConstants;
40 import org.eclipse.jface.operation.IRunnableWithProgress;
41 import org.eclipse.jface.viewers.CheckStateChangedEvent;
42 import org.eclipse.jface.viewers.DecoratingLabelProvider;
43 import org.eclipse.jface.viewers.DoubleClickEvent;
44 import org.eclipse.jface.viewers.ICheckStateListener;
45 import org.eclipse.jface.viewers.IDoubleClickListener;
46 import org.eclipse.jface.viewers.ISelection;
47 import org.eclipse.jface.viewers.ISelectionChangedListener;
48 import org.eclipse.jface.viewers.IStructuredSelection;
49 import org.eclipse.jface.viewers.SelectionChangedEvent;
50 import org.eclipse.jface.viewers.StructuredSelection;
51 import org.eclipse.jface.viewers.TreeSelection;
52 import org.eclipse.jface.viewers.TreeViewer;
53 import org.eclipse.jface.viewers.Viewer;
54 import org.eclipse.jface.wizard.WizardPage;
55 import org.eclipse.osgi.util.NLS;
56 import org.eclipse.swt.SWT;
57 import org.eclipse.swt.events.ModifyEvent;
58 import org.eclipse.swt.events.ModifyListener;
59 import org.eclipse.swt.events.SelectionAdapter;
60 import org.eclipse.swt.events.SelectionEvent;
61 import org.eclipse.swt.graphics.Image;
62 import org.eclipse.swt.graphics.Point;
63 import org.eclipse.swt.layout.GridData;
64 import org.eclipse.swt.layout.GridLayout;
65 import org.eclipse.swt.widgets.Button;
66 import org.eclipse.swt.widgets.Combo;
67 import org.eclipse.swt.widgets.Composite;
68 import org.eclipse.swt.widgets.Control;
69 import org.eclipse.swt.widgets.Group;
70 import org.eclipse.swt.widgets.Label;
71 import org.eclipse.swt.widgets.Shell;
72 import org.eclipse.swt.widgets.Text;
73 import org.eclipse.ui.PlatformUI;
74 import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer;
75 import org.eclipse.ui.model.BaseWorkbenchContentProvider;
76 import org.eclipse.ui.model.WorkbenchLabelProvider;
77 import org.eclipse.ui.model.WorkbenchViewerSorter;
78 import org.eclipse.ui.views.navigator.ResourceSorter;
79
80 import com.ibm.icu.text.MessageFormat;
81
82 /**
83  * Shows the parsed patch file and any mismatches
84  * between files, hunks and the currently selected
85  * resources.
86  */

87 /* package */ class PreviewPatchPage extends WizardPage {
88         
89     /**
90      * Used with CompareInput
91      */

92     static class HunkInput implements ITypedElement, IEncodedStreamContentAccessor {
93         static final String JavaDoc UTF_16= "UTF-16"; //$NON-NLS-1$
94
String JavaDoc fContent;
95         String JavaDoc fType;
96         
97         HunkInput(String JavaDoc type, String JavaDoc s) {
98             fType= type;
99             fContent= s;
100         }
101         public Image getImage() {
102             return null;
103         }
104         public String JavaDoc getName() {
105             return PatchMessages.PreviewPatchPage_NoName_text;
106         }
107         public String JavaDoc getType() {
108             return fType;
109         }
110         public InputStream JavaDoc getContents() {
111             return new ByteArrayInputStream JavaDoc(Utilities.getBytes(fContent, UTF_16));
112         }
113         public String JavaDoc getCharset() {
114             return UTF_16;
115         }
116     }
117
118     class RetargetPatchDialog extends Dialog {
119
120         protected TreeViewer rpTreeViewer;
121         protected DiffProject rpSelectedProject;
122         protected IProject rpTargetProject;
123
124         public RetargetPatchDialog(Shell shell, ISelection selection) {
125             super(shell);
126             setShellStyle(getShellStyle()|SWT.RESIZE);
127             if (selection instanceof IStructuredSelection) {
128                 rpSelectedProject= (DiffProject) ((IStructuredSelection) selection).getFirstElement();
129             }
130         }
131
132         protected Control createDialogArea(Composite parent) {
133             Composite composite= (Composite) super.createDialogArea(parent);
134
135             initializeDialogUnits(parent);
136
137             getShell().setText(PatchMessages.PreviewPatchPage_RetargetPatch);
138
139             GridLayout layout= new GridLayout();
140             layout.numColumns= 1;
141             layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
142             layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
143             composite.setLayout(layout);
144             final GridData data= new GridData(SWT.FILL, SWT.FILL, true, true);
145             composite.setLayoutData(data);
146
147             //add controls to composite as necessary
148
Label label= new Label(composite, SWT.LEFT|SWT.WRAP);
149             label.setText(NLS.bind(PatchMessages.PreviewPatchPage_SelectProject, rpSelectedProject.getName()));
150             final GridData data2= new GridData(SWT.FILL, SWT.BEGINNING, true, false);
151             label.setLayoutData(data2);
152
153             rpTreeViewer= new TreeViewer(composite, SWT.BORDER);
154             GridData gd= new GridData(SWT.FILL, SWT.FILL, true, true);
155             gd.widthHint= 0;
156             gd.heightHint= 0;
157             rpTreeViewer.getTree().setLayoutData(gd);
158
159             rpTreeViewer.setContentProvider(new RetargetPatchContentProvider());
160             rpTreeViewer.setLabelProvider(new WorkbenchLabelProvider());
161             rpTreeViewer.setSorter(new ResourceSorter(ResourceSorter.NAME));
162             rpTreeViewer.setInput(ResourcesPlugin.getWorkspace());
163             rpTreeViewer.setSelection(new StructuredSelection(rpSelectedProject.getProject()));
164
165             setupListeners();
166
167             Dialog.applyDialogFont(composite);
168             
169             return parent;
170         }
171
172         protected void okPressed() {
173             rpSelectedProject.setProject(rpTargetProject);
174             super.okPressed();
175         }
176
177         void setupListeners() {
178             rpTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
179                 public void selectionChanged(SelectionChangedEvent event) {
180                     IStructuredSelection s= (IStructuredSelection) event.getSelection();
181                     Object JavaDoc obj= s.getFirstElement();
182                     if (obj instanceof IProject)
183                         rpTargetProject= (IProject) obj;
184                 }
185             });
186
187             rpTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
188                 public void doubleClick(DoubleClickEvent event) {
189                     ISelection s= event.getSelection();
190                     if (s instanceof IStructuredSelection) {
191                         Object JavaDoc item= ((IStructuredSelection) s).getFirstElement();
192                         if (rpTreeViewer.getExpandedState(item))
193                             rpTreeViewer.collapseToLevel(item, 1);
194                         else
195                             rpTreeViewer.expandToLevel(item, 1);
196                     }
197                 }
198             });
199
200         }
201
202         protected Point getInitialSize() {
203             final Point size= super.getInitialSize();
204             size.x= convertWidthInCharsToPixels(75);
205             size.y+= convertHeightInCharsToPixels(20);
206             return size;
207         }
208     }
209
210     class RetargetPatchContentProvider extends BaseWorkbenchContentProvider {
211         //Never show closed projects
212
boolean showClosedProjects= false;
213
214         public Object JavaDoc[] getChildren(Object JavaDoc element) {
215             if (element instanceof IWorkspace) {
216                 // check if closed projects should be shown
217
IProject[] allProjects= ((IWorkspace) element).getRoot().getProjects();
218                 if (showClosedProjects)
219                     return allProjects;
220
221                 ArrayList JavaDoc accessibleProjects= new ArrayList JavaDoc();
222                 for (int i= 0; i<allProjects.length; i++) {
223                     if (allProjects[i].isOpen()) {
224                         accessibleProjects.add(allProjects[i]);
225                     }
226                 }
227                 return accessibleProjects.toArray();
228             }
229
230             if (element instanceof IProject) {
231                 return new Object JavaDoc[0];
232             }
233             return super.getChildren(element);
234         }
235     }
236
237     private PatchWizard fPatchWizard;
238
239     private ContainerCheckedTreeViewer fTreeViewer;
240     private Combo fStripPrefixSegments;
241     private CompareViewerSwitchingPane fHunkViewer;
242     private Button fIgnoreWhitespaceButton;
243     private Button fReversePatchButton;
244     private Text fFuzzField;
245     private Button fMatchProject;
246
247     private Object JavaDoc inputElement;
248     private CompareConfiguration fCompareConfiguration;
249
250     protected boolean pageRecalculate= true;
251     protected final static String JavaDoc PREVIEWPATCHPAGE_NAME= "PreviewPatchPage"; //$NON-NLS-1$
252

253     /* package */ PreviewPatchPage(PatchWizard pw) {
254         super(PREVIEWPATCHPAGE_NAME, PatchMessages.PreviewPatchPage_title, null);
255
256         setMessage(PatchMessages.PreviewPatchPage_message);
257
258         fPatchWizard= pw;
259         //setPageComplete(false);
260

261         fCompareConfiguration= new CompareConfiguration();
262
263         fCompareConfiguration.setLeftEditable(false);
264         fCompareConfiguration.setLeftLabel(PatchMessages.PreviewPatchPage_Left_title);
265
266         fCompareConfiguration.setRightEditable(false);
267         fCompareConfiguration.setRightLabel(PatchMessages.PreviewPatchPage_Right_title);
268     }
269
270     /* (non-Javadoc)
271      * Method declared in WizardPage
272      */

273     public void setVisible(boolean visible) {
274         if (visible) {
275             buildTree();
276             updateTree();
277         }
278         super.setVisible(visible);
279     }
280
281     public void createControl(Composite parent) {
282
283         Composite composite= new Composite(parent, SWT.NULL);
284         composite.setLayout(new GridLayout());
285         composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL|GridData.HORIZONTAL_ALIGN_FILL));
286
287         PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ICompareContextIds.PATCH_PREVIEW_WIZARD_PAGE);
288         
289         setControl(composite);
290
291         initializeDialogUnits(parent);
292         
293         buildPatchOptionsGroup(composite);
294
295         Splitter splitter= new Splitter(composite, SWT.VERTICAL);
296         splitter.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL
297                     | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL));
298
299         // top pane showing diffs and hunks in a check box tree
300
createTreeViewer(splitter);
301
302         // bottom pane showing hunks in compare viewer
303
fHunkViewer= new CompareViewerSwitchingPane(splitter, SWT.BORDER|SWT.FLAT) {
304             protected Viewer getViewer(Viewer oldViewer, Object JavaDoc input) {
305                 return CompareUI.findContentViewer(oldViewer, (ICompareInput) input, this, fCompareConfiguration);
306             }
307         };
308         fHunkViewer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
309
310         //create Match Project button
311
fMatchProject= new Button(composite, SWT.PUSH);
312         fMatchProject.setLayoutData(new GridData(SWT.END, GridData.BEGINNING, false, false));
313
314         fMatchProject.setText(PatchMessages.PreviewPatchPage_MatchProjects);
315         fMatchProject.setEnabled(false);
316         fMatchProject.setVisible(false);
317         fMatchProject.addSelectionListener(new SelectionAdapter() {
318             public void widgetSelected(SelectionEvent e) {
319                 final RetargetPatchDialog dialog= new RetargetPatchDialog(getShell(), fTreeViewer.getSelection());
320                 dialog.open();
321                 updateTree();
322             }
323         });
324
325         // creating tree's content
326
buildTree();
327         Dialog.applyDialogFont(composite);
328     }
329
330     private void createTreeViewer(Splitter splitter) {
331         fTreeViewer= new ContainerCheckedTreeViewer(splitter, SWT.BORDER);
332         fTreeViewer.setContentProvider(new BaseWorkbenchContentProvider());
333         fTreeViewer.setLabelProvider(new DecoratingLabelProvider(new WorkbenchLabelProvider(), new PreviewPatchLabelDecorator()));
334         fTreeViewer.setSorter(new WorkbenchViewerSorter());
335         fTreeViewer.addCheckStateListener(new ICheckStateListener() {
336             public void checkStateChanged(CheckStateChangedEvent event) {
337                 fTreeViewer.setSubtreeChecked(event.getElement(),event.getChecked());
338                 updateEnablements();
339             }
340         });
341
342         fTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
343             public void doubleClick(DoubleClickEvent event) {
344                 ISelection selection= event.getSelection();
345                 if (selection instanceof TreeSelection) {
346                     TreeSelection treeSel= (TreeSelection) selection;
347                     Object JavaDoc res= treeSel.getFirstElement();
348                     if (res != null) {
349                         if (res instanceof DiffProject || res instanceof Diff) {
350                             if (fTreeViewer.getExpandedState(res))
351                                 fTreeViewer.collapseToLevel(res, 1);
352                             else
353                                 fTreeViewer.expandToLevel(res, 1);
354                         }
355                     }
356                 }
357             }
358         });
359         
360         
361         fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
362
363             public void selectionChanged(SelectionChangedEvent event) {
364                 IStructuredSelection sel= (IStructuredSelection) event.getSelection();
365                 Object JavaDoc obj= sel.getFirstElement();
366
367                 if (obj instanceof Hunk) {
368                     PreviewPatchPage.this.fHunkViewer.setInput(createInput((Hunk) obj));
369                 } else
370                     PreviewPatchPage.this.fHunkViewer.setInput(null);
371                 
372                 fMatchProject.setEnabled(false);
373                 //See if we need to enable match project button
374
if (fPatchWizard.getPatcher().isWorkspacePatch()&&obj instanceof DiffProject) {
375                     fMatchProject.setEnabled(true);
376                 }
377
378             }
379
380         });
381         
382         fTreeViewer.setInput(null);
383     }
384
385     /*
386      * Create the group for setting various patch options
387      */

388     private void buildPatchOptionsGroup(Composite parent) {
389         
390         GridLayout gl;
391         GridData gd;
392         Label l;
393
394         final WorkspacePatcher patcher= fPatchWizard.getPatcher();
395
396         Group group= new Group(parent, SWT.NONE);
397         group.setText(PatchMessages.PreviewPatchPage_PatchOptions_title);
398         gl= new GridLayout(); gl.numColumns= 4;
399         group.setLayout(gl);
400         group.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL|GridData.GRAB_HORIZONTAL));
401
402         // 1st row
403

404         Composite pair= new Composite(group, SWT.NONE);
405         gl= new GridLayout(); gl.numColumns= 2; gl.marginHeight= gl.marginWidth= 0;
406         pair.setLayout(gl);
407         gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
408         pair.setLayoutData(gd);
409
410         l= new Label(pair, SWT.NONE);
411         l.setText(PatchMessages.PreviewPatchPage_IgnoreSegments_text);
412         gd= new GridData(GridData.VERTICAL_ALIGN_CENTER|GridData.HORIZONTAL_ALIGN_BEGINNING|GridData.GRAB_HORIZONTAL);
413         l.setLayoutData(gd);
414
415         fStripPrefixSegments= new Combo(pair, SWT.DROP_DOWN|SWT.READ_ONLY|SWT.SIMPLE);
416         int prefixCnt= patcher.getStripPrefixSegments();
417         String JavaDoc prefix= Integer.toString(prefixCnt);
418         fStripPrefixSegments.add(prefix);
419         fStripPrefixSegments.setText(prefix);
420         gd= new GridData(GridData.VERTICAL_ALIGN_CENTER|GridData.HORIZONTAL_ALIGN_END);
421         fStripPrefixSegments.setLayoutData(gd);
422
423         addSpacer(group);
424
425         fReversePatchButton= new Button(group, SWT.CHECK);
426         fReversePatchButton.setText(PatchMessages.PreviewPatchPage_ReversePatch_text);
427
428         addSpacer(group);
429
430         // 2nd row
431
pair= new Composite(group, SWT.NONE);
432         gl= new GridLayout(); gl.numColumns= 3; gl.marginHeight= gl.marginWidth= 0;
433         pair.setLayout(gl);
434         gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
435         pair.setLayoutData(gd);
436
437         l= new Label(pair, SWT.NONE);
438         l.setText(PatchMessages.PreviewPatchPage_FuzzFactor_text);
439         l.setToolTipText(PatchMessages.PreviewPatchPage_FuzzFactor_tooltip);
440         gd= new GridData(GridData.VERTICAL_ALIGN_CENTER|GridData.HORIZONTAL_ALIGN_BEGINNING|GridData.GRAB_HORIZONTAL);
441         l.setLayoutData(gd);
442
443         fFuzzField= new Text(pair, SWT.BORDER);
444         fFuzzField.setText("2"); //$NON-NLS-1$
445
gd= new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_END); gd.widthHint= 30;
446         fFuzzField.setLayoutData(gd);
447
448         Button b= new Button(pair, SWT.PUSH);
449         b.setText(PatchMessages.PreviewPatchPage_GuessFuzz_text);
450             b.addSelectionListener(
451                 new SelectionAdapter() {
452             public void widgetSelected(SelectionEvent e) {
453                 int fuzz= guessFuzzFactor(patcher);
454                 if (fuzz>=0)
455                     fFuzzField.setText(Integer.toString(fuzz));
456             }
457                 }
458             );
459         gd= new GridData(GridData.VERTICAL_ALIGN_CENTER);
460         int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
461         Point minSize = b.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
462         gd.widthHint = Math.max(widthHint, minSize.x);
463         b.setLayoutData(gd);
464
465         addSpacer(group);
466
467         fIgnoreWhitespaceButton= new Button(group, SWT.CHECK);
468         fIgnoreWhitespaceButton.setText(PatchMessages.PreviewPatchPage_IgnoreWhitespace_text);
469
470         addSpacer(group);
471
472         // register listeners
473

474         if (fStripPrefixSegments!=null)
475             fStripPrefixSegments.addSelectionListener(
476                 new SelectionAdapter() {
477                 public void widgetSelected(SelectionEvent e) {
478                     if (patcher.setStripPrefixSegments(getStripPrefixSegments()))
479                         updateTree();
480                 }
481                 }
482             );
483         fReversePatchButton.addSelectionListener(
484             new SelectionAdapter() {
485             public void widgetSelected(SelectionEvent e) {
486                 if (patcher.setReversed(fReversePatchButton.getSelection()))
487                     updateTree();
488             }
489             }
490         );
491         fIgnoreWhitespaceButton.addSelectionListener(
492             new SelectionAdapter() {
493             public void widgetSelected(SelectionEvent e) {
494                 if (patcher.setIgnoreWhitespace(fIgnoreWhitespaceButton.getSelection()))
495                     updateTree();
496             }
497             }
498         );
499
500         fFuzzField.addModifyListener(
501             new ModifyListener() {
502             public void modifyText(ModifyEvent e) {
503                 if (patcher.setFuzz(getFuzzFactor()))
504                     updateTree();
505             }
506         });
507     }
508
509     private int guessFuzzFactor(final WorkspacePatcher patcher) {
510         final int strip= getStripPrefixSegments();
511         final int[] result= new int[1];
512         try {
513             PlatformUI.getWorkbench().getProgressService().run(true, true,
514             //TimeoutContext.run(true, GUESS_TIMEOUT, getControl().getShell(),
515
new IRunnableWithProgress() {
516                         public void run(IProgressMonitor monitor) {
517                             result[0]= guess(patcher, monitor, strip);
518                         }
519                 }
520             );
521             return result[0];
522         } catch (InvocationTargetException JavaDoc ex) {
523             // NeedWork
524
} catch (InterruptedException JavaDoc ex) {
525             // NeedWork
526
}
527         return -1;
528     }
529
530     private int guess(WorkspacePatcher patcher, IProgressMonitor pm, int strip) {
531
532         Diff[] diffs= patcher.getDiffs();
533         if (diffs==null||diffs.length<=0)
534             return -1;
535
536         // now collect files and determine "work"
537
IFile[] files= new IFile[diffs.length];
538         int work= 0;
539         for (int i= 0; i<diffs.length; i++) {
540             Diff diff= diffs[i];
541             if (diff==null)
542                 continue;
543             if (diff.getType()!=Differencer.ADDITION) {
544                 IPath p= diff.fOldPath;
545                 if (strip>0&&strip<p.segmentCount())
546                     p= p.removeFirstSegments(strip);
547                 IFile file= existsInSelection(p);
548                 if (file!=null) {
549                     files[i]= file;
550                     work+= diff.fHunks.size();
551                 }
552             }
553         }
554
555         // do the "work"
556
int[] fuzzRef= new int[1];
557         String JavaDoc format= PatchMessages.PreviewPatchPage_GuessFuzzProgress_format;
558         pm.beginTask(PatchMessages.PreviewPatchPage_GuessFuzzProgress_text, work);
559         try {
560             int fuzz= 0;
561             for (int i= 0; i<diffs.length; i++) {
562                 Diff d= diffs[i];
563                 IFile file= files[i];
564                 if (d!=null&&file!=null) {
565                     List JavaDoc lines= patcher.load(file, false);
566                     String JavaDoc name= d.getPath().lastSegment();
567                     Iterator JavaDoc iter= d.fHunks.iterator();
568                     int shift= 0;
569                     for (int hcnt= 1; iter.hasNext(); hcnt++) {
570                         pm.subTask(MessageFormat.format(format, new String JavaDoc[] {name, Integer.toString(hcnt)}));
571                         Hunk h= (Hunk) iter.next();
572                         shift= patcher.calculateFuzz(h, lines, shift, pm, fuzzRef);
573                         int f= fuzzRef[0];
574                         if (f==-1) // cancel
575
return -1;
576                         if (f>fuzz)
577                             fuzz= f;
578                         pm.worked(1);
579                     }
580                 }
581             }
582             return fuzz;
583         } finally {
584             pm.done();
585         }
586     }
587
588     ICompareInput createInput(Hunk hunk) {
589
590         String JavaDoc[] lines= hunk.fLines;
591         StringBuffer JavaDoc left= new StringBuffer JavaDoc();
592         StringBuffer JavaDoc right= new StringBuffer JavaDoc();
593
594         for (int i= 0; i<lines.length; i++) {
595             String JavaDoc line= lines[i];
596             String JavaDoc rest= line.substring(1);
597             switch (line.charAt(0)) {
598                 case ' ' :
599                     left.append(rest);
600                     right.append(rest);
601                     break;
602                 case '-' :
603                     left.append(rest);
604                     break;
605                 case '+' :
606                     right.append(rest);
607                     break;
608             }
609         }
610
611         Diff diff= hunk.fParent;
612         IPath path= diff.getPath();
613         String JavaDoc type= path.getFileExtension();
614
615         return new DiffNode(new HunkInput(type, left.toString()), new HunkInput(type, right.toString()));
616     }
617
618     private IFile existsInSelection(IPath path) {
619         return fPatchWizard.getPatcher().existsInTarget(path);
620     }
621
622     private void buildTree() {
623
624         inputElement= fPatchWizard.getPatcher();
625
626         //Update prefix count - go through all of the diffs and find the smallest
627
//path segment contained in all diffs.
628
int length= 99;
629         if (fStripPrefixSegments!=null&&pageRecalculate) {
630             length= fPatchWizard.getPatcher().calculatePrefixSegmentCount();
631             if (length!=99) {
632                 for (int k= 1; k<length; k++)
633                     fStripPrefixSegments.add(Integer.toString(k));
634                 pageRecalculate= false;
635             }
636         }
637
638         fTreeViewer.setInput(inputElement);
639     }
640
641     /**
642      * Updates label and checked state of tree items.
643      */

644     private void updateTree() {
645
646         if (fTreeViewer==null)
647             return;
648
649         int strip= getStripPrefixSegments();
650         //Get the elements from the content provider
651
BaseWorkbenchContentProvider contentProvider= (BaseWorkbenchContentProvider) fTreeViewer.getContentProvider();
652         Object JavaDoc[] projects= contentProvider.getElements(inputElement);
653         ArrayList JavaDoc hunksToCheck= new ArrayList JavaDoc();
654         //Iterate through projects and call reset on each project
655
for (int j= 0; j<projects.length; j++) {
656             if (projects[j] instanceof DiffProject) {
657                 DiffProject project= (DiffProject) projects[j];
658                 hunksToCheck.addAll(project.reset(fPatchWizard.getPatcher(), strip, getFuzzFactor()));
659                 for (Iterator JavaDoc iter= project.fDiffs.iterator(); iter.hasNext();) {
660                     Diff diff= (Diff) iter.next();
661                     fTreeViewer.update(diff, null);
662                 }
663             } else {
664                 if (projects[j] instanceof Diff) {
665                     Diff diff= (Diff) projects[j];
666                     hunksToCheck.addAll(diff.reset(fPatchWizard.getPatcher(), strip, getFuzzFactor()));
667                     fTreeViewer.update(diff, null);
668                 }
669             }
670         }
671         fTreeViewer.refresh();
672         fTreeViewer.setCheckedElements(hunksToCheck.toArray());
673         updateEnablements();
674     }
675
676     private void addSpacer(Composite parent) {
677         Label label= new Label(parent, SWT.NONE);
678         GridData gd= new GridData(GridData.FILL_HORIZONTAL);
679         gd.widthHint= 20;
680         label.setLayoutData(gd);
681     }
682
683     private int getStripPrefixSegments() {
684         int stripPrefixSegments= 0;
685         if (fStripPrefixSegments!=null) {
686             String JavaDoc s= fStripPrefixSegments.getText();
687             try {
688                 stripPrefixSegments= Integer.parseInt(s);
689             } catch (NumberFormatException JavaDoc ex) {
690                 // silently ignored
691
}
692         }
693         return stripPrefixSegments;
694     }
695
696     private int getFuzzFactor() {
697         int fuzzFactor= 0;
698         if (fFuzzField!=null) {
699             String JavaDoc s= fFuzzField.getText();
700             try {
701                 fuzzFactor= Integer.parseInt(s);
702             } catch (NumberFormatException JavaDoc ex) {
703                 // silently ignored
704
}
705         }
706         return fuzzFactor;
707     }
708
709     /**
710      * Makes sure that at least one hunk is checked off in the tree before
711      * allowing the patch to be applied.
712      */

713     /* private */void updateEnablements() {
714         boolean atLeastOneIsEnabled= false;
715         if (fTreeViewer!=null) {
716             BaseWorkbenchContentProvider contentProvider= (BaseWorkbenchContentProvider) fTreeViewer.getContentProvider();
717             Object JavaDoc[] projects= contentProvider.getElements(inputElement);
718             //Iterate through projects
719
for (int j= 0; j<projects.length; j++) {
720                 if (projects[j] instanceof DiffProject) {
721                     DiffProject project= (DiffProject) projects[j];
722                     //Iterate through project diffs
723
Object JavaDoc[] diffs= project.getChildren(project);
724                     for (int i= 0; i<diffs.length; i++) {
725                         Diff diff= (Diff) diffs[i];
726                         atLeastOneIsEnabled= updateEnablement(atLeastOneIsEnabled, diff);
727                     }
728                 } else if (projects[j] instanceof Diff) {
729                     Diff diff= (Diff) projects[j];
730                     atLeastOneIsEnabled= updateEnablement(atLeastOneIsEnabled, diff);
731                 }
732             }
733         }
734
735         //Check to see if Match Project button should be visible
736
fMatchProject.setVisible(fPatchWizard.getPatcher().isWorkspacePatch());
737
738         setPageComplete(atLeastOneIsEnabled);
739     }
740
741     private boolean updateEnablement(boolean atLeastOneIsEnabled, Diff diff) {
742         boolean checked= fTreeViewer.getChecked(diff);
743         diff.setEnabled(checked);
744         if (checked) {
745             Object JavaDoc[] hunkItems= diff.getChildren(diff);
746             for (int h= 0; h<hunkItems.length; h++) {
747                 Hunk hunk= (Hunk) hunkItems[h];
748                 checked= fTreeViewer.getChecked(hunk);
749                 hunk.setEnabled(checked);
750                 if (checked) {
751                     //For workspace patch: before setting enabled flag, make sure that the project
752
//that contains this hunk actually exists in the workspace. This is to guard against the
753
//case of having a new file in a patch that is being applied to a project that
754
//doesn't currently exist.
755
boolean projectExists= true;
756                     DiffProject project= (DiffProject)diff.getParent(null);
757                     if (project!= null){
758                         projectExists=project.getProject().exists();
759                     }
760                     if (projectExists)
761                         atLeastOneIsEnabled= true;
762                 }
763
764             }
765         }
766     
767         return atLeastOneIsEnabled;
768     }
769
770 }
771
Popular Tags