diff options
543 files changed, 24185 insertions, 24185 deletions
diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FileDiffResult.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FileDiffResult.java index 9b7b584dc..ab64d83a3 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FileDiffResult.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FileDiffResult.java @@ -68,7 +68,7 @@ public class FileDiffResult implements IFilePatchResult { * @param content the contents being patched or <code>null</code> for an addition * @param monitor a progress monitor or <code>null</code> if no progress monitoring is desired */ - public void refresh(ReaderCreator content, IProgressMonitor monitor) { + public void refresh(ReaderCreator content, IProgressMonitor monitor) { this.fMatches= false; this.fDiffProblem= false; boolean create= false; diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FilePatch2.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FilePatch2.java index f66faad94..4160b131f 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FilePatch2.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/FilePatch2.java @@ -58,17 +58,17 @@ public class FilePatch2 implements IFilePatch2 { * @param newPath the path of the after state * @param newDate the timestamp of the after state */ - public FilePatch2(IPath oldPath, long oldDate, IPath newPath, long newDate) { + public FilePatch2(IPath oldPath, long oldDate, IPath newPath, long newDate) { this.fOldPath= oldPath; this.oldDate = oldDate; this.fNewPath= newPath; this.newDate = newDate; } - /** - * Return the parent project or <code>null</code> if there isn't one. - * @return the parent project or <code>null</code> - */ + /** + * Return the parent project or <code>null</code> if there isn't one. + * @return the parent project or <code>null</code> + */ public DiffProject getProject() { return this.fProject; } diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/Hunk.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/Hunk.java index 938d99774..2256d28b7 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/Hunk.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/Hunk.java @@ -63,9 +63,9 @@ public class Hunk implements IHunk { public Hunk(FilePatch2 parent, int hunkType, int oldStart, int oldLength, int newStart, int newLength, String[] lines) { this.fParent = parent; - if (this.fParent != null) { - this.fParent.add(this); - } + if (this.fParent != null) { + this.fParent.add(this); + } this.hunkType = hunkType; this.fOldLength = oldLength; this.fOldStart = oldStart; @@ -74,9 +74,9 @@ public class Hunk implements IHunk { this.fLines = lines; } - public Hunk(FilePatch2 parent, Hunk toCopy) { - this(parent, toCopy.hunkType, toCopy.fOldStart, toCopy.fOldLength, toCopy.fNewStart, toCopy.fNewLength, toCopy.fLines); - } + public Hunk(FilePatch2 parent, Hunk toCopy) { + this(parent, toCopy.hunkType, toCopy.fOldStart, toCopy.fOldLength, toCopy.fNewStart, toCopy.fNewLength, toCopy.fLines); + } /* * Returns the contents of this hunk. diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/LineReader.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/LineReader.java index 7ae7880ff..f7732e063 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/LineReader.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/LineReader.java @@ -121,15 +121,15 @@ public class LineReader { this.fIgnoreSingleCR= true; } - /** - * Reads a line of text. A line is considered to be terminated by any one - * of a line feed ('\n'), a carriage return ('\r'), or a carriage return - * followed immediately by a line-feed. - * @return A string containing the contents of the line including - * the line-termination characters, or <code>null</code> if the end of the - * stream has been reached - * @exception IOException If an I/O error occurs - */ + /** + * Reads a line of text. A line is considered to be terminated by any one + * of a line feed ('\n'), a carriage return ('\r'), or a carriage return + * followed immediately by a line-feed. + * @return A string containing the contents of the line including + * the line-termination characters, or <code>null</code> if the end of the + * stream has been reached + * @exception IOException If an I/O error occurs + */ String readLine() throws IOException { try { while (!this.fSawEOF) { diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/PatchReader.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/PatchReader.java index 058aedbc7..7bf46f7c5 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/PatchReader.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/internal/core/patch/PatchReader.java @@ -671,7 +671,7 @@ public class PatchReader { while (st.hasMoreElements()) { String token= st.nextToken().trim(); if (token.length() > 0) - l.add(token); + l.add(token); } return l.toArray(new String[l.size()]); } diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/DifferencesIterator.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/DifferencesIterator.java index f7f919227..a7dd086bc 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/DifferencesIterator.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/DifferencesIterator.java @@ -42,8 +42,8 @@ import java.util.List; } /* - * Returns the number of RangeDifferences - */ + * Returns the number of RangeDifferences + */ int getCount() { return this.fRange.size(); } @@ -72,8 +72,8 @@ import java.util.List; } /* - * Removes all <code>RangeDifference</code>s - */ + * Removes all <code>RangeDifference</code>s + */ void removeAll() { this.fRange.clear(); } diff --git a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/RangeComparatorLCS.java b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/RangeComparatorLCS.java index ba0f856fb..7949b3a03 100644 --- a/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/RangeComparatorLCS.java +++ b/bundles/org.eclipse.compare.core/src/org/eclipse/compare/rangedifferencer/RangeComparatorLCS.java @@ -151,7 +151,7 @@ import org.eclipse.core.runtime.*; * @param length The number of non-empty (i.e non-zero) entries in LCS * @param comparator The comparator used to generate the LCS */ - private void compactAndShiftLCS(int[] lcsSide, int length, + private void compactAndShiftLCS(int[] lcsSide, int length, IRangeComparator comparator) { // If the LCS is empty, just return if (length == 0) diff --git a/bundles/org.eclipse.compare.win32/META-INF/MANIFEST.MF b/bundles/org.eclipse.compare.win32/META-INF/MANIFEST.MF index 124efe42c..6321d2dd5 100644 --- a/bundles/org.eclipse.compare.win32/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.compare.win32/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.compare.win32;singleton:=true -Bundle-Version: 1.2.400.qualifier +Bundle-Version: 1.2.500.qualifier Bundle-Vendor: %providerName Bundle-RequiredExecutionEnvironment: JavaSE-1.8 Eclipse-PlatformFilter: (osgi.os=win32) diff --git a/bundles/org.eclipse.compare.win32/pom.xml b/bundles/org.eclipse.compare.win32/pom.xml index c89baa794..859508af4 100644 --- a/bundles/org.eclipse.compare.win32/pom.xml +++ b/bundles/org.eclipse.compare.win32/pom.xml @@ -19,7 +19,7 @@ </parent> <groupId>org.eclipse.compare</groupId> <artifactId>org.eclipse.compare.win32</artifactId> - <version>1.2.400-SNAPSHOT</version> + <version>1.2.500-SNAPSHOT</version> <packaging>eclipse-plugin</packaging> <build> diff --git a/bundles/org.eclipse.compare.win32/src/org/eclipse/compare/internal/win32/WordComparison.java b/bundles/org.eclipse.compare.win32/src/org/eclipse/compare/internal/win32/WordComparison.java index bceda549b..a6cef6046 100644 --- a/bundles/org.eclipse.compare.win32/src/org/eclipse/compare/internal/win32/WordComparison.java +++ b/bundles/org.eclipse.compare.win32/src/org/eclipse/compare/internal/win32/WordComparison.java @@ -410,56 +410,56 @@ public class WordComparison { || (!inplace && getDocumentDirty(document)); } - /** - * Initialize the workbench menus for proper menu merging - * Copied from org.eclipse.ui.internal.editorsupport.win32OleEditor - */ - protected void initializeWorkbenchMenus(IWorkbenchWindow window) { - //If there was an OLE Error or nothing has been created yet - if (frame == null || frame.isDisposed()) - return; - // Get the browser menu bar. If one does not exist then - // create it. - Shell shell = frame.getShell(); - Menu menuBar = shell.getMenuBar(); - if (menuBar == null) { - menuBar = new Menu(shell, SWT.BAR); - shell.setMenuBar(menuBar); - } + /** + * Initialize the workbench menus for proper menu merging + * Copied from org.eclipse.ui.internal.editorsupport.win32OleEditor + */ + protected void initializeWorkbenchMenus(IWorkbenchWindow window) { + //If there was an OLE Error or nothing has been created yet + if (frame == null || frame.isDisposed()) + return; + // Get the browser menu bar. If one does not exist then + // create it. + Shell shell = frame.getShell(); + Menu menuBar = shell.getMenuBar(); + if (menuBar == null) { + menuBar = new Menu(shell, SWT.BAR); + shell.setMenuBar(menuBar); + } - // Swap the file and window menus. - MenuItem[] windowMenu = new MenuItem[1]; - MenuItem[] fileMenu = new MenuItem[1]; - Vector containerItems = new Vector(); + // Swap the file and window menus. + MenuItem[] windowMenu = new MenuItem[1]; + MenuItem[] fileMenu = new MenuItem[1]; + Vector containerItems = new Vector(); - for (int i = 0; i < menuBar.getItemCount(); i++) { - MenuItem item = menuBar.getItem(i); - String id = ""; //$NON-NLS-1$ - if (item.getData() instanceof IMenuManager) - id = ((IMenuManager) item.getData()).getId(); - if (id.equals(IWorkbenchActionConstants.M_FILE)) - fileMenu[0] = item; - else if (id.equals(IWorkbenchActionConstants.M_WINDOW)) - windowMenu[0] = item; - else { - if (window.isApplicationMenu(id)) { - containerItems.addElement(item); - } - } - } - MenuItem[] containerMenu = new MenuItem[containerItems.size()]; - containerItems.copyInto(containerMenu); - frame.setFileMenus(fileMenu); - frame.setContainerMenus(containerMenu); - frame.setWindowMenus(windowMenu); - } + for (int i = 0; i < menuBar.getItemCount(); i++) { + MenuItem item = menuBar.getItem(i); + String id = ""; //$NON-NLS-1$ + if (item.getData() instanceof IMenuManager) + id = ((IMenuManager) item.getData()).getId(); + if (id.equals(IWorkbenchActionConstants.M_FILE)) + fileMenu[0] = item; + else if (id.equals(IWorkbenchActionConstants.M_WINDOW)) + windowMenu[0] = item; + else { + if (window.isApplicationMenu(id)) { + containerItems.addElement(item); + } + } + } + MenuItem[] containerMenu = new MenuItem[containerItems.size()]; + containerItems.copyInto(containerMenu); + frame.setFileMenus(fileMenu); + frame.setContainerMenus(containerMenu); + frame.setWindowMenus(windowMenu); + } - /** - * Return whether the comparison document is being shown in-place or in - * a separate window. - * @return whether the comparison document is being shown in-place or in - * a separate window - */ + /** + * Return whether the comparison document is being shown in-place or in + * a separate window. + * @return whether the comparison document is being shown in-place or in + * a separate window + */ public boolean isInplace() { return inplace; } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareEditorInput.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareEditorInput.java index ae4cb4e6e..d8c155ac8 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareEditorInput.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareEditorInput.java @@ -376,14 +376,14 @@ public abstract class CompareEditorInput extends PlatformObject implements IEdit /* * FIXME! - */ + */ protected void setMessage(String message) { fMessage= message; } /* * FIXME! - */ + */ public String getMessage() { return fMessage; } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareUI.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareUI.java index 6fa811254..18cdf0fc0 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareUI.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareUI.java @@ -94,10 +94,10 @@ public final class CompareUI { /** * Name of the title property of a compare viewer. - * If a property with this name is set - * on the top level SWT control of a viewer, it is used as a title in the pane's - * title bar. - */ + * If a property with this name is set + * on the top level SWT control of a viewer, it is used as a title in the pane's + * title bar. + */ public static final String COMPARE_VIEWER_TITLE= "org.eclipse.compare.CompareUI.CompareViewerTitle"; //$NON-NLS-1$ private CompareUI() { @@ -283,7 +283,7 @@ public final class CompareUI { */ @Deprecated public static IStreamMerger createStreamMerger(IContentType type) { - return CompareUIPlugin.getDefault().createStreamMerger(type); + return CompareUIPlugin.getDefault().createStreamMerger(type); } /** @@ -298,7 +298,7 @@ public final class CompareUI { */ @Deprecated public static IStreamMerger createStreamMerger(String type) { - return CompareUIPlugin.getDefault().createStreamMerger(type); + return CompareUIPlugin.getDefault().createStreamMerger(type); } /** diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareViewerSwitchingPane.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareViewerSwitchingPane.java index 6f2ddc727..db2e4fa38 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareViewerSwitchingPane.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/CompareViewerSwitchingPane.java @@ -204,7 +204,7 @@ public abstract class CompareViewerSwitchingPane extends CompareViewerPane { @Override public void setSelection(ISelection s) { if (fViewer != null) - fViewer.setSelection(s); + fViewer.setSelection(s); } private boolean hasFocus2() { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/EditionSelectionDialog.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/EditionSelectionDialog.java index 78ff969d4..3d856f9f0 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/EditionSelectionDialog.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/EditionSelectionDialog.java @@ -603,20 +603,20 @@ public class EditionSelectionDialog extends ResizableDialog { return result.toArray(new ITypedElement[result.size()]); } - /** - * Returns a label for identifying the target side of a compare viewer. - * This implementation extracts the value for the key "targetLabel" from the resource bundle - * and passes it as the format argument to <code>MessageFormat.format</code>. - * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) - * is the name of the given input element. + /** + * Returns a label for identifying the target side of a compare viewer. + * This implementation extracts the value for the key "targetLabel" from the resource bundle + * and passes it as the format argument to <code>MessageFormat.format</code>. + * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) + * is the name of the given input element. * <p> * Subclasses may override to create their own label. * </p> - * - * @param target the target element for which a label must be returned - * @param item if a path has been specified in <code>selectEdition</code> a sub element of the given target; otherwise the same as target - * @return a label the target side of a compare viewer - */ + * + * @param target the target element for which a label must be returned + * @param item if a path has been specified in <code>selectEdition</code> a sub element of the given target; otherwise the same as target + * @return a label the target side of a compare viewer + */ protected String getTargetLabel(ITypedElement target, ITypedElement item) { String format= null; if (target instanceof ResourceNode) @@ -636,7 +636,7 @@ public class EditionSelectionDialog extends ResizableDialog { return string; } - private boolean hasDoubleQuotes(String string) { + private boolean hasDoubleQuotes(String string) { return string.indexOf("''") != -1; //$NON-NLS-1$ } @@ -645,19 +645,19 @@ public class EditionSelectionDialog extends ResizableDialog { } /** - * Returns a label for identifying the edition side of a compare viewer. - * This implementation extracts the value for the key "editionLabel" from the resource bundle - * and passes it as the format argument to <code>MessageFormat.format</code>. - * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) - * is the formatted modification date of the given input element. - * <p> + * Returns a label for identifying the edition side of a compare viewer. + * This implementation extracts the value for the key "editionLabel" from the resource bundle + * and passes it as the format argument to <code>MessageFormat.format</code>. + * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) + * is the formatted modification date of the given input element. + * <p> * Subclasses may override to create their own label. * </p> * * @param selectedEdition the selected edition for which a label must be returned - * @param item if a path has been specified in <code>selectEdition</code> a sub element of the given selectedEdition; otherwise the same as selectedEdition - * @return a label for the edition side of a compare viewer - */ + * @param item if a path has been specified in <code>selectEdition</code> a sub element of the given selectedEdition; otherwise the same as selectedEdition + * @return a label for the edition side of a compare viewer + */ protected String getEditionLabel(ITypedElement selectedEdition, ITypedElement item) { String format= null; if (selectedEdition instanceof ResourceNode) @@ -679,21 +679,21 @@ public class EditionSelectionDialog extends ResizableDialog { return formatString(format, date); } - /** - * Returns a label for identifying a node in the edition tree viewer. - * This implementation extracts the value for the key "workspaceTreeFormat" or - * "treeFormat" (in that order) from the resource bundle - * and passes it as the format argument to <code>MessageFormat.format</code>. - * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) - * is the formatted modification date of the given input element. - * <p> + /** + * Returns a label for identifying a node in the edition tree viewer. + * This implementation extracts the value for the key "workspaceTreeFormat" or + * "treeFormat" (in that order) from the resource bundle + * and passes it as the format argument to <code>MessageFormat.format</code>. + * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) + * is the formatted modification date of the given input element. + * <p> * Subclasses may override to create their own label. * </p> * * @param edition the edition for which a label must be returned - * @param item if a path has been specified in <code>edition</code> a sub element of the given edition; otherwise the same as edition - * @param date this date will be returned as part of the formatted string - * @return a label of a node in the edition tree viewer + * @param item if a path has been specified in <code>edition</code> a sub element of the given edition; otherwise the same as edition + * @param date this date will be returned as part of the formatted string + * @return a label of a node in the edition tree viewer * @since 2.0 */ protected String getShortEditionLabel(ITypedElement edition, ITypedElement item, Date date) { @@ -709,21 +709,21 @@ public class EditionSelectionDialog extends ResizableDialog { return formatString(format, ds); } - /** - * Returns an image for identifying the edition side of a compare viewer. - * This implementation extracts the value for the key "editionLabel" from the resource bundle - * and passes it as the format argument to <code>MessageFormat.format</code>. - * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) - * is the formatted modification date of the given input element. - * <p> + /** + * Returns an image for identifying the edition side of a compare viewer. + * This implementation extracts the value for the key "editionLabel" from the resource bundle + * and passes it as the format argument to <code>MessageFormat.format</code>. + * The single format argument for <code>MessageFormat.format</code> ("{0}" in the format string) + * is the formatted modification date of the given input element. + * <p> * Subclasses may override to create their own label. * </p> * * @param selectedEdition the selected edition for which a label must be returned - * @param item if a path has been specified in <code>selectEdition</code> a sub element of the given selectedEdition; otherwise the same as selectedEdition - * @return a label the edition side of a compare viewer - * @since 2.0 - */ + * @param item if a path has been specified in <code>selectEdition</code> a sub element of the given selectedEdition; otherwise the same as selectedEdition + * @return a label the edition side of a compare viewer + * @since 2.0 + */ protected Image getEditionImage(ITypedElement selectedEdition, ITypedElement item) { if (selectedEdition instanceof ResourceNode) return selectedEdition.getImage(); diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/HistoryItem.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/HistoryItem.java index c799c3bac..57e685093 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/HistoryItem.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/HistoryItem.java @@ -78,19 +78,19 @@ public class HistoryItem implements IEncodedStreamContentAccessor, ITypedElement @Override public String getCharset() throws CoreException { - String charset= fFileState.getCharset(); - if (charset == null) { - IResource resource= getResource(); - if (resource instanceof IEncodedStorage) - charset= ((IEncodedStorage)resource).getCharset(); - } + String charset= fFileState.getCharset(); + if (charset == null) { + IResource resource= getResource(); + if (resource instanceof IEncodedStorage) + charset= ((IEncodedStorage)resource).getCharset(); + } return charset; } @Override public IResource getResource() { - IPath fullPath= fFileState.getFullPath(); - return ResourcesPlugin.getWorkspace().getRoot().findMember(fullPath); + IPath fullPath= fFileState.getFullPath(); + return ResourcesPlugin.getWorkspace().getRoot().findMember(fullPath); } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/IStreamMerger.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/IStreamMerger.java index bc19f6202..6c2c622ea 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/IStreamMerger.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/IStreamMerger.java @@ -32,42 +32,42 @@ import org.eclipse.core.runtime.IStatus; @Deprecated public interface IStreamMerger { - /** - * Indicates the successful completion of the merge operation (value <code>IStatus.OK</code>) - */ - public static final int OK= IStatus.OK; + /** + * Indicates the successful completion of the merge operation (value <code>IStatus.OK</code>) + */ + public static final int OK= IStatus.OK; - /** - * Indicates that a change conflict prevented the merge from successful completion (value <code>1</code>) - */ - public static final int CONFLICT= 1; + /** + * Indicates that a change conflict prevented the merge from successful completion (value <code>1</code>) + */ + public static final int CONFLICT= 1; - /** - * Status code describing an internal error (value <code>2</code>) - */ - public static final int INTERNAL_ERROR= 2; + /** + * Status code describing an internal error (value <code>2</code>) + */ + public static final int INTERNAL_ERROR= 2; - /** - * Performs a merge operation on the given input streams and writes the merge result to the output stream. - * On success a status <code>IStatus.OK</code> is returned, on error a status <code>IStatus.ERROR</code>. - * If the merge operation cannot deal with conflicts, the code of the error status has the value <code>IStreamMerger.CONFLICT</code>. - * For text oriented mergers the encoding for the input and output streams is honored. - * It is the responsibility of callers to close input and output streams. - * - * @param output the byte stream to which the merge result is written; the merger will not close the stream - * @param outputEncoding the encoding to use when writing to the output stream - * @param ancestor the byte stream from which the common ancestor is read - * @param ancestorEncoding the encoding of the ancestor input byte stream - * @param target the byte stream containing the target of the merge - * @param targetEncoding the encoding of the target input byte stream - * @param other the byte stream containing the target of the merge - * @param otherEncoding the encoding of the other input byte stream - * @param monitor reports progress of the merge operation - * @return returns the completion status of the operation - */ + /** + * Performs a merge operation on the given input streams and writes the merge result to the output stream. + * On success a status <code>IStatus.OK</code> is returned, on error a status <code>IStatus.ERROR</code>. + * If the merge operation cannot deal with conflicts, the code of the error status has the value <code>IStreamMerger.CONFLICT</code>. + * For text oriented mergers the encoding for the input and output streams is honored. + * It is the responsibility of callers to close input and output streams. + * + * @param output the byte stream to which the merge result is written; the merger will not close the stream + * @param outputEncoding the encoding to use when writing to the output stream + * @param ancestor the byte stream from which the common ancestor is read + * @param ancestorEncoding the encoding of the ancestor input byte stream + * @param target the byte stream containing the target of the merge + * @param targetEncoding the encoding of the target input byte stream + * @param other the byte stream containing the target of the merge + * @param otherEncoding the encoding of the other input byte stream + * @param monitor reports progress of the merge operation + * @return returns the completion status of the operation + */ IStatus merge(OutputStream output, String outputEncoding, InputStream ancestor, String ancestorEncoding, InputStream target, String targetEncoding, InputStream other, String otherEncoding, - IProgressMonitor monitor); + IProgressMonitor monitor); } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/ResourceNode.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/ResourceNode.java index 018ed5aa1..1b3ff0866 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/ResourceNode.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/ResourceNode.java @@ -121,7 +121,7 @@ public class ResourceNode extends BufferedContent /** * Returns the hash code of the name. - * @return a hash code value for this object. + * @return a hash code value for this object. */ @Override public int hashCode() { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/ZipFileStructureCreator.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/ZipFileStructureCreator.java index 442f31092..826bd9df2 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/ZipFileStructureCreator.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/ZipFileStructureCreator.java @@ -175,16 +175,16 @@ public class ZipFileStructureCreator implements IStructureCreator { } void appendBytes(byte[] buffer, int length) { - if (length > 0) { + if (length > 0) { int oldLen= 0; if (fContents != null) oldLen= fContents.length; byte[] newBuf= new byte[oldLen + length]; if (oldLen > 0) - System.arraycopy(fContents, 0, newBuf, 0, oldLen); - System.arraycopy(buffer, 0, newBuf, oldLen, length); - fContents= newBuf; - } + System.arraycopy(fContents, 0, newBuf, 0, oldLen); + System.arraycopy(buffer, 0, newBuf, oldLen, length); + fContents= newBuf; + } } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/ContentMergeViewer.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/ContentMergeViewer.java index a0b270840..db23be7a3 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/ContentMergeViewer.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/ContentMergeViewer.java @@ -1068,7 +1068,7 @@ public abstract class ContentMergeViewer extends ContentViewer } super.handleDispose(event); - } + } /** * Updates the enabled state of the toolbar items. diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/TextMergeViewer.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/TextMergeViewer.java index 6135f5ba7..7c6f260f8 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/TextMergeViewer.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/contentmergeviewer/TextMergeViewer.java @@ -505,7 +505,7 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { return null; } - private Diff findDiff(Position p, boolean left) { + private Diff findDiff(Position p, boolean left) { for (Iterator<?> iterator = fMerger.rangesIterator(); iterator.hasNext();) { Diff diff = (Diff) iterator.next(); Position diffPos; @@ -1650,11 +1650,11 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { } private ChainedPreferenceStore createChainedPreferenceStore() { - List<IPreferenceStore> stores= new ArrayList<>(2); + List<IPreferenceStore> stores= new ArrayList<>(2); stores.add(getCompareConfiguration().getPreferenceStore()); stores.add(EditorsUI.getPreferenceStore()); return new ChainedPreferenceStore(stores.toArray(new IPreferenceStore[stores.size()])); - } + } /** * Creates a color from the information stored in the given preference store. @@ -2012,7 +2012,7 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { } // don't add anything here, disposing colors should be done last super.handleDispose(event); - } + } private void disconnect(ContributorInfo legInfo) { if (legInfo != null) @@ -2102,16 +2102,16 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { }); fRight.getSourceViewer().addTextPresentationListener(new ChangeHighlighter(fRight)); - IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); - // part is not available for contexts different than editor - if (part != null) { - ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); - if (selectionProvider instanceof CompareEditorSelectionProvider) { - CompareEditorSelectionProvider cesp = (CompareEditorSelectionProvider) selectionProvider; - SourceViewer focusSourceViewer = fFocusPart == null ? null : fFocusPart.getSourceViewer(); - cesp.setViewers(new SourceViewer[] { fLeft.getSourceViewer(), fRight.getSourceViewer(), fAncestor.getSourceViewer() }, focusSourceViewer); - } - } + IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); + // part is not available for contexts different than editor + if (part != null) { + ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); + if (selectionProvider instanceof CompareEditorSelectionProvider) { + CompareEditorSelectionProvider cesp = (CompareEditorSelectionProvider) selectionProvider; + SourceViewer focusSourceViewer = fFocusPart == null ? null : fFocusPart.getSourceViewer(); + cesp.setViewers(new SourceViewer[] { fLeft.getSourceViewer(), fRight.getSourceViewer(), fAncestor.getSourceViewer() }, focusSourceViewer); + } + } hsynchViewport(fAncestor.getSourceViewer(), fLeft.getSourceViewer(), fRight.getSourceViewer()); hsynchViewport(fLeft.getSourceViewer(), fAncestor.getSourceViewer(), fRight.getSourceViewer()); @@ -2197,13 +2197,13 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { sb1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - if (fSynchronizedScrolling) { + if (fSynchronizedScrolling) { int v= sb1.getSelection(); if (st2.isVisible()) st2.setHorizontalPixel(v); if (st3.isVisible()) st3.setHorizontalPixel(v); - } + } } }); } @@ -2331,7 +2331,7 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { for (Iterator<?> iterator = fMerger.rangesIterator(); iterator.hasNext();) { Diff diff = (Diff) iterator.next(); int h= fSynchronizedScrolling ? diff.getMaxDiffHeight() - : diff.getRightHeight(); + : diff.getRightHeight(); if (fMerger.useChange(diff)) { @@ -2928,20 +2928,20 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { if (input instanceof IDiffElement) { IDiffContainer parent= ((IDiffElement) input).getParent(); if (parent instanceof ICompareInput) { - ICompareInput ci= (ICompareInput) parent; - - if (ci.getAncestor() instanceof IDocumentRange - || ci.getLeft() instanceof IDocumentRange - || ci.getRight() instanceof IDocumentRange) { - if (left instanceof IDocumentRange) - leftRange= ((IDocumentRange) left).getRange(); - if (right instanceof IDocumentRange) - rightRange= ((IDocumentRange) right).getRange(); - - ancestor= ci.getAncestor(); - left= getCompareConfiguration().isMirrored() ? ci.getRight() : ci.getLeft(); - right= getCompareConfiguration().isMirrored() ? ci.getLeft() : ci.getRight(); - } + ICompareInput ci= (ICompareInput) parent; + + if (ci.getAncestor() instanceof IDocumentRange + || ci.getLeft() instanceof IDocumentRange + || ci.getRight() instanceof IDocumentRange) { + if (left instanceof IDocumentRange) + leftRange= ((IDocumentRange) left).getRange(); + if (right instanceof IDocumentRange) + rightRange= ((IDocumentRange) right).getRange(); + + ancestor= ci.getAncestor(); + left= getCompareConfiguration().isMirrored() ? ci.getRight() : ci.getLeft(); + right= getCompareConfiguration().isMirrored() ? ci.getLeft() : ci.getRight(); + } } } } @@ -3024,9 +3024,9 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { Diff selectDiff= null; if (FIX_47640) { if (leftRange != null) - selectDiff= fMerger.findDiff(LEFT_CONTRIBUTOR, leftRange); + selectDiff= fMerger.findDiff(LEFT_CONTRIBUTOR, leftRange); else if (rightRange != null) - selectDiff= fMerger.findDiff(RIGHT_CONTRIBUTOR, rightRange); + selectDiff= fMerger.findDiff(RIGHT_CONTRIBUTOR, rightRange); } if (selectDiff != null) setCurrentDiff(selectDiff, true); @@ -3386,9 +3386,9 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { } @Override - protected final void handleResizeLeftRight(int x, int y, int width1, int centerWidth, int width2, int height) { - if (fBirdsEyeCanvas != null) - width2-= BIRDS_EYE_VIEW_WIDTH; + protected final void handleResizeLeftRight(int x, int y, int width1, int centerWidth, int width2, int height) { + if (fBirdsEyeCanvas != null) + width2-= BIRDS_EYE_VIEW_WIDTH; Rectangle trim= fLeft.getSourceViewer().getTextWidget().computeTrim(0, 0, 0, 0); int scrollbarHeight= trim.height + trim.x; @@ -3422,7 +3422,7 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { int scrollbarWidth= 0; if (fSynchronizedScrolling && fScrollCanvas != null) { trim= fLeft.getSourceViewer().getTextWidget().computeTrim(0, 0, 0, 0); - // one pixel was cut off + // one pixel was cut off scrollbarWidth= trim.width + 2*trim.x+1; } int rightTextWidth= width2-scrollbarWidth; @@ -3440,18 +3440,18 @@ public class TextMergeViewer extends ContentMergeViewer implements IAdaptable { fScrollCanvas.setBounds(x, y, scrollbarWidth, height-scrollbarHeight); } - if (fBirdsEyeCanvas != null) { - int verticalScrollbarButtonHeight= scrollbarWidth; + if (fBirdsEyeCanvas != null) { + int verticalScrollbarButtonHeight= scrollbarWidth; int horizontalScrollbarButtonHeight= scrollbarHeight; if (fIsMac) { verticalScrollbarButtonHeight+= 2; horizontalScrollbarButtonHeight= 18; } - if (fSummaryHeader != null) + if (fSummaryHeader != null) fSummaryHeader.setBounds(x+scrollbarWidth, y, BIRDS_EYE_VIEW_WIDTH, verticalScrollbarButtonHeight); - y+= verticalScrollbarButtonHeight; - fBirdsEyeCanvas.setBounds(x+scrollbarWidth, y, BIRDS_EYE_VIEW_WIDTH, height-(2*verticalScrollbarButtonHeight+horizontalScrollbarButtonHeight)); - } + y+= verticalScrollbarButtonHeight; + fBirdsEyeCanvas.setBounds(x+scrollbarWidth, y, BIRDS_EYE_VIEW_WIDTH, height-(2*verticalScrollbarButtonHeight+horizontalScrollbarButtonHeight)); + } // doesn't work since TextEditors don't have their correct size yet. updateVScrollBar(); diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/BufferedResourceNode.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/BufferedResourceNode.java index ca80919c0..815b44c1a 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/BufferedResourceNode.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/BufferedResourceNode.java @@ -45,11 +45,11 @@ public class BufferedResourceNode extends ResourceNode { super(resource); } - /* - * Returns <code>true</code> if buffer contains uncommitted changes. - */ + /* + * Returns <code>true</code> if buffer contains uncommitted changes. + */ public boolean isDirty() { - return fDirty; + return fDirty; } @Override diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java index 07af66f1c..2d5d8c9f8 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditor.java @@ -240,20 +240,20 @@ public class CompareEditor extends EditorPart ErrorDialog.openError(getSite().getShell(), title, msg, s); return; } - doSetInput(input); - // Need to refresh the contributor (see #67888) - refreshActionBarsContributor(); + doSetInput(input); + // Need to refresh the contributor (see #67888) + refreshActionBarsContributor(); } public void refreshActionBarsContributor() { IEditorSite editorSite= getEditorSite(); - if (editorSite != null) { - IEditorActionBarContributor actionBarContributor= editorSite.getActionBarContributor(); - if (actionBarContributor != null) { - actionBarContributor.setActiveEditor(null); - actionBarContributor.setActiveEditor(this); - } - } + if (editorSite != null) { + IEditorActionBarContributor actionBarContributor= editorSite.getActionBarContributor(); + if (actionBarContributor != null) { + actionBarContributor.setActiveEditor(null); + actionBarContributor.setActiveEditor(this); + } + } } private void doSetInput(IEditorInput input) { @@ -299,12 +299,12 @@ public class CompareEditor extends EditorPart initializeInBackground(cei, hadPreviousInput); } - firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); + firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); - // We only need to notify of new Saveables if we are changing inputs - if (hadPreviousInput && hasResult) { - registerSaveable(); - } + // We only need to notify of new Saveables if we are changing inputs + if (hadPreviousInput && hasResult) { + registerSaveable(); + } } private void registerSaveable() { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditorSelectionProvider.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditorSelectionProvider.java index cfa829fbe..ea1004aa7 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditorSelectionProvider.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareEditorSelectionProvider.java @@ -45,17 +45,17 @@ public class CompareEditorSelectionProvider implements IPostSelectionProvider { doSelectionChanged(event); } - @Override + @Override public void focusGained(FocusEvent e) { - // expecting a StyledText widget here - doFocusChanged(e.widget); - } + // expecting a StyledText widget here + doFocusChanged(e.widget); + } - @Override + @Override public void focusLost(FocusEvent e) { - // do not reset due to focus behavior on GTK - //fViewerInFocus= null; - } + // do not reset due to focus behavior on GTK + //fViewerInFocus= null; + } } private class InternalPostSelectionListener implements ISelectionChangedListener { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ComparePreferencePage.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ComparePreferencePage.java index 4d72bd60e..ac215b261 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ComparePreferencePage.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ComparePreferencePage.java @@ -369,8 +369,8 @@ public class ComparePreferencePage extends PreferencePage implements IWorkbenchP CompareMessages.ComparePreferencePage_0, 1, new String[][] { new String[] { CompareMessages.ComparePreferencePage_1, ICompareUIConstants.PREF_VALUE_PROMPT }, - new String[] { CompareMessages.ComparePreferencePage_2, ICompareUIConstants.PREF_VALUE_LOOP }, - new String[] { CompareMessages.ComparePreferencePage_3, ICompareUIConstants.PREF_VALUE_NEXT }, + new String[] { CompareMessages.ComparePreferencePage_2, ICompareUIConstants.PREF_VALUE_LOOP }, + new String[] { CompareMessages.ComparePreferencePage_3, ICompareUIConstants.PREF_VALUE_NEXT }, new String[] { CompareMessages.ComparePreferencePage_4, ICompareUIConstants.PREF_VALUE_DO_NOTHING} }, radioGroup, true); diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareUIPlugin.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareUIPlugin.java index 21f2399fe..45f71276b 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareUIPlugin.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/CompareUIPlugin.java @@ -106,63 +106,63 @@ import org.osgi.framework.ServiceRegistration; */ public final class CompareUIPlugin extends AbstractUIPlugin { - static class CompareRegistry<T> { - private final static String ID_ATTRIBUTE= "id"; //$NON-NLS-1$ - private final static String EXTENSIONS_ATTRIBUTE= "extensions"; //$NON-NLS-1$ - private final static String CONTENT_TYPE_ID_ATTRIBUTE= "contentTypeId"; //$NON-NLS-1$ - - private HashMap<String, T> fIdMap; // maps ids to data - private HashMap<String, List<T>> fExtensionMap; // multimap: maps extensions to list of data - private HashMap<IContentType, List<T>> fContentTypeBindings; // multimap: maps content type bindings to list of data - - - void register(IConfigurationElement element, T data) { - String id= element.getAttribute(ID_ATTRIBUTE); - if (id != null) { - if (fIdMap == null) - fIdMap= new HashMap<>(); - fIdMap.put(id, data); - } - - String types= element.getAttribute(EXTENSIONS_ATTRIBUTE); - if (types != null) { - if (fExtensionMap == null) - fExtensionMap= new HashMap<>(); - StringTokenizer tokenizer= new StringTokenizer(types, ","); //$NON-NLS-1$ - while (tokenizer.hasMoreElements()) { - String extension= tokenizer.nextToken().trim(); - List<T> l = fExtensionMap.get(normalizeCase(extension)); + static class CompareRegistry<T> { + private final static String ID_ATTRIBUTE= "id"; //$NON-NLS-1$ + private final static String EXTENSIONS_ATTRIBUTE= "extensions"; //$NON-NLS-1$ + private final static String CONTENT_TYPE_ID_ATTRIBUTE= "contentTypeId"; //$NON-NLS-1$ + + private HashMap<String, T> fIdMap; // maps ids to data + private HashMap<String, List<T>> fExtensionMap; // multimap: maps extensions to list of data + private HashMap<IContentType, List<T>> fContentTypeBindings; // multimap: maps content type bindings to list of data + + + void register(IConfigurationElement element, T data) { + String id= element.getAttribute(ID_ATTRIBUTE); + if (id != null) { + if (fIdMap == null) + fIdMap= new HashMap<>(); + fIdMap.put(id, data); + } + + String types= element.getAttribute(EXTENSIONS_ATTRIBUTE); + if (types != null) { + if (fExtensionMap == null) + fExtensionMap= new HashMap<>(); + StringTokenizer tokenizer= new StringTokenizer(types, ","); //$NON-NLS-1$ + while (tokenizer.hasMoreElements()) { + String extension= tokenizer.nextToken().trim(); + List<T> l = fExtensionMap.get(normalizeCase(extension)); if (l == null) fExtensionMap.put(normalizeCase(extension), l = new ArrayList<>()); l.add(data); - } - } - } - - void createBinding(IConfigurationElement element, String idAttributeName) { - String type= element.getAttribute(CONTENT_TYPE_ID_ATTRIBUTE); - String id= element.getAttribute(idAttributeName); - if (id == null) - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.targetIdAttributeMissing", idAttributeName)); //$NON-NLS-1$ - if (type != null && id != null && fIdMap != null) { - T o= fIdMap.get(id); - if (o != null) { - IContentType ct= fgContentTypeManager.getContentType(type); - if (ct != null) { - if (fContentTypeBindings == null) - fContentTypeBindings= new HashMap<>(); - List<T> l = fContentTypeBindings.get(ct); - if (l == null) + } + } + } + + void createBinding(IConfigurationElement element, String idAttributeName) { + String type= element.getAttribute(CONTENT_TYPE_ID_ATTRIBUTE); + String id= element.getAttribute(idAttributeName); + if (id == null) + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.targetIdAttributeMissing", idAttributeName)); //$NON-NLS-1$ + if (type != null && id != null && fIdMap != null) { + T o= fIdMap.get(id); + if (o != null) { + IContentType ct= fgContentTypeManager.getContentType(type); + if (ct != null) { + if (fContentTypeBindings == null) + fContentTypeBindings= new HashMap<>(); + List<T> l = fContentTypeBindings.get(ct); + if (l == null) fContentTypeBindings.put(ct, l = new ArrayList<>()); - l.add(o); - } else { - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.contentTypeNotFound", type)); //$NON-NLS-1$ - } - } else { - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.targetNotFound", id)); //$NON-NLS-1$ - } - } - } + l.add(o); + } else { + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.contentTypeNotFound", type)); //$NON-NLS-1$ + } + } else { + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.targetNotFound", id)); //$NON-NLS-1$ + } + } + } T search(IContentType type) { List<T> list = searchAll(type); @@ -190,7 +190,7 @@ public final class CompareUIPlugin extends AbstractUIPlugin { return fExtensionMap.get(normalizeCase(extension)); return null; } - } + } /** Status code describing an internal error */ public static final int INTERNAL_ERROR= 1; @@ -222,7 +222,7 @@ public final class CompareUIPlugin extends AbstractUIPlugin { private static final String CONTENT_TYPE_BINDING= "contentTypeBinding"; //$NON-NLS-1$ - private static final String COMPARE_EDITOR= PLUGIN_ID + ".CompareEditor"; //$NON-NLS-1$ + private static final String COMPARE_EDITOR= PLUGIN_ID + ".CompareEditor"; //$NON-NLS-1$ private static final String STRUCTUREVIEWER_ALIASES_PREFERENCE_NAME= "StructureViewerAliases"; //$NON-NLS-1$ @@ -362,65 +362,65 @@ public final class CompareUIPlugin extends AbstractUIPlugin { // collect all IStreamMergers IConfigurationElement[] elements= registry.getConfigurationElementsFor(PLUGIN_ID, STREAM_MERGER_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (STREAM_MERGER.equals(element.getName())) + IConfigurationElement element= elements[i]; + if (STREAM_MERGER.equals(element.getName())) fStreamMergers.register(element, new StreamMergerDescriptor(element)); } for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (CONTENT_TYPE_BINDING.equals(element.getName())) - fStreamMergers.createBinding(element, STREAM_MERGER_ID_ATTRIBUTE); + IConfigurationElement element= elements[i]; + if (CONTENT_TYPE_BINDING.equals(element.getName())) + fStreamMergers.createBinding(element, STREAM_MERGER_ID_ATTRIBUTE); } // collect all IStructureCreators elements= registry.getConfigurationElementsFor(PLUGIN_ID, STRUCTURE_CREATOR_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - String name= element.getName(); - if (!CONTENT_TYPE_BINDING.equals(name)) { - if (!STRUCTURE_CREATOR.equals(name)) - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, STRUCTURE_CREATOR)); //$NON-NLS-1$ - fStructureCreators.register(element, new StructureCreatorDescriptor(element)); - } + IConfigurationElement element= elements[i]; + String name= element.getName(); + if (!CONTENT_TYPE_BINDING.equals(name)) { + if (!STRUCTURE_CREATOR.equals(name)) + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, STRUCTURE_CREATOR)); //$NON-NLS-1$ + fStructureCreators.register(element, new StructureCreatorDescriptor(element)); + } } for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (CONTENT_TYPE_BINDING.equals(element.getName())) - fStructureCreators.createBinding(element, STRUCTURE_CREATOR_ID_ATTRIBUTE); + IConfigurationElement element= elements[i]; + if (CONTENT_TYPE_BINDING.equals(element.getName())) + fStructureCreators.createBinding(element, STRUCTURE_CREATOR_ID_ATTRIBUTE); } // collect all viewers which define the structure merge viewer extension point elements= registry.getConfigurationElementsFor(PLUGIN_ID, STRUCTURE_MERGE_VIEWER_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - String name= element.getName(); - if (!CONTENT_TYPE_BINDING.equals(name)) { - if (!VIEWER_TAG.equals(name)) - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, VIEWER_TAG)); //$NON-NLS-1$ - fStructureMergeViewers.register(element, new ViewerDescriptor(element)); - } + IConfigurationElement element= elements[i]; + String name= element.getName(); + if (!CONTENT_TYPE_BINDING.equals(name)) { + if (!VIEWER_TAG.equals(name)) + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, VIEWER_TAG)); //$NON-NLS-1$ + fStructureMergeViewers.register(element, new ViewerDescriptor(element)); + } } for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (CONTENT_TYPE_BINDING.equals(element.getName())) - fStructureMergeViewers.createBinding(element, STRUCTURE_MERGE_VIEWER_ID_ATTRIBUTE); + IConfigurationElement element= elements[i]; + if (CONTENT_TYPE_BINDING.equals(element.getName())) + fStructureMergeViewers.createBinding(element, STRUCTURE_MERGE_VIEWER_ID_ATTRIBUTE); } // collect all viewers which define the content merge viewer extension point elements= registry.getConfigurationElementsFor(PLUGIN_ID, CONTENT_MERGE_VIEWER_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - String name= element.getName(); - if (!CONTENT_TYPE_BINDING.equals(name)) { - if (!VIEWER_TAG.equals(name)) - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, VIEWER_TAG)); //$NON-NLS-1$ - fContentMergeViewers.register(element, new ViewerDescriptor(element)); - } + IConfigurationElement element= elements[i]; + String name= element.getName(); + if (!CONTENT_TYPE_BINDING.equals(name)) { + if (!VIEWER_TAG.equals(name)) + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, VIEWER_TAG)); //$NON-NLS-1$ + fContentMergeViewers.register(element, new ViewerDescriptor(element)); + } } for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (CONTENT_TYPE_BINDING.equals(element.getName())) - fContentMergeViewers.createBinding(element, CONTENT_MERGE_VIEWER_ID_ATTRIBUTE); + IConfigurationElement element= elements[i]; + if (CONTENT_TYPE_BINDING.equals(element.getName())) + fContentMergeViewers.createBinding(element, CONTENT_MERGE_VIEWER_ID_ATTRIBUTE); } // collect all extensions that define the compare filter extension point @@ -446,18 +446,18 @@ public final class CompareUIPlugin extends AbstractUIPlugin { // collect all viewers which define the content viewer extension point elements= registry.getConfigurationElementsFor(PLUGIN_ID, CONTENT_VIEWER_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - String name= element.getName(); - if (!CONTENT_TYPE_BINDING.equals(name)) { - if (!VIEWER_TAG.equals(name)) - logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, VIEWER_TAG)); //$NON-NLS-1$ - fContentViewers.register(element, new ViewerDescriptor(element)); - } + IConfigurationElement element= elements[i]; + String name= element.getName(); + if (!CONTENT_TYPE_BINDING.equals(name)) { + if (!VIEWER_TAG.equals(name)) + logErrorMessage(Utilities.getFormattedString("CompareUIPlugin.unexpectedTag", name, VIEWER_TAG)); //$NON-NLS-1$ + fContentViewers.register(element, new ViewerDescriptor(element)); + } } for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (CONTENT_TYPE_BINDING.equals(element.getName())) - fContentViewers.createBinding(element, CONTENT_VIEWER_ID_ATTRIBUTE); + IConfigurationElement element= elements[i]; + if (CONTENT_TYPE_BINDING.equals(element.getName())) + fContentViewers.createBinding(element, CONTENT_VIEWER_ID_ATTRIBUTE); } } @@ -877,7 +877,7 @@ public final class CompareUIPlugin extends AbstractUIPlugin { initializeRegistries(); StructureCreatorDescriptor scc= fStructureCreators.search(ctype); // search for content type if (scc == null && type != null) - scc= getStructureCreator(type); // search for old-style type scheme + scc= getStructureCreator(type); // search for old-style type scheme if (scc != null) { IStructureCreator sc= scc.createStructureCreator(); if (sc != null) { @@ -998,7 +998,7 @@ public final class CompareUIPlugin extends AbstractUIPlugin { if (in instanceof ITypedElement) { ITypedElement tin= (ITypedElement) in; - IContentType ct= getContentType(tin); + IContentType ct= getContentType(tin); if (ct != null) { initializeRegistries(); List<ViewerDescriptor> list = fContentViewers.searchAll(ct); @@ -1105,9 +1105,9 @@ public final class CompareUIPlugin extends AbstractUIPlugin { } private static Viewer getViewer(Object descriptor, Viewer oldViewer, Composite parent, CompareConfiguration cc) { - if (descriptor instanceof IViewerDescriptor) + if (descriptor instanceof IViewerDescriptor) return ((IViewerDescriptor)descriptor).createViewer(oldViewer, parent, cc); - return null; + return null; } private static String[] getTypes(ICompareInput input) { @@ -1119,17 +1119,17 @@ public final class CompareUIPlugin extends AbstractUIPlugin { if (ancestor != null) { String type= ancestor.getType(); if (type != null) - tmp.add(normalizeCase(type)); + tmp.add(normalizeCase(type)); } if (left != null) { String type= left.getType(); if (type != null) - tmp.add(normalizeCase(type)); + tmp.add(normalizeCase(type)); } if (right != null) { String type= right.getType(); if (type != null) - tmp.add(normalizeCase(type)); + tmp.add(normalizeCase(type)); } return tmp.toArray(new String[tmp.size()]); } @@ -1376,7 +1376,7 @@ public final class CompareUIPlugin extends AbstractUIPlugin { //---- filters public boolean filter(String name, boolean isFolder, boolean isArchive) { - if (fFilter == null) { + if (fFilter == null) { fFilter= new CompareResourceFilter(); final IPreferenceStore ps= getPreferenceStore(); fFilter.setFilters(ps.getString(ComparePreferencePage.PATH_FILTER)); @@ -1385,8 +1385,8 @@ public final class CompareUIPlugin extends AbstractUIPlugin { fFilter.setFilters(ps.getString(ComparePreferencePage.PATH_FILTER)); }; ps.addPropertyChangeListener(fPropertyChangeListener); - } - return fFilter.filter(name, isFolder, isArchive); + } + return fFilter.filter(name, isFolder, isArchive); } private void internalOpenDialog(final CompareEditorInput input) { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DiffImageDescriptor.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DiffImageDescriptor.java index fabcc9c81..f4d70a4e9 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DiffImageDescriptor.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DiffImageDescriptor.java @@ -133,7 +133,7 @@ public class DiffImageDescriptor extends CompositeImageDescriptor { /* && i1.palette == i2.palette */ && i1.transparentPixel == i2.transparentPixel && i1.maskPad == i2.maskPad - && i1.alpha == i2.alpha + && i1.alpha == i2.alpha && i1.type == i2.type && i1.x == i2.x && i1.y == i2.y && i1.disposalMethod == i2.disposalMethod && i1.delayTime == i2.delayTime && equals(i1.data,i2.data) && equals(i1.maskData, i2.maskData) diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DocLineComparator.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DocLineComparator.java index fe2ebb007..5eb99ee55 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DocLineComparator.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/DocLineComparator.java @@ -251,7 +251,7 @@ public class DocLineComparator implements ITokenComparator { * Extract a single line from the underlying document. * * @param line the number of the line to extract - * @param whether to include the line separator + * @param whether to include the line separator * @return the contents of the line as a String */ private String extract(int line, boolean includeSeparator) { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java index e004e2493..14b092e4c 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java @@ -307,7 +307,7 @@ public class MergeSourceViewer implements ISelectionChangedListener, MergeSourceViewer.this.getSourceViewer().setSelectedRange(selectionStart, selectionLength); - markInNavigationHistory(); + markInNavigationHistory(); } widget.setRedraw(true); } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ResourceCompareInput.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ResourceCompareInput.java index 49427d2ce..374523a14 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ResourceCompareInput.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/ResourceCompareInput.java @@ -504,44 +504,44 @@ class ResourceCompareInput extends CompareEditorInput { @Override public <T> T getAdapter(Class<T> adapter) { if (IFile.class.equals(adapter)) { - IProgressMonitor pm= new NullProgressMonitor(); + IProgressMonitor pm= new NullProgressMonitor(); // flush changes in any dirty viewer flushViewers(pm); - IFile[] files= getAdapter(IFile[].class); - if (files != null && files.length > 0) - return (T) files[0]; // can only return one: limitation on IDE.saveAllEditors; see #64617 - return null; + IFile[] files= getAdapter(IFile[].class); + if (files != null && files.length > 0) + return (T) files[0]; // can only return one: limitation on IDE.saveAllEditors; see #64617 + return null; } if (IFile[].class.equals(adapter)) { - HashSet<IFile> collector= new HashSet<>(); - collectDirtyResources(fRoot, collector); - return (T) collector.toArray(new IFile[collector.size()]); + HashSet<IFile> collector= new HashSet<>(); + collectDirtyResources(fRoot, collector); + return (T) collector.toArray(new IFile[collector.size()]); } return super.getAdapter(adapter); } private void collectDirtyResources(Object o, Set<IFile> collector) { if (o instanceof DiffNode) { - DiffNode node= (DiffNode) o; + DiffNode node= (DiffNode) o; ITypedElement left= node.getLeft(); if (left instanceof BufferedResourceNode) { - BufferedResourceNode bn= (BufferedResourceNode) left; - if (bn.isDirty()) { - IResource resource= bn.getResource(); - if (resource instanceof IFile) - collector.add((IFile) resource); - } + BufferedResourceNode bn= (BufferedResourceNode) left; + if (bn.isDirty()) { + IResource resource= bn.getResource(); + if (resource instanceof IFile) + collector.add((IFile) resource); + } } ITypedElement right= node.getRight(); if (right instanceof BufferedResourceNode) { - BufferedResourceNode bn= (BufferedResourceNode) right; - if (bn.isDirty()) { - IResource resource= bn.getResource(); - if (resource instanceof IFile) - collector.add((IFile) resource); - } + BufferedResourceNode bn= (BufferedResourceNode) right; + if (bn.isDirty()) { + IResource resource= bn.getResource(); + if (resource instanceof IFile) + collector.add((IFile) resource); + } } IDiffElement[] children= node.getChildren(); @@ -549,7 +549,7 @@ class ResourceCompareInput extends CompareEditorInput { for (int i= 0; i < children.length; i++) { IDiffElement element= children[i]; if (element instanceof DiffNode) - collectDirtyResources(element, collector); + collectDirtyResources(element, collector); } } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/Utilities.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/Utilities.java index 06ab3e188..3ae8cafdc 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/Utilities.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/Utilities.java @@ -429,7 +429,7 @@ public class Utilities { for (Iterator it = validPaths.iterator(); it.hasNext();) { IPath path = (IPath) it.next(); if(path.isPrefixOf(resourceFullPath) || - resourceFullPath.isPrefixOf(path)) { + resourceFullPath.isPrefixOf(path)) { return false; } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/DocumentMerger.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/DocumentMerger.java index 12dc5d0d8..faa11e67a 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/DocumentMerger.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/DocumentMerger.java @@ -976,7 +976,7 @@ public class DocumentMerger { return region; } - public Diff findDiff(Position p, boolean left) { + public Diff findDiff(Position p, boolean left) { for (Iterator<Diff> iterator = fAllDiffs.iterator(); iterator.hasNext();) { Diff diff = iterator.next(); Position diffPos; @@ -1150,7 +1150,7 @@ public class DocumentMerger { while (e.hasNext()) { Diff diff= e.next(); int h= synchronizedScrolling ? diff.getMaxDiffHeight() - : diff.getRightHeight(); + : diff.getRightHeight(); if (useChange(diff.getKind()) && !diff.fIsWhitespace) { yy= (y*size.y)/virtualHeight; @@ -1282,7 +1282,7 @@ public class DocumentMerger { for (Iterator<Diff> iterator = changesIterator(); iterator.hasNext();) { Diff diff = iterator.next(); if (diff.isDeleted() || diff.getKind() == RangeDifference.NOCHANGE) - continue; + continue; if (diff.overlaps(contributor, rangeStart, rangeEnd, getDocument(contributor).getLength())) return diff; } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/LineComparator.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/LineComparator.java index f7f8e399e..0b85c139e 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/LineComparator.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/merge/LineComparator.java @@ -26,39 +26,39 @@ import org.eclipse.compare.rangedifferencer.IRangeComparator; */ class LineComparator implements IRangeComparator { - private String[] fLines; + private String[] fLines; - public LineComparator(InputStream is, String encoding) throws IOException { + public LineComparator(InputStream is, String encoding) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding)); - String line; - ArrayList<String> ar = new ArrayList<>(); - while ((line = br.readLine()) != null) { - ar.add(line); - } - // It is the responsibility of the caller to close the stream - fLines = ar.toArray(new String[ar.size()]); - } + BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding)); + String line; + ArrayList<String> ar = new ArrayList<>(); + while ((line = br.readLine()) != null) { + ar.add(line); + } + // It is the responsibility of the caller to close the stream + fLines = ar.toArray(new String[ar.size()]); + } - String getLine(int ix) { - return fLines[ix]; - } + String getLine(int ix) { + return fLines[ix]; + } - @Override + @Override public int getRangeCount() { - return fLines.length; - } + return fLines.length; + } - @Override + @Override public boolean rangesEqual(int thisIndex, IRangeComparator other, - int otherIndex) { - String s1 = fLines[thisIndex]; - String s2 = ((LineComparator) other).fLines[otherIndex]; - return s1.equals(s2); - } + int otherIndex) { + String s1 = fLines[thisIndex]; + String s2 = ((LineComparator) other).fLines[otherIndex]; + return s1.equals(s2); + } - @Override + @Override public boolean skipRangeComparison(int length, int maxLength, IRangeComparator other) { - return false; - } + return false; + } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/DecoratorOverlayIcon.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/DecoratorOverlayIcon.java index 37c9b6a42..20db8e922 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/DecoratorOverlayIcon.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/DecoratorOverlayIcon.java @@ -27,104 +27,104 @@ import org.eclipse.swt.graphics.Point; * Copied until bug 164394 is resolved. */ class DecoratorOverlayIcon extends CompositeImageDescriptor { - // the base image - private Image base; + // the base image + private Image base; - // the overlay images - private ImageDescriptor[] overlays; + // the overlay images + private ImageDescriptor[] overlays; - // the size - private Point size; + // the size + private Point size; - /** - * OverlayIcon constructor. - * - * @param baseImage the base image - * @param overlaysArray the overlay images - * @param sizeValue the size - */ - public DecoratorOverlayIcon(Image baseImage, - ImageDescriptor[] overlaysArray, Point sizeValue) { - this.base = baseImage; - this.overlays = overlaysArray; - this.size = sizeValue; - } + /** + * OverlayIcon constructor. + * + * @param baseImage the base image + * @param overlaysArray the overlay images + * @param sizeValue the size + */ + public DecoratorOverlayIcon(Image baseImage, + ImageDescriptor[] overlaysArray, Point sizeValue) { + this.base = baseImage; + this.overlays = overlaysArray; + this.size = sizeValue; + } - /** - * Draw the overlays for the receiver. - * @param overlaysArray the overlay images - */ - protected void drawOverlays(ImageDescriptor[] overlaysArray) { + /** + * Draw the overlays for the receiver. + * @param overlaysArray the overlay images + */ + protected void drawOverlays(ImageDescriptor[] overlaysArray) { - for (int i = 0; i < overlays.length; i++) { - ImageDescriptor overlay = overlaysArray[i]; - if (overlay == null) { + for (int i = 0; i < overlays.length; i++) { + ImageDescriptor overlay = overlaysArray[i]; + if (overlay == null) { continue; } - ImageData overlayData = overlay.getImageData(); - //Use the missing descriptor if it is not there. - if (overlayData == null) { + ImageData overlayData = overlay.getImageData(); + //Use the missing descriptor if it is not there. + if (overlayData == null) { overlayData = ImageDescriptor.getMissingImageDescriptor() - .getImageData(); + .getImageData(); } - switch (i) { - case IDecoration.TOP_LEFT: - drawImage(overlayData, 0, 0); - break; - case IDecoration.TOP_RIGHT: - drawImage(overlayData, size.x - overlayData.width, 0); - break; - case IDecoration.BOTTOM_LEFT: - drawImage(overlayData, 0, size.y - overlayData.height); - break; - case IDecoration.BOTTOM_RIGHT: - drawImage(overlayData, size.x - overlayData.width, size.y - - overlayData.height); - break; - } - } - } + switch (i) { + case IDecoration.TOP_LEFT: + drawImage(overlayData, 0, 0); + break; + case IDecoration.TOP_RIGHT: + drawImage(overlayData, size.x - overlayData.width, 0); + break; + case IDecoration.BOTTOM_LEFT: + drawImage(overlayData, 0, size.y - overlayData.height); + break; + case IDecoration.BOTTOM_RIGHT: + drawImage(overlayData, size.x - overlayData.width, size.y + - overlayData.height); + break; + } + } + } - @Override + @Override public boolean equals(Object o) { - if (!(o instanceof DecoratorOverlayIcon)) { + if (!(o instanceof DecoratorOverlayIcon)) { return false; } - DecoratorOverlayIcon other = (DecoratorOverlayIcon) o; - return base.equals(other.base) - && Arrays.equals(overlays, other.overlays); - } + DecoratorOverlayIcon other = (DecoratorOverlayIcon) o; + return base.equals(other.base) + && Arrays.equals(overlays, other.overlays); + } - @Override + @Override public int hashCode() { - int code = base.hashCode(); - for (int i = 0; i < overlays.length; i++) { - if (overlays[i] != null) { + int code = base.hashCode(); + for (int i = 0; i < overlays.length; i++) { + if (overlays[i] != null) { code ^= overlays[i].hashCode(); } - } - return code; - } + } + return code; + } - @Override + @Override protected void drawCompositeImage(int width, int height) { - ImageDescriptor underlay = overlays[IDecoration.UNDERLAY]; - if (underlay != null) { + ImageDescriptor underlay = overlays[IDecoration.UNDERLAY]; + if (underlay != null) { drawImage(underlay.getImageData(), 0, 0); } - drawImage(base.getImageData(), 0, 0); - drawOverlays(overlays); - } + drawImage(base.getImageData(), 0, 0); + drawOverlays(overlays); + } - @Override + @Override protected Point getSize() { - return size; - } + return size; + } - @Override + @Override protected int getTransparentPixel() { - return base.getImageData().transparentPixel; - } + return base.getImageData().transparentPixel; + } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchTargetPage.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchTargetPage.java index e762bf5f3..2c0e878b1 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchTargetPage.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchTargetPage.java @@ -92,15 +92,15 @@ public class PatchTargetPage extends WizardPage { useWorkspaceAsTarget.addListener(SWT.Selection, event -> { fShowError = true; - if (useWorkspaceAsTarget.getSelection()) { - fPatchTargets.getTree().setEnabled(false); - fPatcher.setTarget(ResourcesPlugin.getWorkspace().getRoot()); - } else { - fPatchTargets.getTree().setEnabled(true); - fPatcher.setTarget(Utilities.getFirstResource(fPatchTargets.getSelection())); - } - markPreviewPageToRecalucateIfNonWorkspacePatch(); - updateWidgetEnablements(); + if (useWorkspaceAsTarget.getSelection()) { + fPatchTargets.getTree().setEnabled(false); + fPatcher.setTarget(ResourcesPlugin.getWorkspace().getRoot()); + } else { + fPatchTargets.getTree().setEnabled(true); + fPatcher.setTarget(Utilities.getFirstResource(fPatchTargets.getSelection())); + } + markPreviewPageToRecalucateIfNonWorkspacePatch(); + updateWidgetEnablements(); }); } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchWizardDialog.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchWizardDialog.java index 211da60e4..a2a42d850 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchWizardDialog.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/PatchWizardDialog.java @@ -32,11 +32,11 @@ public class PatchWizardDialog extends WizardDialog { @Override protected IDialogSettings getDialogBoundsSettings() { - IDialogSettings settings = CompareUIPlugin.getDefault().getDialogSettings(); - IDialogSettings section = settings.getSection(PATCH_WIZARD_SETTINGS_SECTION); - if (section == null) { - section = settings.addNewSection(PATCH_WIZARD_SETTINGS_SECTION); - } - return section; + IDialogSettings settings = CompareUIPlugin.getDefault().getDialogSettings(); + IDialogSettings section = settings.getSection(PATCH_WIZARD_SETTINGS_SECTION); + if (section == null) { + section = settings.addNewSection(PATCH_WIZARD_SETTINGS_SECTION); + } + return section; } } diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/RetargetPatchElementDialog.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/RetargetPatchElementDialog.java index 778970a88..20f2a9314 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/RetargetPatchElementDialog.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/patch/RetargetPatchElementDialog.java @@ -49,7 +49,7 @@ class RetargetPatchElementDialog extends Dialog { private static class RetargetPatchContentProvider extends BaseWorkbenchContentProvider { private final PatchDiffNode node; public RetargetPatchContentProvider(PatchDiffNode node) { - this.node = node; + this.node = node; } @Override public Object[] getChildren(Object element) { @@ -104,8 +104,8 @@ class RetargetPatchElementDialog extends Dialog { GridLayout layout= new GridLayout(); layout.numColumns= 1; - layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); composite.setLayout(layout); final GridData data= new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(data); diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DiffTreeViewer.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DiffTreeViewer.java index f206b7234..aed63ed10 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DiffTreeViewer.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DiffTreeViewer.java @@ -370,8 +370,8 @@ public class DiffTreeViewer extends TreeViewer { /** * Overridden to avoid expanding {@code DiffNode}s that shouldn't expand. * - * @param node the node to expand - * @param level non-negative level, or {@code ALL_LEVELS} to collapse all levels of the tree + * @param node the node to expand + * @param level non-negative level, or {@code ALL_LEVELS} to collapse all levels of the tree */ @Override protected void internalExpandToLevel(Widget node, int level) { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DocumentRangeNode.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DocumentRangeNode.java index 701fd922f..28fad0147 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DocumentRangeNode.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/DocumentRangeNode.java @@ -255,8 +255,8 @@ public class DocumentRangeNode /** * Implementation based on <code>getID</code>. - * @param other the object to compare this <code>DocumentRangeNode</code> against. - * @return <code>true</code> if the <code>DocumentRangeNodes</code>are equal; <code>false</code> otherwise. + * @param other the object to compare this <code>DocumentRangeNode</code> against. + * @return <code>true</code> if the <code>DocumentRangeNodes</code>are equal; <code>false</code> otherwise. */ @Override public boolean equals(Object other) { diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/ICompareInputChangeListener.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/ICompareInputChangeListener.java index ad5319d60..2682af036 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/ICompareInputChangeListener.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/ICompareInputChangeListener.java @@ -32,7 +32,7 @@ package org.eclipse.compare.structuremergeviewer; public interface ICompareInputChangeListener { /** * Called whenever the value (not the content) of one or more of the three sides - * of a {@link ICompareInput} has changed. + * of a {@link ICompareInput} has changed. * * @param source the {@link ICompareInput} that has changed */ diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/StructureDiffViewer.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/StructureDiffViewer.java index e534f7cd6..af1093d5f 100644 --- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/StructureDiffViewer.java +++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/structuremergeviewer/StructureDiffViewer.java @@ -263,7 +263,7 @@ public class StructureDiffViewer extends DiffTreeViewer { return fRoot; } - /* + /* * Method declared on StructuredViewer. Overridden to create the comparable * structures from the input object and to feed them through the differencing * engine. Note: for this viewer the value from <code>getInput</code> is not diff --git a/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/ProxyType.java b/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/ProxyType.java index d4fe64494..d47165cc2 100644 --- a/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/ProxyType.java +++ b/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/ProxyType.java @@ -57,27 +57,27 @@ public class ProxyType implements INodeChangeListener, IPreferenceChangeListener public static final int NEVER_SET = 2; public static int socksSystemPropertySetting; - /** - * Absolute path to the node for the cached proxy information - */ - private static final String PREFERENCES_CONTEXT = "/org.eclipse.core.net.proxy.auth"; //$NON-NLS-1$ + /** + * Absolute path to the node for the cached proxy information + */ + private static final String PREFERENCES_CONTEXT = "/org.eclipse.core.net.proxy.auth"; //$NON-NLS-1$ /* * Fields used to cache authentication information in the keyring */ - private static final String INFO_PROXY_USER = "user"; //$NON-NLS-1$ - private static final String INFO_PROXY_PASS = "pass"; //$NON-NLS-1$ - static { - String value = System.getProperty(PROP_SOCKS_SYSTEM_PROPERTY_HANDLING); - if (value == null) { - socksSystemPropertySetting = ONLY_SET_FOR_1_5_OR_LATER; - } else if (value.equals("always")) { //$NON-NLS-1$ - socksSystemPropertySetting = ALWAYS_SET; - } else if (value.equals("never")) { //$NON-NLS-1$ - socksSystemPropertySetting = NEVER_SET; - } else { - socksSystemPropertySetting = ONLY_SET_FOR_1_5_OR_LATER; - } - } + private static final String INFO_PROXY_USER = "user"; //$NON-NLS-1$ + private static final String INFO_PROXY_PASS = "pass"; //$NON-NLS-1$ + static { + String value = System.getProperty(PROP_SOCKS_SYSTEM_PROPERTY_HANDLING); + if (value == null) { + socksSystemPropertySetting = ONLY_SET_FOR_1_5_OR_LATER; + } else if (value.equals("always")) { //$NON-NLS-1$ + socksSystemPropertySetting = ALWAYS_SET; + } else if (value.equals("never")) { //$NON-NLS-1$ + socksSystemPropertySetting = NEVER_SET; + } else { + socksSystemPropertySetting = ONLY_SET_FOR_1_5_OR_LATER; + } + } private String name; private boolean updatingPreferences; @@ -532,7 +532,7 @@ public class ProxyType implements INodeChangeListener, IPreferenceChangeListener return node; } - private void loadProxyAuth(IProxyData data) { + private void loadProxyAuth(IProxyData data) { ISecurePreferences node = getNode(); if (node == null) return; diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IHelpContextIds.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IHelpContextIds.java index cc47d2591..8012ddbfd 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IHelpContextIds.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IHelpContextIds.java @@ -15,7 +15,7 @@ package org.eclipse.jsch.internal.ui; public interface IHelpContextIds{ - public final String USER_VALIDATION_DIALOG="org.eclipse.team.cvs.ui.user_validation_dialog_contex"; //$NON-NLS-1$ - public final String KEYBOARD_INTERACTIVE_DIALOG="org.eclipse.team.cvs.ui.keyboard_interactive_dialog_context"; //$NON-NLS-1$ + public final String USER_VALIDATION_DIALOG="org.eclipse.team.cvs.ui.user_validation_dialog_contex"; //$NON-NLS-1$ + public final String KEYBOARD_INTERACTIVE_DIALOG="org.eclipse.team.cvs.ui.keyboard_interactive_dialog_context"; //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IUIConstants.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IUIConstants.java index b7a5a84a7..8144daf9c 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IUIConstants.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/IUIConstants.java @@ -15,15 +15,15 @@ package org.eclipse.jsch.internal.ui; public interface IUIConstants{ - public final String PREFIX=JSchUIPlugin.ID+"."; //$NON-NLS-1$ + public final String PREFIX=JSchUIPlugin.ID+"."; //$NON-NLS-1$ - // image path - public final String ICON_PATH="$nl$/icons/full/"; //$NON-NLS-1$ + // image path + public final String ICON_PATH="$nl$/icons/full/"; //$NON-NLS-1$ - // preferences - public final String PREF_FIRST_STARTUP="pref_first_startup"; //$NON-NLS-1$ + // preferences + public final String PREF_FIRST_STARTUP="pref_first_startup"; //$NON-NLS-1$ - // images - public final String IMG_KEY_LOCK="wizban/keylock.gif"; //$NON-NLS-1$ + // images + public final String IMG_KEY_LOCK="wizban/keylock.gif"; //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/JSchUIPlugin.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/JSchUIPlugin.java index 8345362fb..b8eef4087 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/JSchUIPlugin.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/JSchUIPlugin.java @@ -29,95 +29,95 @@ import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; public class JSchUIPlugin extends AbstractUIPlugin{ - public static final String ID="org.eclipse.jsch.ui"; //$NON-NLS-1$ - public static final String DECORATOR_ID="org.eclipse.jsch.ui.decorator"; //$NON-NLS-1$ - - private static Hashtable<String, ImageDescriptor> imageDescriptors = new Hashtable<>(20); - /** - * The singleton plug-in instance - */ - private static JSchUIPlugin plugin; - private ServiceTracker<?, ?> tracker; - - public JSchUIPlugin(){ - super(); - plugin=this; - } - - /** - * Returns the singleton plug-in instance. - * - * @return the plugin instance - */ - public static JSchUIPlugin getPlugin(){ - return plugin; - } - - /** - * Returns the image descriptor for the given image ID. - * Returns null if there is no such image. - * @param id the id of the image descriptor - * @return the image descriptor - */ - public static ImageDescriptor getImageDescriptor(String id){ - return imageDescriptors.get(id); - } - - /** - * Creates an image and places it in the image registry. - */ - protected void createImageDescriptor(String id){ - URL url=FileLocator.find(JSchUIPlugin.getPlugin().getBundle(), new Path( - IUIConstants.ICON_PATH+id), null); - ImageDescriptor desc=ImageDescriptor.createFromURL(url); - imageDescriptors.put(id, desc); - } - - /** - * Convenience method to get an image descriptor for an extension - * - * @param extension the extension declaring the image - * @param subdirectoryAndFilename the path to the image - * @return the image - */ - public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) { - URL fullPathString = FileLocator.find(Platform.getBundle(extension.getNamespaceIdentifier()), new Path(subdirectoryAndFilename), null); - return ImageDescriptor.createFromURL(fullPathString); - } - - /** - * Initializes the table of images used in this plugin. - */ - private void initializeImages() { - createImageDescriptor(IUIConstants.IMG_KEY_LOCK); - } - - @Override + public static final String ID="org.eclipse.jsch.ui"; //$NON-NLS-1$ + public static final String DECORATOR_ID="org.eclipse.jsch.ui.decorator"; //$NON-NLS-1$ + + private static Hashtable<String, ImageDescriptor> imageDescriptors = new Hashtable<>(20); + /** + * The singleton plug-in instance + */ + private static JSchUIPlugin plugin; + private ServiceTracker<?, ?> tracker; + + public JSchUIPlugin(){ + super(); + plugin=this; + } + + /** + * Returns the singleton plug-in instance. + * + * @return the plugin instance + */ + public static JSchUIPlugin getPlugin(){ + return plugin; + } + + /** + * Returns the image descriptor for the given image ID. + * Returns null if there is no such image. + * @param id the id of the image descriptor + * @return the image descriptor + */ + public static ImageDescriptor getImageDescriptor(String id){ + return imageDescriptors.get(id); + } + + /** + * Creates an image and places it in the image registry. + */ + protected void createImageDescriptor(String id){ + URL url=FileLocator.find(JSchUIPlugin.getPlugin().getBundle(), new Path( + IUIConstants.ICON_PATH+id), null); + ImageDescriptor desc=ImageDescriptor.createFromURL(url); + imageDescriptors.put(id, desc); + } + + /** + * Convenience method to get an image descriptor for an extension + * + * @param extension the extension declaring the image + * @param subdirectoryAndFilename the path to the image + * @return the image + */ + public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) { + URL fullPathString = FileLocator.find(Platform.getBundle(extension.getNamespaceIdentifier()), new Path(subdirectoryAndFilename), null); + return ImageDescriptor.createFromURL(fullPathString); + } + + /** + * Initializes the table of images used in this plugin. + */ + private void initializeImages() { + createImageDescriptor(IUIConstants.IMG_KEY_LOCK); + } + + @Override public void start(BundleContext context) throws Exception { - super.start(context); + super.start(context); - initializeImages(); + initializeImages(); - IPreferenceStore store = getPreferenceStore(); - if (store.getBoolean(IUIConstants.PREF_FIRST_STARTUP)) { - store.setValue(IUIConstants.PREF_FIRST_STARTUP, false); - } + IPreferenceStore store = getPreferenceStore(); + if (store.getBoolean(IUIConstants.PREF_FIRST_STARTUP)) { + store.setValue(IUIConstants.PREF_FIRST_STARTUP, false); + } - tracker = new ServiceTracker(getBundle().getBundleContext(),IJSchService.class.getName(), null); - tracker.open(); - } + tracker = new ServiceTracker(getBundle().getBundleContext(),IJSchService.class.getName(), null); + tracker.open(); + } - @Override + @Override public void stop(BundleContext context) throws Exception{ - super.stop(context); - tracker.close(); - } + super.stop(context); + tracker.close(); + } - public IJSchService getJSchService() { - return (IJSchService)tracker.getService(); - } + public IJSchService getJSchService() { + return (IJSchService)tracker.getService(); + } - public URL getImageUrl(String relative){ - return FileLocator.find(Platform.getBundle(ID), new Path(IUIConstants.ICON_PATH + relative), null); - } + public URL getImageUrl(String relative){ + return FileLocator.find(Platform.getBundle(ID), new Path(IUIConstants.ICON_PATH + relative), null); + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/KeyboardInteractiveDialog.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/KeyboardInteractiveDialog.java index 85f6dcd07..6b1328251 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/KeyboardInteractiveDialog.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/KeyboardInteractiveDialog.java @@ -37,68 +37,68 @@ import org.eclipse.ui.PlatformUI; * A dialog for keyboard-interactive authentication for the ssh2 connection. */ public class KeyboardInteractiveDialog extends TrayDialog { - // widgets - private Text[] texts; - protected Image keyLockImage; - protected Button allowCachingButton; - protected Text usernameField; - - protected String userName; - protected String domain; - protected String destination; - protected String name; - protected String instruction; - protected String lang; - protected String[] prompt; - protected boolean[] echo; - private String message; - private String[] result; - protected boolean allowCaching=false; - - private boolean isPasswordAuth=false; - - - /** - * Creates a new KeyboardInteractiveDialog. - * - * @param parentShell the parent shell - * @param location - * @param destination - * @param name the name - * @param userName - * @param instruction the instruction - * @param prompt the titles for text fields - * @param echo '*' should be used or not - */ - public KeyboardInteractiveDialog(Shell parentShell, - String location, - String destination, - String name, - String userName, - String instruction, - String[] prompt, - boolean[] echo){ - super(parentShell); - this.domain=location; - this.destination=destination; - this.name=name; - this.userName=userName; - this.instruction=instruction; - this.prompt=prompt; - this.echo=echo; - if (name!=null && name.length()>0) { - this.message=NLS.bind(Messages.KeyboardInteractiveDialog_0, new String[] { destination, name }); - } else { - this.message=NLS.bind(Messages.KeyboardInteractiveDialog_1, destination); - } - - if(KeyboardInteractiveDialog.isPasswordAuth(prompt)){ - isPasswordAuth=true; - } - } + // widgets + private Text[] texts; + protected Image keyLockImage; + protected Button allowCachingButton; + protected Text usernameField; + + protected String userName; + protected String domain; + protected String destination; + protected String name; + protected String instruction; + protected String lang; + protected String[] prompt; + protected boolean[] echo; + private String message; + private String[] result; + protected boolean allowCaching=false; + + private boolean isPasswordAuth=false; + + + /** + * Creates a new KeyboardInteractiveDialog. + * + * @param parentShell the parent shell + * @param location + * @param destination + * @param name the name + * @param userName + * @param instruction the instruction + * @param prompt the titles for text fields + * @param echo '*' should be used or not + */ + public KeyboardInteractiveDialog(Shell parentShell, + String location, + String destination, + String name, + String userName, + String instruction, + String[] prompt, + boolean[] echo){ + super(parentShell); + this.domain=location; + this.destination=destination; + this.name=name; + this.userName=userName; + this.instruction=instruction; + this.prompt=prompt; + this.echo=echo; + if (name!=null && name.length()>0) { + this.message=NLS.bind(Messages.KeyboardInteractiveDialog_0, new String[] { destination, name }); + } else { + this.message=NLS.bind(Messages.KeyboardInteractiveDialog_1, destination); + } + + if(KeyboardInteractiveDialog.isPasswordAuth(prompt)){ + isPasswordAuth=true; + } + } @Override - protected void configureShell(Shell newShell) { + protected void configureShell(Shell newShell) { super.configureShell(newShell); if (isPasswordAuth) { newShell.setText(Messages.KeyboardInteractiveDialog_2); @@ -112,7 +112,7 @@ public class KeyboardInteractiveDialog extends TrayDialog { } @Override - public void create() { + public void create() { super.create(); if (isPasswordAuth && usernameField != null && userName != null) { @@ -124,7 +124,7 @@ public class KeyboardInteractiveDialog extends TrayDialog { texts[0].setFocus(); } } - @Override + @Override protected Control createDialogArea(Composite parent) { Composite top = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); @@ -212,109 +212,109 @@ protected Control createDialogArea(Composite parent) { return main; } - /** - * Creates the three widgets that represent the user name entry area. - * - * @param parent the parent of the widgets - */ - protected void createUsernameFields(Composite parent){ - new Label(parent, SWT.NONE).setText(Messages.KeyboardInteractiveDialog_6); - - usernameField=new Text(parent, SWT.BORDER); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - usernameField.setLayoutData(data); - } - - /** + /** + * Creates the three widgets that represent the user name entry area. + * + * @param parent the parent of the widgets + */ + protected void createUsernameFields(Composite parent){ + new Label(parent, SWT.NONE).setText(Messages.KeyboardInteractiveDialog_6); + + usernameField=new Text(parent, SWT.BORDER); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + usernameField.setLayoutData(data); + } + + /** * Creates the widgets that represent the entry area. * * @param parent * the parent of the widgets */ - protected void createPasswordFields(Composite parent) { - texts=new Text[prompt.length]; - - for(int i=0; i<prompt.length; i++){ - new Label(parent, SWT.NONE).setText(prompt[i]); - int flag=SWT.BORDER; - if(!echo[i]){ - flag|=SWT.PASSWORD; - } - texts[i]=new Text(parent, flag); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - texts[i].setLayoutData(data); - if(!echo[i]){ - texts[i].setEchoChar('*'); - } - } - } - /** - * Returns the entered values, or null - * if the user canceled. - * - * @return the entered values - */ - public String[] getResult() { - return result; - } - - /** - * Returns <code>true</code> if the save password checkbox was selected. - * @return <code>true</code> if the save password checkbox was selected and <code>false</code> - * otherwise. - */ - public boolean getAllowCaching(){ - return allowCaching; - } - - /** - * Notifies that the ok button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets - * this dialog's return code to <code>Window.OK</code> - * and closes the dialog. Subclasses may override. - * </p> - */ - @Override + protected void createPasswordFields(Composite parent) { + texts=new Text[prompt.length]; + + for(int i=0; i<prompt.length; i++){ + new Label(parent, SWT.NONE).setText(prompt[i]); + int flag=SWT.BORDER; + if(!echo[i]){ + flag|=SWT.PASSWORD; + } + texts[i]=new Text(parent, flag); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + texts[i].setLayoutData(data); + if(!echo[i]){ + texts[i].setEchoChar('*'); + } + } + } + /** + * Returns the entered values, or null + * if the user canceled. + * + * @return the entered values + */ + public String[] getResult() { + return result; + } + + /** + * Returns <code>true</code> if the save password checkbox was selected. + * @return <code>true</code> if the save password checkbox was selected and <code>false</code> + * otherwise. + */ + public boolean getAllowCaching(){ + return allowCaching; + } + + /** + * Notifies that the ok button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets + * this dialog's return code to <code>Window.OK</code> + * and closes the dialog. Subclasses may override. + * </p> + */ + @Override protected void okPressed() { - result=new String[prompt.length]; - for(int i=0; i<texts.length; i++){ - result[i]=texts[i].getText(); - } - super.okPressed(); - } - /** - * Notifies that the cancel button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets - * this dialog's return code to <code>Window.CANCEL</code> - * and closes the dialog. Subclasses may override. - * </p> - */ - @Override + result=new String[prompt.length]; + for(int i=0; i<texts.length; i++){ + result[i]=texts[i].getText(); + } + super.okPressed(); + } + /** + * Notifies that the cancel button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets + * this dialog's return code to <code>Window.CANCEL</code> + * and closes the dialog. Subclasses may override. + * </p> + */ + @Override protected void cancelPressed() { - result=null; - super.cancelPressed(); - } - - @Override - public boolean close(){ - if(keyLockImage!=null){ - keyLockImage.dispose(); - } - return super.close(); - } - - /** - * Guesses if this dialog is used for password authentication. - * @param prompt prompts for keyboard-interactive authentication method. - * @return <code>true</code> if this dialog is used for password authentication. - */ - static boolean isPasswordAuth(String[] prompt) { + result=null; + super.cancelPressed(); + } + + @Override + public boolean close(){ + if(keyLockImage!=null){ + keyLockImage.dispose(); + } + return super.close(); + } + + /** + * Guesses if this dialog is used for password authentication. + * @param prompt prompts for keyboard-interactive authentication method. + * @return <code>true</code> if this dialog is used for password authentication. + */ + static boolean isPasswordAuth(String[] prompt) { return prompt != null && prompt.length == 1 && prompt[0].trim().equalsIgnoreCase("password:"); //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/Messages.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/Messages.java index 0dbd5e9ca..0453c56f0 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/Messages.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/Messages.java @@ -17,117 +17,117 @@ package org.eclipse.jsch.internal.ui; import org.eclipse.osgi.util.NLS; public class Messages extends NLS{ - private static final String BUNDLE_NAME="org.eclipse.jsch.internal.ui.messages";//$NON-NLS-1$ + private static final String BUNDLE_NAME="org.eclipse.jsch.internal.ui.messages";//$NON-NLS-1$ - static{ - // load message values from bundle file - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } + static{ + // load message values from bundle file + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } - public static String CVSSSH2ServerConnection_open; - public static String CVSSSH2PreferencePage_18; - public static String CVSSSH2PreferencePage_19; - public static String CVSSSH2PreferencePage_2; - public static String CVSSSH2PreferencePage_20; - public static String CVSSSH2PreferencePage_21; - public static String CVSSSH2PreferencePage_23; - public static String CVSSSH2PreferencePage_24; - public static String CVSSSH2PreferencePage_25; - public static String CVSSSH2PreferencePage_26; - public static String CVSSSH2PreferencePage_27; - public static String CVSSSH2PreferencePage_3; - public static String CVSSSH2PreferencePage_30; - public static String CVSSSH2PreferencePage_31; - public static String CVSSSH2PreferencePage_32; - public static String CVSSSH2PreferencePage_33; - public static String CVSSSH2PreferencePage_34; - public static String CVSSSH2PreferencePage_35; - public static String CVSSSH2PreferencePage_36; - public static String CVSSSH2PreferencePage_39; - public static String CVSSSH2PreferencePage_4; - public static String CVSSSH2PreferencePage_41; - public static String CVSSSH2PreferencePage_42; - public static String CVSSSH2PreferencePage_43; - public static String CVSSSH2PreferencePage_44; - public static String CVSSSH2PreferencePage_45; - public static String CVSSSH2PreferencePage_47; - public static String CVSSSH2PreferencePage_48; - public static String CVSSSH2PreferencePage_49; - public static String CVSSSH2PreferencePage_5; - public static String CVSSSH2PreferencePage_50; - public static String CVSSSH2PreferencePage_53; - public static String CVSSSH2PreferencePage_55; - public static String CVSSSH2PreferencePage_57; - public static String CVSSSH2PreferencePage_59; - public static String CVSSSH2PreferencePage_99; - public static String CVSSSH2PreferencePage_100; - public static String CVSSSH2PreferencePage_104; - public static String CVSSSH2PreferencePage_105; - public static String CVSSSH2PreferencePage_106; - public static String CVSSSH2PreferencePage_107; - public static String CVSSSH2PreferencePage_108; - public static String CVSSSH2PreferencePage_109; - public static String CVSSSH2PreferencePage_110; - public static String CVSSSH2PreferencePage_111; - public static String CVSSSH2ServerConnection_3; - public static String CVSSSH2ServerConnection_0; - public static String CVSSSH2ServerConnection_1; - public static String CVSSSH2PreferencePage_information; - public static String CVSSSH2PreferencePage_error; - public static String CVSSSH2PreferencePage_confirmation; - public static String CVSSSH2PreferencePage_question; - public static String CVSSSH2PreferencePage_125; - public static String CVSSSH2PreferencePage_126; - public static String CVSSSH2PreferencePage_127; - public static String CVSSSH2PreferencePage_128; - public static String CVSSSH2PreferencePage_129; - public static String CVSSSH2PreferencePage_130; - public static String CVSSSH2PreferencePage_131; - public static String CVSSSH2PreferencePage_132; - public static String CVSSSH2PreferencePage_133; - public static String CVSSSH2PreferencePage_134; - public static String CVSSSH2PreferencePage_135; - public static String CVSSSH2PreferencePage_136; - public static String CVSSSH2PreferencePage_137; - public static String CVSSSH2PreferencePage_138; - public static String CVSSSH2PreferencePage_139; - public static String CVSSSH2PreferencePage_140; - public static String CVSSSH2PreferencePage_141; - public static String CVSSSH2PreferencePage_142; - public static String CVSSSH2PreferencePage_143; - public static String CVSSSH2PreferencePage_144; - public static String CVSSSH2PreferencePage_145; - public static String CVSSSH2PreferencePage_146; - public static String CVSSSH2PreferencePage_147; - public static String KeyboardInteractiveDialog_0; - public static String KeyboardInteractiveDialog_1; - public static String KeyboardInteractiveDialog_2; - public static String KeyboardInteractiveDialog_3; - public static String KeyboardInteractiveDialog_4; - public static String KeyboardInteractiveDialog_6; - public static String KeyboradInteractiveDialog_message; - public static String KeyboardInteractiveDialog_labelRepository; + public static String CVSSSH2ServerConnection_open; + public static String CVSSSH2PreferencePage_18; + public static String CVSSSH2PreferencePage_19; + public static String CVSSSH2PreferencePage_2; + public static String CVSSSH2PreferencePage_20; + public static String CVSSSH2PreferencePage_21; + public static String CVSSSH2PreferencePage_23; + public static String CVSSSH2PreferencePage_24; + public static String CVSSSH2PreferencePage_25; + public static String CVSSSH2PreferencePage_26; + public static String CVSSSH2PreferencePage_27; + public static String CVSSSH2PreferencePage_3; + public static String CVSSSH2PreferencePage_30; + public static String CVSSSH2PreferencePage_31; + public static String CVSSSH2PreferencePage_32; + public static String CVSSSH2PreferencePage_33; + public static String CVSSSH2PreferencePage_34; + public static String CVSSSH2PreferencePage_35; + public static String CVSSSH2PreferencePage_36; + public static String CVSSSH2PreferencePage_39; + public static String CVSSSH2PreferencePage_4; + public static String CVSSSH2PreferencePage_41; + public static String CVSSSH2PreferencePage_42; + public static String CVSSSH2PreferencePage_43; + public static String CVSSSH2PreferencePage_44; + public static String CVSSSH2PreferencePage_45; + public static String CVSSSH2PreferencePage_47; + public static String CVSSSH2PreferencePage_48; + public static String CVSSSH2PreferencePage_49; + public static String CVSSSH2PreferencePage_5; + public static String CVSSSH2PreferencePage_50; + public static String CVSSSH2PreferencePage_53; + public static String CVSSSH2PreferencePage_55; + public static String CVSSSH2PreferencePage_57; + public static String CVSSSH2PreferencePage_59; + public static String CVSSSH2PreferencePage_99; + public static String CVSSSH2PreferencePage_100; + public static String CVSSSH2PreferencePage_104; + public static String CVSSSH2PreferencePage_105; + public static String CVSSSH2PreferencePage_106; + public static String CVSSSH2PreferencePage_107; + public static String CVSSSH2PreferencePage_108; + public static String CVSSSH2PreferencePage_109; + public static String CVSSSH2PreferencePage_110; + public static String CVSSSH2PreferencePage_111; + public static String CVSSSH2ServerConnection_3; + public static String CVSSSH2ServerConnection_0; + public static String CVSSSH2ServerConnection_1; + public static String CVSSSH2PreferencePage_information; + public static String CVSSSH2PreferencePage_error; + public static String CVSSSH2PreferencePage_confirmation; + public static String CVSSSH2PreferencePage_question; + public static String CVSSSH2PreferencePage_125; + public static String CVSSSH2PreferencePage_126; + public static String CVSSSH2PreferencePage_127; + public static String CVSSSH2PreferencePage_128; + public static String CVSSSH2PreferencePage_129; + public static String CVSSSH2PreferencePage_130; + public static String CVSSSH2PreferencePage_131; + public static String CVSSSH2PreferencePage_132; + public static String CVSSSH2PreferencePage_133; + public static String CVSSSH2PreferencePage_134; + public static String CVSSSH2PreferencePage_135; + public static String CVSSSH2PreferencePage_136; + public static String CVSSSH2PreferencePage_137; + public static String CVSSSH2PreferencePage_138; + public static String CVSSSH2PreferencePage_139; + public static String CVSSSH2PreferencePage_140; + public static String CVSSSH2PreferencePage_141; + public static String CVSSSH2PreferencePage_142; + public static String CVSSSH2PreferencePage_143; + public static String CVSSSH2PreferencePage_144; + public static String CVSSSH2PreferencePage_145; + public static String CVSSSH2PreferencePage_146; + public static String CVSSSH2PreferencePage_147; + public static String KeyboardInteractiveDialog_0; + public static String KeyboardInteractiveDialog_1; + public static String KeyboardInteractiveDialog_2; + public static String KeyboardInteractiveDialog_3; + public static String KeyboardInteractiveDialog_4; + public static String KeyboardInteractiveDialog_6; + public static String KeyboradInteractiveDialog_message; + public static String KeyboardInteractiveDialog_labelRepository; - public static String PreferencePage_0; - public static String PreferencePage_1; - public static String UserInfoPrompter_0; - public static String UserInfoPrompter_1; - public static String UserValidationDialog_0; - public static String UserValidationDialog_1; - public static String UserValidationDialog_2; - public static String UserValidationDialog_4; - public static String UserValidationDialog_5; - public static String UserValidationDialog_6; + public static String PreferencePage_0; + public static String PreferencePage_1; + public static String UserInfoPrompter_0; + public static String UserInfoPrompter_1; + public static String UserValidationDialog_0; + public static String UserValidationDialog_1; + public static String UserValidationDialog_2; + public static String UserValidationDialog_4; + public static String UserValidationDialog_5; + public static String UserValidationDialog_6; - public static String UserValidationDialog_required; - public static String UserValidationDialog_labelUser; - public static String UserValidationDialog_labelPassword; - public static String UserValidationDialog_password; - public static String UserValidationDialog_user; + public static String UserValidationDialog_required; + public static String UserValidationDialog_labelUser; + public static String UserValidationDialog_labelPassword; + public static String UserValidationDialog_password; + public static String UserValidationDialog_user; - public static String WorkbenchUserAuthenticator_cancelled; - public static String WorkbenchUserAuthenticator_1; - public static String WorkbenchUserAuthenticator_2; - public static String WorkbenchUserAuthenticator_The_operation_was_canceled_by_the_user_1; + public static String WorkbenchUserAuthenticator_cancelled; + public static String WorkbenchUserAuthenticator_1; + public static String WorkbenchUserAuthenticator_2; + public static String WorkbenchUserAuthenticator_The_operation_was_canceled_by_the_user_1; } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/UserValidationDialog.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/UserValidationDialog.java index 1859876b3..dcef8115a 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/UserValidationDialog.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/UserValidationDialog.java @@ -62,7 +62,7 @@ public class UserValidationDialog extends TrayDialog { */ public UserValidationDialog(Shell parentShell, String location, String defaultName, String message) { super(parentShell); - setShellStyle(getShellStyle() | SWT.RESIZE); + setShellStyle(getShellStyle() | SWT.RESIZE); this.defaultUsername = defaultName; this.domain = location; this.message = message; @@ -72,7 +72,7 @@ public class UserValidationDialog extends TrayDialog { super.configureShell(newShell); newShell.setText(Messages.UserValidationDialog_0); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IHelpContextIds.USER_VALIDATION_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IHelpContextIds.USER_VALIDATION_DIALOG); } @Override public void create() { @@ -153,7 +153,7 @@ public class UserValidationDialog extends TrayDialog { }); } - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); return main; } @@ -234,9 +234,9 @@ public class UserValidationDialog extends TrayDialog { @Override protected void cancelPressed(){ - password = null; - username = null; - super.cancelPressed(); + password = null; + username = null; + super.cancelPressed(); } /** diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/IHelpContextIds.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/IHelpContextIds.java index d4124076b..efdd1d5fc 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/IHelpContextIds.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/IHelpContextIds.java @@ -24,10 +24,10 @@ import org.eclipse.jsch.internal.ui.JSchUIPlugin; */ public interface IHelpContextIds{ - public static final String PREFIX=JSchUIPlugin.ID+"."; //$NON-NLS-1$ + public static final String PREFIX=JSchUIPlugin.ID+"."; //$NON-NLS-1$ - public static final String KEYBOARD_INTERACTIVE_DIALOG=PREFIX - +"keyboard_interactive_dialog_context"; //$NON-NLS-1$ - public static final String USER_VALIDATION_DIALOG=PREFIX - +"user_validation_dialog_context"; //$NON-NLS-1$ + public static final String KEYBOARD_INTERACTIVE_DIALOG=PREFIX + +"keyboard_interactive_dialog_context"; //$NON-NLS-1$ + public static final String USER_VALIDATION_DIALOG=PREFIX + +"user_validation_dialog_context"; //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/KeyboardInteractiveDialog.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/KeyboardInteractiveDialog.java index 40a6d82cc..a20b22e0c 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/KeyboardInteractiveDialog.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/KeyboardInteractiveDialog.java @@ -41,282 +41,282 @@ import org.eclipse.ui.PlatformUI; * @since 1.1 */ public class KeyboardInteractiveDialog extends TrayDialog{ - // whether or not the user name can be changed - protected boolean isUsernameMutable=false; - - // widgets - private Text[] texts; - protected Image keyLockImage; - protected Button allowCachingButton; - protected Text usernameField; - - protected String defaultUsername; - protected String comment; - protected String destination; - protected String name; - protected String instruction; - protected String lang; - protected String[] prompt; - protected boolean[] echo; - private String message; - private String[] result; - protected boolean allowCaching=false; - - private boolean isPasswordAuth=false; - - /** - * Creates a new KeyboardInteractiveDialog. - * - * @param parentShell the parent shell - * @param comment the comment - * @param destination the location - * @param name the name - * @param userName user name - * @param instruction the instruction - * @param prompt the titles for text-fields - * @param echo '*' should be used or not - */ - public KeyboardInteractiveDialog(Shell parentShell, String comment, - String destination, String name, String userName, String instruction, String[] prompt, - boolean[] echo){ - super(parentShell); - setShellStyle(getShellStyle()|SWT.RESIZE); - this.comment=comment; - this.destination=destination; - this.name=name; - this.defaultUsername=userName; - this.instruction=instruction; - this.prompt=prompt; - this.echo=echo; - this.message=NLS.bind(Messages.KeyboradInteractiveDialog_message, - new String[] {destination - +(name!=null&&name.length()>0 ? ": "+name : "")}); //NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-2$ - - if(prompt!=null && prompt.length==1 && prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ - isPasswordAuth=true; - } - - } - - @Override + // whether or not the user name can be changed + protected boolean isUsernameMutable=false; + + // widgets + private Text[] texts; + protected Image keyLockImage; + protected Button allowCachingButton; + protected Text usernameField; + + protected String defaultUsername; + protected String comment; + protected String destination; + protected String name; + protected String instruction; + protected String lang; + protected String[] prompt; + protected boolean[] echo; + private String message; + private String[] result; + protected boolean allowCaching=false; + + private boolean isPasswordAuth=false; + + /** + * Creates a new KeyboardInteractiveDialog. + * + * @param parentShell the parent shell + * @param comment the comment + * @param destination the location + * @param name the name + * @param userName user name + * @param instruction the instruction + * @param prompt the titles for text-fields + * @param echo '*' should be used or not + */ + public KeyboardInteractiveDialog(Shell parentShell, String comment, + String destination, String name, String userName, String instruction, String[] prompt, + boolean[] echo){ + super(parentShell); + setShellStyle(getShellStyle()|SWT.RESIZE); + this.comment=comment; + this.destination=destination; + this.name=name; + this.defaultUsername=userName; + this.instruction=instruction; + this.prompt=prompt; + this.echo=echo; + this.message=NLS.bind(Messages.KeyboradInteractiveDialog_message, + new String[] {destination + +(name!=null&&name.length()>0 ? ": "+name : "")}); //NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-2$ + + if(prompt!=null && prompt.length==1 && prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ + isPasswordAuth=true; + } + + } + + @Override protected void configureShell(Shell newShell){ - super.configureShell(newShell); - if(isPasswordAuth){ - newShell.setText(Messages.UserValidationDialog_required); - } - else{ - newShell.setText(message); - } - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, - IHelpContextIds.KEYBOARD_INTERACTIVE_DIALOG); - } - - @Override + super.configureShell(newShell); + if(isPasswordAuth){ + newShell.setText(Messages.UserValidationDialog_required); + } + else{ + newShell.setText(message); + } + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, + IHelpContextIds.KEYBOARD_INTERACTIVE_DIALOG); + } + + @Override public void create(){ - super.create(); + super.create(); - if(isPasswordAuth&&usernameField!=null){ - usernameField.setText(defaultUsername); - usernameField.setEditable(false); - } + if(isPasswordAuth&&usernameField!=null){ + usernameField.setText(defaultUsername); + usernameField.setEditable(false); + } - if(texts.length>0){ - texts[0].setFocus(); - } - } + if(texts.length>0){ + texts[0].setFocus(); + } + } - @Override + @Override protected Control createDialogArea(Composite parent){ - Composite top=new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.numColumns=2; - - top.setLayout(layout); - top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - Composite imageComposite=new Composite(top, SWT.NONE); - layout=new GridLayout(); - imageComposite.setLayout(layout); - imageComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); - - Composite main=new Composite(top, SWT.NONE); - layout=new GridLayout(); - layout.numColumns=3; - main.setLayout(layout); - main.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - Label imageLabel=new Label(imageComposite, SWT.NONE); - keyLockImage=JSchUIPlugin.getImageDescriptor(IUIConstants.IMG_KEY_LOCK) - .createImage(); - imageLabel.setImage(keyLockImage); - GridData data=new GridData(GridData.FILL_HORIZONTAL - |GridData.GRAB_HORIZONTAL); - imageLabel.setLayoutData(data); - - if(message!=null){ - Label messageLabel=new Label(main, SWT.WRAP); - messageLabel.setText(message); - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - data.widthHint=400; - messageLabel.setLayoutData(data); - } - if(comment!=null){ - Label label=new Label(main, SWT.WRAP); - if(isUsernameMutable){ - label.setText(NLS.bind(Messages.UserValidationDialog_labelUser, - new String[] {comment})); - } - else{ - label.setText(NLS.bind(Messages.UserValidationDialog_labelPassword, - (new Object[] {defaultUsername, comment}))); - } - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - data.widthHint=400; - label.setLayoutData(data); - } - if(instruction!=null&&instruction.length()>0){ - Label label=new Label(main, SWT.WRAP); - label.setText(instruction); - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - data.widthHint=400; - label.setLayoutData(data); - } - - if(isPasswordAuth){ - createUsernameFields(main); - } - - createPasswordFields(main); - - if(isPasswordAuth){ - allowCachingButton=new Button(main, SWT.CHECK); - allowCachingButton.setText(Messages.UserValidationDialog_6); - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - allowCachingButton.setLayoutData(data); - allowCachingButton.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - allowCaching=allowCachingButton.getSelection(); - } - }); - } - - Dialog.applyDialogFont(parent); - - return main; - } - - /** - * Creates the three widgets that represent the user name entry area. - * - * @param parent the parent of the widgets - */ - protected void createUsernameFields(Composite parent){ - new Label(parent, SWT.NONE).setText(Messages.UserValidationDialog_user); - - usernameField=new Text(parent, SWT.BORDER); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - usernameField.setLayoutData(data); - } - - /** - * Creates the widgets that represent the entry area. - * - * @param parent the parent of the widgets - */ - protected void createPasswordFields(Composite parent){ - texts=new Text[prompt.length]; - - for(int i=0; i<prompt.length; i++){ - new Label(parent, SWT.NONE).setText(prompt[i]); - int flag=SWT.BORDER; - if(!echo[i]){ - flag|=SWT.PASSWORD; - } - texts[i]=new Text(parent, flag); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - texts[i].setLayoutData(data); - if(!echo[i]){ - texts[i].setEchoChar('*'); - } - } - } - - /** - * Returns the entered values, or null - * if the user canceled. - * - * @return the entered values - */ - public String[] getResult(){ - return result; - } - - /** - * Returns <code>true</code> if the save password checkbox was selected. - * @return <code>true</code> if the save password checkbox was selected and <code>false</code> - * otherwise. - */ - public boolean getAllowCaching(){ - return allowCaching; - } - - /** - * Notifies that the ok button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets - * this dialog's return code to <code>Window.OK</code> - * and closes the dialog. Subclasses may override. - * </p> - */ - @Override + Composite top=new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.numColumns=2; + + top.setLayout(layout); + top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Composite imageComposite=new Composite(top, SWT.NONE); + layout=new GridLayout(); + imageComposite.setLayout(layout); + imageComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); + + Composite main=new Composite(top, SWT.NONE); + layout=new GridLayout(); + layout.numColumns=3; + main.setLayout(layout); + main.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Label imageLabel=new Label(imageComposite, SWT.NONE); + keyLockImage=JSchUIPlugin.getImageDescriptor(IUIConstants.IMG_KEY_LOCK) + .createImage(); + imageLabel.setImage(keyLockImage); + GridData data=new GridData(GridData.FILL_HORIZONTAL + |GridData.GRAB_HORIZONTAL); + imageLabel.setLayoutData(data); + + if(message!=null){ + Label messageLabel=new Label(main, SWT.WRAP); + messageLabel.setText(message); + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + data.widthHint=400; + messageLabel.setLayoutData(data); + } + if(comment!=null){ + Label label=new Label(main, SWT.WRAP); + if(isUsernameMutable){ + label.setText(NLS.bind(Messages.UserValidationDialog_labelUser, + new String[] {comment})); + } + else{ + label.setText(NLS.bind(Messages.UserValidationDialog_labelPassword, + (new Object[] {defaultUsername, comment}))); + } + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + data.widthHint=400; + label.setLayoutData(data); + } + if(instruction!=null&&instruction.length()>0){ + Label label=new Label(main, SWT.WRAP); + label.setText(instruction); + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + data.widthHint=400; + label.setLayoutData(data); + } + + if(isPasswordAuth){ + createUsernameFields(main); + } + + createPasswordFields(main); + + if(isPasswordAuth){ + allowCachingButton=new Button(main, SWT.CHECK); + allowCachingButton.setText(Messages.UserValidationDialog_6); + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + allowCachingButton.setLayoutData(data); + allowCachingButton.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + allowCaching=allowCachingButton.getSelection(); + } + }); + } + + Dialog.applyDialogFont(parent); + + return main; + } + + /** + * Creates the three widgets that represent the user name entry area. + * + * @param parent the parent of the widgets + */ + protected void createUsernameFields(Composite parent){ + new Label(parent, SWT.NONE).setText(Messages.UserValidationDialog_user); + + usernameField=new Text(parent, SWT.BORDER); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + usernameField.setLayoutData(data); + } + + /** + * Creates the widgets that represent the entry area. + * + * @param parent the parent of the widgets + */ + protected void createPasswordFields(Composite parent){ + texts=new Text[prompt.length]; + + for(int i=0; i<prompt.length; i++){ + new Label(parent, SWT.NONE).setText(prompt[i]); + int flag=SWT.BORDER; + if(!echo[i]){ + flag|=SWT.PASSWORD; + } + texts[i]=new Text(parent, flag); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + texts[i].setLayoutData(data); + if(!echo[i]){ + texts[i].setEchoChar('*'); + } + } + } + + /** + * Returns the entered values, or null + * if the user canceled. + * + * @return the entered values + */ + public String[] getResult(){ + return result; + } + + /** + * Returns <code>true</code> if the save password checkbox was selected. + * @return <code>true</code> if the save password checkbox was selected and <code>false</code> + * otherwise. + */ + public boolean getAllowCaching(){ + return allowCaching; + } + + /** + * Notifies that the ok button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets + * this dialog's return code to <code>Window.OK</code> + * and closes the dialog. Subclasses may override. + * </p> + */ + @Override protected void okPressed(){ - result=new String[prompt.length]; - for(int i=0; i<texts.length; i++){ - result[i]=texts[i].getText(); - } - super.okPressed(); - } - - /** - * Sets whether or not the username field should be mutable. - * This method must be called before create(), otherwise it - * will be ignored. - * - * @param value whether the username is mutable - */ - public void setUsernameMutable(boolean value){ - isUsernameMutable=value; - } - - /** - * Notifies that the cancel button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets - * this dialog's return code to <code>Window.CANCEL</code> - * and closes the dialog. Subclasses may override. - * </p> - */ - @Override - protected void cancelPressed(){ - result=null; - super.cancelPressed(); - } - - @Override - public boolean close(){ - if(keyLockImage!=null){ - keyLockImage.dispose(); - } - return super.close(); - } + result=new String[prompt.length]; + for(int i=0; i<texts.length; i++){ + result[i]=texts[i].getText(); + } + super.okPressed(); + } + + /** + * Sets whether or not the username field should be mutable. + * This method must be called before create(), otherwise it + * will be ignored. + * + * @param value whether the username is mutable + */ + public void setUsernameMutable(boolean value){ + isUsernameMutable=value; + } + + /** + * Notifies that the cancel button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets + * this dialog's return code to <code>Window.CANCEL</code> + * and closes the dialog. Subclasses may override. + * </p> + */ + @Override + protected void cancelPressed(){ + result=null; + super.cancelPressed(); + } + + @Override + public boolean close(){ + if(keyLockImage!=null){ + keyLockImage.dispose(); + } + return super.close(); + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/UserValidationDialog.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/UserValidationDialog.java index ea035fb83..f29ad949d 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/UserValidationDialog.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/UserValidationDialog.java @@ -40,239 +40,239 @@ import org.eclipse.ui.PlatformUI; * @since 1.1 */ public class UserValidationDialog extends TrayDialog{ - // widgets - protected Text usernameField; - protected Text passwordField; - protected Button allowCachingButton; + // widgets + protected Text usernameField; + protected Text passwordField; + protected Button allowCachingButton; - protected String comment; - protected String defaultUsername; - protected String password=null; - protected boolean allowCaching=false; - protected boolean isAllowCaching=false; - protected Image keyLockImage; + protected String comment; + protected String defaultUsername; + protected String password=null; + protected boolean allowCaching=false; + protected boolean isAllowCaching=false; + protected Image keyLockImage; - // whether or not the user name can be changed - protected boolean isUsernameMutable=true; - protected String username=null; - protected String message=null; + // whether or not the user name can be changed + protected boolean isUsernameMutable=true; + protected String username=null; + protected String message=null; - /** - * Creates a new UserValidationDialog. - * - * @param parentShell - * the parent shell - * @param comment - * the location - * @param defaultName - * the default user name - * @param message - * a message to display to the user - * @param isAllowCaching - * a flag to show a check box to save password - */ - public UserValidationDialog(Shell parentShell, String comment, - String defaultName, String message, boolean isAllowCaching){ - super(parentShell); - setShellStyle(getShellStyle()|SWT.RESIZE); - this.defaultUsername=defaultName; - this.comment=comment; - this.message=message; - this.isAllowCaching=isAllowCaching; - } + /** + * Creates a new UserValidationDialog. + * + * @param parentShell + * the parent shell + * @param comment + * the location + * @param defaultName + * the default user name + * @param message + * a message to display to the user + * @param isAllowCaching + * a flag to show a check box to save password + */ + public UserValidationDialog(Shell parentShell, String comment, + String defaultName, String message, boolean isAllowCaching){ + super(parentShell); + setShellStyle(getShellStyle()|SWT.RESIZE); + this.defaultUsername=defaultName; + this.comment=comment; + this.message=message; + this.isAllowCaching=isAllowCaching; + } @Override - protected void configureShell(Shell newShell){ - super.configureShell(newShell); - newShell.setText(Messages.UserValidationDialog_required); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, - IHelpContextIds.USER_VALIDATION_DIALOG); - } + protected void configureShell(Shell newShell){ + super.configureShell(newShell); + newShell.setText(Messages.UserValidationDialog_required); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, + IHelpContextIds.USER_VALIDATION_DIALOG); + } - @Override + @Override public void create(){ - super.create(); - // add some default values - usernameField.setText(defaultUsername); + super.create(); + // add some default values + usernameField.setText(defaultUsername); - if(isUsernameMutable){ - // give focus to user name field - usernameField.selectAll(); - usernameField.setFocus(); - } - else{ - usernameField.setEditable(false); - passwordField.setFocus(); - } - } + if(isUsernameMutable){ + // give focus to user name field + usernameField.selectAll(); + usernameField.setFocus(); + } + else{ + usernameField.setEditable(false); + passwordField.setFocus(); + } + } - @Override + @Override protected Control createDialogArea(Composite parent){ - Composite top=new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.numColumns=2; + Composite top=new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.numColumns=2; - top.setLayout(layout); - top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + top.setLayout(layout); + top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Composite imageComposite=new Composite(top, SWT.NONE); - layout=new GridLayout(); - imageComposite.setLayout(layout); - imageComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); + Composite imageComposite=new Composite(top, SWT.NONE); + layout=new GridLayout(); + imageComposite.setLayout(layout); + imageComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); - Composite main=new Composite(top, SWT.NONE); - layout=new GridLayout(); - layout.numColumns=3; - main.setLayout(layout); - main.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Composite main=new Composite(top, SWT.NONE); + layout=new GridLayout(); + layout.numColumns=3; + main.setLayout(layout); + main.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Label imageLabel=new Label(imageComposite, SWT.NONE); - keyLockImage=JSchUIPlugin.getImageDescriptor(IUIConstants.IMG_KEY_LOCK) - .createImage(); - imageLabel.setImage(keyLockImage); - GridData data=new GridData(GridData.FILL_HORIZONTAL - |GridData.GRAB_HORIZONTAL); - imageLabel.setLayoutData(data); + Label imageLabel=new Label(imageComposite, SWT.NONE); + keyLockImage=JSchUIPlugin.getImageDescriptor(IUIConstants.IMG_KEY_LOCK) + .createImage(); + imageLabel.setImage(keyLockImage); + GridData data=new GridData(GridData.FILL_HORIZONTAL + |GridData.GRAB_HORIZONTAL); + imageLabel.setLayoutData(data); - if(message!=null){ - Label messageLabel=new Label(main, SWT.WRAP); - messageLabel.setText(message); - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - data.widthHint=400; - messageLabel.setLayoutData(data); - } - if(comment!=null){ - Label label=new Label(main, SWT.WRAP); - if(isUsernameMutable){ - label.setText(NLS.bind(Messages.UserValidationDialog_labelUser, - new String[] {comment})); - } - else{ - label.setText(NLS.bind(Messages.UserValidationDialog_labelPassword, - (new Object[] {defaultUsername, comment}))); - } - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - data.widthHint=400; - label.setLayoutData(data); - } - createUsernameFields(main); - createPasswordFields(main); + if(message!=null){ + Label messageLabel=new Label(main, SWT.WRAP); + messageLabel.setText(message); + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + data.widthHint=400; + messageLabel.setLayoutData(data); + } + if(comment!=null){ + Label label=new Label(main, SWT.WRAP); + if(isUsernameMutable){ + label.setText(NLS.bind(Messages.UserValidationDialog_labelUser, + new String[] {comment})); + } + else{ + label.setText(NLS.bind(Messages.UserValidationDialog_labelPassword, + (new Object[] {defaultUsername, comment}))); + } + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + data.widthHint=400; + label.setLayoutData(data); + } + createUsernameFields(main); + createPasswordFields(main); - if(isAllowCaching){ - allowCachingButton=new Button(main, SWT.CHECK); - allowCachingButton.setText(Messages.UserValidationDialog_6); - data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); - data.horizontalSpan=3; - allowCachingButton.setLayoutData(data); - allowCachingButton.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - allowCaching=allowCachingButton.getSelection(); - } - }); - } + if(isAllowCaching){ + allowCachingButton=new Button(main, SWT.CHECK); + allowCachingButton.setText(Messages.UserValidationDialog_6); + data=new GridData(GridData.FILL_HORIZONTAL|GridData.GRAB_HORIZONTAL); + data.horizontalSpan=3; + allowCachingButton.setLayoutData(data); + allowCachingButton.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + allowCaching=allowCachingButton.getSelection(); + } + }); + } - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); - return main; - } + return main; + } - /** - * Creates the three widgets that represent the password entry area. - * - * @param parent - * the parent of the widgets - */ - protected void createPasswordFields(Composite parent){ - new Label(parent, SWT.NONE).setText(Messages.UserValidationDialog_password); + /** + * Creates the three widgets that represent the password entry area. + * + * @param parent + * the parent of the widgets + */ + protected void createPasswordFields(Composite parent){ + new Label(parent, SWT.NONE).setText(Messages.UserValidationDialog_password); - passwordField=new Text(parent, SWT.BORDER|SWT.PASSWORD); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - passwordField.setLayoutData(data); - } + passwordField=new Text(parent, SWT.BORDER|SWT.PASSWORD); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + passwordField.setLayoutData(data); + } - /** - * Creates the three widgets that represent the user name entry area. - * - * @param parent - * the parent of the widgets - */ - protected void createUsernameFields(Composite parent){ - new Label(parent, SWT.NONE).setText(Messages.UserValidationDialog_user); + /** + * Creates the three widgets that represent the user name entry area. + * + * @param parent + * the parent of the widgets + */ + protected void createUsernameFields(Composite parent){ + new Label(parent, SWT.NONE).setText(Messages.UserValidationDialog_user); - usernameField=new Text(parent, SWT.BORDER); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - usernameField.setLayoutData(data); - } + usernameField=new Text(parent, SWT.BORDER); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + usernameField.setLayoutData(data); + } - /** - * Returns the password entered by the user, or null if the user canceled. - * - * @return the entered password - */ - public String getPassword(){ - return password; - } + /** + * Returns the password entered by the user, or null if the user canceled. + * + * @return the entered password + */ + public String getPassword(){ + return password; + } - /** - * Returns the username entered by the user, or null if the user canceled. - * - * @return the entered username - */ - public String getUsername(){ - return username; - } + /** + * Returns the username entered by the user, or null if the user canceled. + * + * @return the entered username + */ + public String getUsername(){ + return username; + } - /** - * Returns <code>true</code> if the save password checkbox was selected. - * - * @return <code>true</code> if the save password checkbox was selected and - * <code>false</code> otherwise. - */ - public boolean getAllowCaching(){ - return allowCaching; - } + /** + * Returns <code>true</code> if the save password checkbox was selected. + * + * @return <code>true</code> if the save password checkbox was selected and + * <code>false</code> otherwise. + */ + public boolean getAllowCaching(){ + return allowCaching; + } - /** - * Notifies that the ok button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets this dialog's - * return code to <code>Window.OK</code> and closes the dialog. Subclasses - * may override. - * </p> - */ - @Override + /** + * Notifies that the ok button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets this dialog's + * return code to <code>Window.OK</code> and closes the dialog. Subclasses + * may override. + * </p> + */ + @Override protected void okPressed(){ - password=passwordField.getText(); - username=usernameField.getText(); + password=passwordField.getText(); + username=usernameField.getText(); - super.okPressed(); - } + super.okPressed(); + } - /** - * Sets whether or not the username field should be mutable. This method must - * be called before create(), otherwise it will be ignored. - * - * @param value - * whether the username is mutable - */ - public void setUsernameMutable(boolean value){ - isUsernameMutable=value; - } + /** + * Sets whether or not the username field should be mutable. This method must + * be called before create(), otherwise it will be ignored. + * + * @param value + * whether the username is mutable + */ + public void setUsernameMutable(boolean value){ + isUsernameMutable=value; + } - @Override - public boolean close(){ - if(keyLockImage!=null){ - keyLockImage.dispose(); - } - return super.close(); - } + @Override + public boolean close(){ + if(keyLockImage!=null){ + keyLockImage.dispose(); + } + return super.close(); + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/WorkbenchUserAuthenticator.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/WorkbenchUserAuthenticator.java index 1276044b2..24672fa49 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/WorkbenchUserAuthenticator.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/authenticator/WorkbenchUserAuthenticator.java @@ -36,163 +36,163 @@ import org.eclipse.ui.PlatformUI; * @since 1.1 */ public class WorkbenchUserAuthenticator implements IUserAuthenticator{ - /** - * WorkbenchUserAuthenticator constructor. - */ - public WorkbenchUserAuthenticator(){ - super(); - } - - @Override + /** + * WorkbenchUserAuthenticator constructor. + */ + public WorkbenchUserAuthenticator(){ + super(); + } + + @Override public void promptForUserInfo(final IJSchLocation location, - final IUserInfo userinfo, final String message){ - - // ask the user for a password - final String[] result=new String[2]; - Display display=Display.getCurrent(); - final boolean allowCaching[]= {false}; - if(display!=null){ - allowCaching[0]=promptForPassword(location, userinfo.getUsername(), - message, userinfo.isUsernameMutable(), result); - } - else{ - // sync exec in default thread + final IUserInfo userinfo, final String message){ + + // ask the user for a password + final String[] result=new String[2]; + Display display=Display.getCurrent(); + final boolean allowCaching[]= {false}; + if(display!=null){ + allowCaching[0]=promptForPassword(location, userinfo.getUsername(), + message, userinfo.isUsernameMutable(), result); + } + else{ + // sync exec in default thread Display.getDefault().syncExec(() -> allowCaching[0] = promptForPassword(location, userinfo.getUsername(), message, userinfo.isUsernameMutable(), result)); - } - - if(result[0]==null){ - throw new OperationCanceledException( - Messages.WorkbenchUserAuthenticator_cancelled); - } - - if(userinfo.isUsernameMutable()){ - userinfo.setUsername(result[0]); - - } - userinfo.setPassword(result[1]); - - if(location!=null){ - if(userinfo.isUsernameMutable()){ - location.setUsername(result[0]); - } - location.setPassword(result[1]); - if(location.getPasswordStore()!=null){ - if(allowCaching[0]) - location.getPasswordStore().update(location); - else - location.getPasswordStore().clear(location); - } - } - } - - /** - * Asks the user to enter a password. Places the - * results in the supplied string[]. result[0] must - * contain the username, result[1] must contain the password. - * If the user canceled, both values must be zero. - * - * @param location the location to obtain the password for - * @param username the username - * @param message a message to display to the user - * @param userMutable whether the user can be changed in the dialog - * @param result a String array of length two in which to put the result - */ - protected boolean promptForPassword(final IJSchLocation location, - final String username, final String message, final boolean userMutable, - final String[] result){ - String comment=location==null ? null : location.getComment(); - UserValidationDialog dialog=new UserValidationDialog(null, comment, - (username==null) ? "" : username, message, (location!=null && location.getPasswordStore()!=null));//$NON-NLS-1$ - dialog.setUsernameMutable(userMutable); - dialog.open(); - result[0]=dialog.getUsername(); - result[1]=dialog.getPassword(); - return dialog.getAllowCaching(); - } - - /** - * Asks the user to enter values. - * - * @param location the location to obtain the password for - * @param destination the location - * @param name the name - * @param instruction the instruction - * @param prompt the titles for text fields - * @param echo '*' should be used or not - * @return the entered values, or null if user canceled. - */ - @Override + } + + if(result[0]==null){ + throw new OperationCanceledException( + Messages.WorkbenchUserAuthenticator_cancelled); + } + + if(userinfo.isUsernameMutable()){ + userinfo.setUsername(result[0]); + + } + userinfo.setPassword(result[1]); + + if(location!=null){ + if(userinfo.isUsernameMutable()){ + location.setUsername(result[0]); + } + location.setPassword(result[1]); + if(location.getPasswordStore()!=null){ + if(allowCaching[0]) + location.getPasswordStore().update(location); + else + location.getPasswordStore().clear(location); + } + } + } + + /** + * Asks the user to enter a password. Places the + * results in the supplied string[]. result[0] must + * contain the username, result[1] must contain the password. + * If the user canceled, both values must be zero. + * + * @param location the location to obtain the password for + * @param username the username + * @param message a message to display to the user + * @param userMutable whether the user can be changed in the dialog + * @param result a String array of length two in which to put the result + */ + protected boolean promptForPassword(final IJSchLocation location, + final String username, final String message, final boolean userMutable, + final String[] result){ + String comment=location==null ? null : location.getComment(); + UserValidationDialog dialog=new UserValidationDialog(null, comment, + (username==null) ? "" : username, message, (location!=null && location.getPasswordStore()!=null));//$NON-NLS-1$ + dialog.setUsernameMutable(userMutable); + dialog.open(); + result[0]=dialog.getUsername(); + result[1]=dialog.getPassword(); + return dialog.getAllowCaching(); + } + + /** + * Asks the user to enter values. + * + * @param location the location to obtain the password for + * @param destination the location + * @param name the name + * @param instruction the instruction + * @param prompt the titles for text fields + * @param echo '*' should be used or not + * @return the entered values, or null if user canceled. + */ + @Override public String[] promptForKeyboradInteractive( - final IJSchLocation location, final String destination, - final String name, final String instruction, final String[] prompt, - final boolean[] echo){ - final String[][] result=new String[1][]; - final boolean[] allowCaching=new boolean[1]; - Display display=Display.getCurrent(); - if(display!=null){ - result[0]=_promptForUserInteractive(location, destination, name, - instruction, prompt, echo, allowCaching); - } - else{ - // sync exec in default thread + final IJSchLocation location, final String destination, + final String name, final String instruction, final String[] prompt, + final boolean[] echo){ + final String[][] result=new String[1][]; + final boolean[] allowCaching=new boolean[1]; + Display display=Display.getCurrent(); + if(display!=null){ + result[0]=_promptForUserInteractive(location, destination, name, + instruction, prompt, echo, allowCaching); + } + else{ + // sync exec in default thread Display.getDefault().syncExec(() -> result[0] = _promptForUserInteractive(location, destination, name, instruction, prompt, echo, allowCaching)); - } - if(result[0]!=null && location!=null && - prompt!=null && prompt.length==1 && prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ - location.setPassword(result[0][0]); - if(location.getPasswordStore()!=null){ - if(allowCaching[0]) - location.getPasswordStore().update(location); - else - location.getPasswordStore().clear(location); - } - } - return result[0]; - } - - protected String[] _promptForUserInteractive( - final IJSchLocation location, final String destination, - final String name, final String instruction, final String[] prompt, - final boolean[] echo, final boolean[] allowCaching){ - String comment=location==null ? null : location.getComment(); - String username=location==null ? "" : location.getUsername(); //$NON-NLS-1$ - KeyboardInteractiveDialog dialog=new KeyboardInteractiveDialog(null, - comment, destination, name, username, instruction, prompt, echo); - dialog.setUsernameMutable(false); - dialog.open(); - String[] _result=dialog.getResult(); - if(_result!=null) - allowCaching[0]=dialog.getAllowCaching(); - return _result; - } - - - @Override + } + if(result[0]!=null && location!=null && + prompt!=null && prompt.length==1 && prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ + location.setPassword(result[0][0]); + if(location.getPasswordStore()!=null){ + if(allowCaching[0]) + location.getPasswordStore().update(location); + else + location.getPasswordStore().clear(location); + } + } + return result[0]; + } + + protected String[] _promptForUserInteractive( + final IJSchLocation location, final String destination, + final String name, final String instruction, final String[] prompt, + final boolean[] echo, final boolean[] allowCaching){ + String comment=location==null ? null : location.getComment(); + String username=location==null ? "" : location.getUsername(); //$NON-NLS-1$ + KeyboardInteractiveDialog dialog=new KeyboardInteractiveDialog(null, + comment, destination, name, username, instruction, prompt, echo); + dialog.setUsernameMutable(false); + dialog.open(); + String[] _result=dialog.getResult(); + if(_result!=null) + allowCaching[0]=dialog.getAllowCaching(); + return _result; + } + + + @Override public int prompt(IJSchLocation location, final int promptType, - final String title, final String message, final int[] promptResponses, - final int defaultResponse){ - final Display display=getStandardDisplay(); - final int[] retval=new int[1]; - final String[] buttons=new String[promptResponses.length]; - for(int i=0; i<promptResponses.length; i++){ - int prompt=promptResponses[i]; - switch(prompt){ - case IUserAuthenticator.OK_ID: - buttons[i]=IDialogConstants.OK_LABEL; - break; - case IUserAuthenticator.CANCEL_ID: - buttons[i]=IDialogConstants.CANCEL_LABEL; - break; - case IUserAuthenticator.NO_ID: - buttons[i]=IDialogConstants.NO_LABEL; - break; - case IUserAuthenticator.YES_ID: - buttons[i]=IDialogConstants.YES_LABEL; - break; - } - } + final String title, final String message, final int[] promptResponses, + final int defaultResponse){ + final Display display=getStandardDisplay(); + final int[] retval=new int[1]; + final String[] buttons=new String[promptResponses.length]; + for(int i=0; i<promptResponses.length; i++){ + int prompt=promptResponses[i]; + switch(prompt){ + case IUserAuthenticator.OK_ID: + buttons[i]=IDialogConstants.OK_LABEL; + break; + case IUserAuthenticator.CANCEL_ID: + buttons[i]=IDialogConstants.CANCEL_LABEL; + break; + case IUserAuthenticator.NO_ID: + buttons[i]=IDialogConstants.NO_LABEL; + break; + case IUserAuthenticator.YES_ID: + buttons[i]=IDialogConstants.YES_LABEL; + break; + } + } display.syncExec(() -> { Shell shell = null; @@ -207,35 +207,35 @@ public int prompt(IJSchLocation location, final int promptType, shell = new Shell(display); } final MessageDialog dialog = new MessageDialog(shell, title, - null, message, promptType, buttons, 1); - retval[0]=dialog.open(); + null, message, promptType, buttons, 1); + retval[0]=dialog.open(); }); - return retval[0]; - } + return retval[0]; + } - @Override + @Override public boolean promptForHostKeyChange(final IJSchLocation location){ - final boolean[] openConfirm=new boolean[] {false}; - final Display display=getStandardDisplay(); + final boolean[] openConfirm=new boolean[] {false}; + final Display display=getStandardDisplay(); display.syncExec(() -> openConfirm[0] = MessageDialog.openConfirm(null, Messages.WorkbenchUserAuthenticator_1, NLS.bind(Messages.WorkbenchUserAuthenticator_2, new String[] { location.getHost() }))); - if(!openConfirm[0]){ - throw new OperationCanceledException(); - } - return openConfirm[0]; - } - - /** - * Returns the standard display to be used. The method first checks, if - * the thread calling this method has an associated display. If so, this - * display is returned. Otherwise the method returns the default display. - * @return standard display - */ - private Display getStandardDisplay(){ - Display display=Display.getCurrent(); - if(display==null){ - display=Display.getDefault(); - } - return display; - } + if(!openConfirm[0]){ + throw new OperationCanceledException(); + } + return openConfirm[0]; + } + + /** + * Returns the standard display to be used. The method first checks, if + * the thread calling this method has an associated display. If so, this + * display is returned. Otherwise the method returns the default display. + * @return standard display + */ + private Display getStandardDisplay(){ + Display display=Display.getCurrent(); + if(display==null){ + display=Display.getDefault(); + } + return display; + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/ExportDialog.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/ExportDialog.java index b7cb27825..df4c889aa 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/ExportDialog.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/ExportDialog.java @@ -28,76 +28,76 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; class ExportDialog extends Dialog{ - protected Text field; - protected String target=null; - protected String title=null; - protected String message=null; + protected Text field; + protected String target=null; + protected String title=null; + protected String message=null; - public ExportDialog(Shell parentShell, String title, String message){ - super(parentShell); - this.title=title; - this.message=message; - } + public ExportDialog(Shell parentShell, String title, String message){ + super(parentShell); + this.title=title; + this.message=message; + } - protected void configureShell(Shell newShell){ - super.configureShell(newShell); - newShell.setText(title); - } + protected void configureShell(Shell newShell){ + super.configureShell(newShell); + newShell.setText(title); + } - public void create(){ - super.create(); - field.setFocus(); - } + public void create(){ + super.create(); + field.setFocus(); + } - protected Control createDialogArea(Composite parent){ - initializeDialogUnits(parent); - Composite main=new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.numColumns=2; - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - main.setLayout(layout); - main.setLayoutData(new GridData(GridData.FILL_BOTH)); + protected Control createDialogArea(Composite parent){ + initializeDialogUnits(parent); + Composite main=new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.numColumns=2; + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + main.setLayout(layout); + main.setLayoutData(new GridData(GridData.FILL_BOTH)); - if(message!=null){ - Label messageLabel=new Label(main, SWT.WRAP); - messageLabel.setText(message); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - messageLabel.setLayoutData(data); - } + if(message!=null){ + Label messageLabel=new Label(main, SWT.WRAP); + messageLabel.setText(message); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + messageLabel.setLayoutData(data); + } - createTargetFields(main); - Dialog.applyDialogFont(main); - return main; - } + createTargetFields(main); + Dialog.applyDialogFont(main); + return main; + } - protected void createTargetFields(Composite parent){ - new Label(parent, SWT.NONE).setText(Messages.CVSSSH2PreferencePage_125); + protected void createTargetFields(Composite parent){ + new Label(parent, SWT.NONE).setText(Messages.CVSSSH2PreferencePage_125); - field=new Text(parent, SWT.BORDER); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - field.setLayoutData(data); - } + field=new Text(parent, SWT.BORDER); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + field.setLayoutData(data); + } - public String getTarget(){ - return target; - } + public String getTarget(){ + return target; + } - protected void okPressed(){ - String _target=field.getText(); - if(_target==null||_target.length()==0){ - return; - } - target=_target; - super.okPressed(); - } + protected void okPressed(){ + String _target=field.getText(); + if(_target==null||_target.length()==0){ + return; + } + target=_target; + super.okPressed(); + } - protected void cancelPressed(){ - target=null; - super.cancelPressed(); - } + protected void cancelPressed(){ + target=null; + super.cancelPressed(); + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PassphraseDialog.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PassphraseDialog.java index bd092f433..e30f18d4c 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PassphraseDialog.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PassphraseDialog.java @@ -28,77 +28,77 @@ import org.eclipse.swt.widgets.Text; class PassphraseDialog extends Dialog{ - protected Text passphraseField; - protected String passphrase=null; - protected String message=null; + protected Text passphraseField; + protected String passphrase=null; + protected String message=null; - public PassphraseDialog(Shell parentShell, String message){ - super(parentShell); - this.message=message; - } + public PassphraseDialog(Shell parentShell, String message){ + super(parentShell); + this.message=message; + } - protected void configureShell(Shell newShell){ - super.configureShell(newShell); - newShell.setText(message); - } + protected void configureShell(Shell newShell){ + super.configureShell(newShell); + newShell.setText(message); + } - public void create(){ - super.create(); - passphraseField.setFocus(); - } + public void create(){ + super.create(); + passphraseField.setFocus(); + } - protected Control createDialogArea(Composite parent){ - initializeDialogUnits(parent); - Composite main=new Composite(parent, SWT.NONE); + protected Control createDialogArea(Composite parent){ + initializeDialogUnits(parent); + Composite main=new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.numColumns=3; - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - main.setLayout(layout); - main.setLayoutData(new GridData(GridData.FILL_BOTH)); + GridLayout layout=new GridLayout(); + layout.numColumns=3; + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + main.setLayout(layout); + main.setLayoutData(new GridData(GridData.FILL_BOTH)); - if(message!=null){ - Label messageLabel=new Label(main, SWT.WRAP); - messageLabel.setText(message); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=3; - messageLabel.setLayoutData(data); - } + if(message!=null){ + Label messageLabel=new Label(main, SWT.WRAP); + messageLabel.setText(message); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=3; + messageLabel.setLayoutData(data); + } - createPassphraseFields(main); - Dialog.applyDialogFont(main); - return main; - } + createPassphraseFields(main); + Dialog.applyDialogFont(main); + return main; + } - protected void createPassphraseFields(Composite parent){ - new Label(parent, SWT.NONE).setText(Messages.CVSSSH2PreferencePage_127); - passphraseField=new Text(parent, SWT.BORDER); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - passphraseField.setLayoutData(data); - passphraseField.setEchoChar('*'); + protected void createPassphraseFields(Composite parent){ + new Label(parent, SWT.NONE).setText(Messages.CVSSSH2PreferencePage_127); + passphraseField=new Text(parent, SWT.BORDER); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + passphraseField.setLayoutData(data); + passphraseField.setEchoChar('*'); - new Label(parent, SWT.NONE); - } + new Label(parent, SWT.NONE); + } - public String getPassphrase(){ - return passphrase; - } + public String getPassphrase(){ + return passphrase; + } - protected void okPressed(){ - String _passphrase=passphraseField.getText(); - if(_passphrase==null||_passphrase.length()==0){ - return; - } - passphrase=_passphrase; - super.okPressed(); - } + protected void okPressed(){ + String _passphrase=passphraseField.getText(); + if(_passphrase==null||_passphrase.length()==0){ + return; + } + passphrase=_passphrase; + super.okPressed(); + } - protected void cancelPressed(){ - passphrase=null; - super.cancelPressed(); - } + protected void cancelPressed(){ + passphrase=null; + super.cancelPressed(); + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PixelConverter.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PixelConverter.java index 73198c8c5..4a6fc150c 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PixelConverter.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PixelConverter.java @@ -25,12 +25,12 @@ public class PixelConverter { public PixelConverter(Control control) { GC gc = new GC(control); - try { - gc.setFont(control.getFont()); - fFontMetrics= gc.getFontMetrics(); - } finally { - gc.dispose(); - } + try { + gc.setFont(control.getFont()); + fFontMetrics= gc.getFontMetrics(); + } finally { + gc.dispose(); + } } public int convertHeightInCharsToPixels(int chars) { diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PreferencePage.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PreferencePage.java index 5685e34c0..6544592a8 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PreferencePage.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/PreferencePage.java @@ -86,416 +86,416 @@ import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; public class PreferencePage extends org.eclipse.jface.preference.PreferencePage - implements IWorkbenchPreferencePage{ - - private static final String SSH2_PREFERENCE_PAGE_CONTEXT="org.eclipse.jsch.ui.ssh2_preference_page_context"; //$NON-NLS-1$ - - private Label ssh2HomeLabel; - private Label privateKeyLabel; - Text ssh2HomeText; - Text privateKeyText; - private Button privateKeyAdd; - - private Button ssh2HomeBrowse; - Button keyGenerateDSA; - Button keyGenerateRSA; - private Button keyLoad; - private Button keyExport; - Button saveKeyPair; - private Label keyCommentLabel; - Text keyCommentText; - private Label keyFingerPrintLabel; - Text keyFingerPrintText; - private Label keyPassphrase1Label; - Text keyPassphrase1Text; - private Label keyPassphrase2Label; - Text keyPassphrase2Text; - private Label publicKeylabel; - Text publicKeyText; - KeyPair kpair=null; - String kpairComment; - - public static final String AUTH_SCHEME="";//$NON-NLS-1$ - - public PreferencePage(){ - setDescription(Messages.CVSSSH2PreferencePage_18); - } - - @Override + implements IWorkbenchPreferencePage{ + + private static final String SSH2_PREFERENCE_PAGE_CONTEXT="org.eclipse.jsch.ui.ssh2_preference_page_context"; //$NON-NLS-1$ + + private Label ssh2HomeLabel; + private Label privateKeyLabel; + Text ssh2HomeText; + Text privateKeyText; + private Button privateKeyAdd; + + private Button ssh2HomeBrowse; + Button keyGenerateDSA; + Button keyGenerateRSA; + private Button keyLoad; + private Button keyExport; + Button saveKeyPair; + private Label keyCommentLabel; + Text keyCommentText; + private Label keyFingerPrintLabel; + Text keyFingerPrintText; + private Label keyPassphrase1Label; + Text keyPassphrase1Text; + private Label keyPassphrase2Label; + Text keyPassphrase2Text; + private Label publicKeylabel; + Text publicKeyText; + KeyPair kpair=null; + String kpairComment; + + public static final String AUTH_SCHEME="";//$NON-NLS-1$ + + public PreferencePage(){ + setDescription(Messages.CVSSSH2PreferencePage_18); + } + + @Override protected Control createContents(Composite parent){ - Composite container=new Composite(parent, SWT.NULL); - GridLayout layout=new GridLayout(); - container.setLayout(layout); - initializeDialogUnits(container); - - CTabFolder tabFolder=new CTabFolder(container, SWT.NONE); - tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); - - CTabItem tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_19); - tabItem.setControl(createGeneralPage(tabFolder)); - - tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_21); - tabItem.setControl(createKeyManagementPage(tabFolder)); - - tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_133); - tabItem.setControl(createHostKeyManagementPage(tabFolder)); - - tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_137); - tabItem.setControl(createPreferredAuthenticationPage(tabFolder)); - - tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_144); - tabItem.setControl(createPreferredKeyExchangePage(tabFolder)); - - tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_145); - tabItem.setControl(createPreferredMACPage(tabFolder)); - - tabItem=new CTabItem(tabFolder, SWT.NONE); - tabItem.setText(Messages.CVSSSH2PreferencePage_146); - tabItem.setControl(createPreferredSSHAgentPage(tabFolder)); - tabFolder.setSelection(0); - initControls(); - - Dialog.applyDialogFont(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - SSH2_PREFERENCE_PAGE_CONTEXT); - return container; - } - - private Control createGeneralPage(Composite parent){ - Composite group=new Composite(parent, SWT.NULL); - GridLayout layout=new GridLayout(); - layout.numColumns=3; - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - group.setLayout(layout); - GridData data=new GridData(); - data.horizontalAlignment=GridData.FILL; - group.setLayoutData(data); - - ssh2HomeLabel=new Label(group, SWT.NONE); - ssh2HomeLabel.setText(Messages.CVSSSH2PreferencePage_23); - - ssh2HomeText=new Text(group, SWT.SINGLE|SWT.BORDER); - ssh2HomeText.setFont(group.getFont()); - GridData gd=new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan=1; - ssh2HomeText.setLayoutData(gd); - - ssh2HomeBrowse=new Button(group, SWT.NULL); - ssh2HomeBrowse.setText(Messages.CVSSSH2PreferencePage_24); - gd=new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan=1; - ssh2HomeBrowse.setLayoutData(gd); - - createSpacer(group, 3); - - privateKeyLabel=new Label(group, SWT.NONE); - privateKeyLabel.setText(Messages.CVSSSH2PreferencePage_25); - - privateKeyText=new Text(group, SWT.SINGLE|SWT.BORDER); - privateKeyText.setFont(group.getFont()); - gd=new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan=1; - privateKeyText.setLayoutData(gd); - - privateKeyAdd=new Button(group, SWT.NULL); - privateKeyAdd.setText(Messages.CVSSSH2PreferencePage_26); - gd=new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan=1; - privateKeyAdd.setLayoutData(gd); - - ssh2HomeBrowse.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - String home=ssh2HomeText.getText(); - - if(!new File(home).exists()){ - while(true){ - int foo=home.lastIndexOf(java.io.File.separator, home.length()); - if(foo==-1) - break; - home=home.substring(0, foo); - if(new File(home).exists()) - break; - } - } - - DirectoryDialog dd=new DirectoryDialog(getShell()); - dd.setFilterPath(home); - dd.setMessage(Messages.CVSSSH2PreferencePage_27); - String dir=dd.open(); - if(dir==null){ // cancel - return; - } - ssh2HomeText.setText(dir); - } - }); - - privateKeyAdd.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - String home=ssh2HomeText.getText(); - - FileDialog fd=new FileDialog(getShell(), SWT.OPEN|SWT.MULTI); - fd.setFilterPath(home); - Object o=fd.open(); - if(o==null){ // cancel - return; - } - String[] files=fd.getFileNames(); - String keys=privateKeyText.getText(); - String dir=fd.getFilterPath(); - if(dir.equals(home)){ - dir="";} //$NON-NLS-1$ - else{ - dir+=java.io.File.separator; - } - - for(int i=0; i<files.length; i++){ - String foo=files[i]; - if(keys.length()!=0) - keys=keys+","; //$NON-NLS-1$ - keys=keys+dir+foo; - } - privateKeyText.setText(keys); - } - }); - - return group; - } - - private Control createKeyManagementPage(Composite parent){ - int columnSpan=3; - Composite group=new Composite(parent, SWT.NULL); - GridLayout layout=new GridLayout(); - layout.numColumns=3; - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - group.setLayout(layout); - GridData gd=new GridData(); - gd.horizontalAlignment=GridData.FILL; - group.setLayoutData(gd); - - keyGenerateDSA=new Button(group, SWT.NULL); - keyGenerateDSA.setText(Messages.CVSSSH2PreferencePage_131); - gd=new GridData(); - gd.horizontalSpan=1; - keyGenerateDSA.setLayoutData(gd); - - keyGenerateRSA=new Button(group, SWT.NULL); - keyGenerateRSA.setText(Messages.CVSSSH2PreferencePage_132); - gd=new GridData(); - gd.horizontalSpan=1; - keyGenerateRSA.setLayoutData(gd); - - keyLoad=new Button(group, SWT.NULL); - keyLoad.setText(Messages.CVSSSH2PreferencePage_128); - gd=new GridData(); - gd.horizontalSpan=1; - keyLoad.setLayoutData(gd); - - publicKeylabel=new Label(group, SWT.NONE); - publicKeylabel.setText(Messages.CVSSSH2PreferencePage_39); - gd=new GridData(); - gd.horizontalSpan=columnSpan; - publicKeylabel.setLayoutData(gd); - - publicKeyText=new Text(group, SWT.MULTI|SWT.BORDER|SWT.V_SCROLL|SWT.WRAP|SWT.LEFT_TO_RIGHT); - publicKeyText.setText(""); //$NON-NLS-1$ - publicKeyText.setEditable(false); - gd=new GridData(); - gd.horizontalSpan=columnSpan; - gd.horizontalAlignment=GridData.FILL; - gd.verticalAlignment=GridData.FILL; - gd.grabExcessHorizontalSpace=true; - gd.grabExcessVerticalSpace=true; - publicKeyText.setLayoutData(gd); - - keyFingerPrintLabel=new Label(group, SWT.NONE); - keyFingerPrintLabel.setText(Messages.CVSSSH2PreferencePage_41); - keyFingerPrintText=new Text(group, SWT.SINGLE|SWT.BORDER|SWT.LEFT_TO_RIGHT); - keyFingerPrintText.setFont(group.getFont()); - keyFingerPrintText.setEditable(false); - gd=new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan=2; - keyFingerPrintText.setLayoutData(gd); - - keyCommentLabel=new Label(group, SWT.NONE); - keyCommentLabel.setText(Messages.CVSSSH2PreferencePage_42); - keyCommentText=new Text(group, SWT.SINGLE|SWT.BORDER); - keyCommentText.setFont(group.getFont()); - gd=new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan=2; - keyCommentText.setLayoutData(gd); + Composite container=new Composite(parent, SWT.NULL); + GridLayout layout=new GridLayout(); + container.setLayout(layout); + initializeDialogUnits(container); + + CTabFolder tabFolder=new CTabFolder(container, SWT.NONE); + tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); + + CTabItem tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_19); + tabItem.setControl(createGeneralPage(tabFolder)); + + tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_21); + tabItem.setControl(createKeyManagementPage(tabFolder)); + + tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_133); + tabItem.setControl(createHostKeyManagementPage(tabFolder)); + + tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_137); + tabItem.setControl(createPreferredAuthenticationPage(tabFolder)); + + tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_144); + tabItem.setControl(createPreferredKeyExchangePage(tabFolder)); + + tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_145); + tabItem.setControl(createPreferredMACPage(tabFolder)); + + tabItem=new CTabItem(tabFolder, SWT.NONE); + tabItem.setText(Messages.CVSSSH2PreferencePage_146); + tabItem.setControl(createPreferredSSHAgentPage(tabFolder)); + tabFolder.setSelection(0); + initControls(); + + Dialog.applyDialogFont(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + SSH2_PREFERENCE_PAGE_CONTEXT); + return container; + } + + private Control createGeneralPage(Composite parent){ + Composite group=new Composite(parent, SWT.NULL); + GridLayout layout=new GridLayout(); + layout.numColumns=3; + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + group.setLayout(layout); + GridData data=new GridData(); + data.horizontalAlignment=GridData.FILL; + group.setLayoutData(data); + + ssh2HomeLabel=new Label(group, SWT.NONE); + ssh2HomeLabel.setText(Messages.CVSSSH2PreferencePage_23); + + ssh2HomeText=new Text(group, SWT.SINGLE|SWT.BORDER); + ssh2HomeText.setFont(group.getFont()); + GridData gd=new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan=1; + ssh2HomeText.setLayoutData(gd); + + ssh2HomeBrowse=new Button(group, SWT.NULL); + ssh2HomeBrowse.setText(Messages.CVSSSH2PreferencePage_24); + gd=new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan=1; + ssh2HomeBrowse.setLayoutData(gd); + + createSpacer(group, 3); + + privateKeyLabel=new Label(group, SWT.NONE); + privateKeyLabel.setText(Messages.CVSSSH2PreferencePage_25); + + privateKeyText=new Text(group, SWT.SINGLE|SWT.BORDER); + privateKeyText.setFont(group.getFont()); + gd=new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan=1; + privateKeyText.setLayoutData(gd); + + privateKeyAdd=new Button(group, SWT.NULL); + privateKeyAdd.setText(Messages.CVSSSH2PreferencePage_26); + gd=new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan=1; + privateKeyAdd.setLayoutData(gd); + + ssh2HomeBrowse.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + String home=ssh2HomeText.getText(); + + if(!new File(home).exists()){ + while(true){ + int foo=home.lastIndexOf(java.io.File.separator, home.length()); + if(foo==-1) + break; + home=home.substring(0, foo); + if(new File(home).exists()) + break; + } + } + + DirectoryDialog dd=new DirectoryDialog(getShell()); + dd.setFilterPath(home); + dd.setMessage(Messages.CVSSSH2PreferencePage_27); + String dir=dd.open(); + if(dir==null){ // cancel + return; + } + ssh2HomeText.setText(dir); + } + }); + + privateKeyAdd.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + String home=ssh2HomeText.getText(); + + FileDialog fd=new FileDialog(getShell(), SWT.OPEN|SWT.MULTI); + fd.setFilterPath(home); + Object o=fd.open(); + if(o==null){ // cancel + return; + } + String[] files=fd.getFileNames(); + String keys=privateKeyText.getText(); + String dir=fd.getFilterPath(); + if(dir.equals(home)){ + dir="";} //$NON-NLS-1$ + else{ + dir+=java.io.File.separator; + } + + for(int i=0; i<files.length; i++){ + String foo=files[i]; + if(keys.length()!=0) + keys=keys+","; //$NON-NLS-1$ + keys=keys+dir+foo; + } + privateKeyText.setText(keys); + } + }); + + return group; + } + + private Control createKeyManagementPage(Composite parent){ + int columnSpan=3; + Composite group=new Composite(parent, SWT.NULL); + GridLayout layout=new GridLayout(); + layout.numColumns=3; + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + group.setLayout(layout); + GridData gd=new GridData(); + gd.horizontalAlignment=GridData.FILL; + group.setLayoutData(gd); + + keyGenerateDSA=new Button(group, SWT.NULL); + keyGenerateDSA.setText(Messages.CVSSSH2PreferencePage_131); + gd=new GridData(); + gd.horizontalSpan=1; + keyGenerateDSA.setLayoutData(gd); + + keyGenerateRSA=new Button(group, SWT.NULL); + keyGenerateRSA.setText(Messages.CVSSSH2PreferencePage_132); + gd=new GridData(); + gd.horizontalSpan=1; + keyGenerateRSA.setLayoutData(gd); + + keyLoad=new Button(group, SWT.NULL); + keyLoad.setText(Messages.CVSSSH2PreferencePage_128); + gd=new GridData(); + gd.horizontalSpan=1; + keyLoad.setLayoutData(gd); + + publicKeylabel=new Label(group, SWT.NONE); + publicKeylabel.setText(Messages.CVSSSH2PreferencePage_39); + gd=new GridData(); + gd.horizontalSpan=columnSpan; + publicKeylabel.setLayoutData(gd); + + publicKeyText=new Text(group, SWT.MULTI|SWT.BORDER|SWT.V_SCROLL|SWT.WRAP|SWT.LEFT_TO_RIGHT); + publicKeyText.setText(""); //$NON-NLS-1$ + publicKeyText.setEditable(false); + gd=new GridData(); + gd.horizontalSpan=columnSpan; + gd.horizontalAlignment=GridData.FILL; + gd.verticalAlignment=GridData.FILL; + gd.grabExcessHorizontalSpace=true; + gd.grabExcessVerticalSpace=true; + publicKeyText.setLayoutData(gd); + + keyFingerPrintLabel=new Label(group, SWT.NONE); + keyFingerPrintLabel.setText(Messages.CVSSSH2PreferencePage_41); + keyFingerPrintText=new Text(group, SWT.SINGLE|SWT.BORDER|SWT.LEFT_TO_RIGHT); + keyFingerPrintText.setFont(group.getFont()); + keyFingerPrintText.setEditable(false); + gd=new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan=2; + keyFingerPrintText.setLayoutData(gd); + + keyCommentLabel=new Label(group, SWT.NONE); + keyCommentLabel.setText(Messages.CVSSSH2PreferencePage_42); + keyCommentText=new Text(group, SWT.SINGLE|SWT.BORDER); + keyCommentText.setFont(group.getFont()); + gd=new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan=2; + keyCommentText.setLayoutData(gd); keyCommentText.addModifyListener(e -> { - if(kpair==null) - return; - try{ - ByteArrayOutputStream out=new ByteArrayOutputStream(); - kpairComment = keyCommentText.getText(); - kpair.writePublicKey(out, kpairComment); - out.close(); - publicKeyText.setText(out.toString()); - } - catch(IOException ee){ - // Ignore - } + if(kpair==null) + return; + try{ + ByteArrayOutputStream out=new ByteArrayOutputStream(); + kpairComment = keyCommentText.getText(); + kpair.writePublicKey(out, kpairComment); + out.close(); + publicKeyText.setText(out.toString()); + } + catch(IOException ee){ + // Ignore + } }); - keyPassphrase1Label=new Label(group, SWT.NONE); - keyPassphrase1Label.setText(Messages.CVSSSH2PreferencePage_43); - keyPassphrase1Text=new Text(group, SWT.SINGLE|SWT.BORDER); - keyPassphrase1Text.setFont(group.getFont()); - keyPassphrase1Text.setEchoChar('*'); - gd=new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan=2; - keyPassphrase1Text.setLayoutData(gd); - - keyPassphrase2Label=new Label(group, SWT.NONE); - keyPassphrase2Label.setText(Messages.CVSSSH2PreferencePage_44); - keyPassphrase2Text=new Text(group, SWT.SINGLE|SWT.BORDER); - keyPassphrase2Text.setFont(group.getFont()); - keyPassphrase2Text.setEchoChar('*'); - gd=new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan=2; - keyPassphrase2Text.setLayoutData(gd); + keyPassphrase1Label=new Label(group, SWT.NONE); + keyPassphrase1Label.setText(Messages.CVSSSH2PreferencePage_43); + keyPassphrase1Text=new Text(group, SWT.SINGLE|SWT.BORDER); + keyPassphrase1Text.setFont(group.getFont()); + keyPassphrase1Text.setEchoChar('*'); + gd=new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan=2; + keyPassphrase1Text.setLayoutData(gd); + + keyPassphrase2Label=new Label(group, SWT.NONE); + keyPassphrase2Label.setText(Messages.CVSSSH2PreferencePage_44); + keyPassphrase2Text=new Text(group, SWT.SINGLE|SWT.BORDER); + keyPassphrase2Text.setFont(group.getFont()); + keyPassphrase2Text.setEchoChar('*'); + gd=new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan=2; + keyPassphrase2Text.setLayoutData(gd); keyPassphrase1Text.addModifyListener(e -> { - String pass1=keyPassphrase1Text.getText(); - String pass2=keyPassphrase2Text.getText(); - if(kpair!=null&&pass1.equals(pass2)){ - saveKeyPair.setEnabled(true); - } - else{ - saveKeyPair.setEnabled(false); - } - if(pass2.length()==0){ - setErrorMessage(null); - return; - } - if(pass1.equals(pass2)){ - setErrorMessage(null); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_48); - } + String pass1=keyPassphrase1Text.getText(); + String pass2=keyPassphrase2Text.getText(); + if(kpair!=null&&pass1.equals(pass2)){ + saveKeyPair.setEnabled(true); + } + else{ + saveKeyPair.setEnabled(false); + } + if(pass2.length()==0){ + setErrorMessage(null); + return; + } + if(pass1.equals(pass2)){ + setErrorMessage(null); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_48); + } }); keyPassphrase2Text.addModifyListener(e -> { - String pass1=keyPassphrase1Text.getText(); - String pass2=keyPassphrase2Text.getText(); - if(kpair!=null&&pass1.equals(pass2)){ - saveKeyPair.setEnabled(true); - } - else{ - saveKeyPair.setEnabled(false); - } - if(pass2.length()<pass1.length()){ - if(pass1.startsWith(pass2)){ - setErrorMessage(null); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_48); - } - return; - } - if(pass1.equals(pass2)){ - setErrorMessage(null); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_48); - } + String pass1=keyPassphrase1Text.getText(); + String pass2=keyPassphrase2Text.getText(); + if(kpair!=null&&pass1.equals(pass2)){ + saveKeyPair.setEnabled(true); + } + else{ + saveKeyPair.setEnabled(false); + } + if(pass2.length()<pass1.length()){ + if(pass1.startsWith(pass2)){ + setErrorMessage(null); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_48); + } + return; + } + if(pass1.equals(pass2)){ + setErrorMessage(null); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_48); + } }); - keyPassphrase2Text.addFocusListener(new FocusListener(){ - @Override - public void focusGained(FocusEvent e){ - String pass1=keyPassphrase1Text.getText(); - String pass2=keyPassphrase2Text.getText(); - if(pass2.length()<pass1.length()){ - if(pass1.startsWith(pass2)){ - setErrorMessage(null); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_48); - } - return; - } - if(pass1.equals(pass2)){ - setErrorMessage(null); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_48); - } - } - - @Override - public void focusLost(FocusEvent e){ - String pass1=keyPassphrase1Text.getText(); - String pass2=keyPassphrase2Text.getText(); - if(pass1.equals(pass2)){ - setErrorMessage(null); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_48); - } - } - }); - - Composite buttons=new Composite(group, SWT.NONE); - layout=new GridLayout(2, true); - layout.marginWidth=0; - layout.marginHeight=0; - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - buttons.setLayout(layout); - gd=new GridData(GridData.HORIZONTAL_ALIGN_END); - gd.horizontalSpan=columnSpan; - buttons.setLayoutData(gd); - - keyExport=new Button(buttons, SWT.NULL); - keyExport.setText(Messages.CVSSSH2PreferencePage_105); - gd=new GridData(GridData.FILL_BOTH); - keyExport.setLayoutData(gd); - - saveKeyPair=new Button(buttons, SWT.NULL); - saveKeyPair.setText(Messages.CVSSSH2PreferencePage_45); - gd=new GridData(GridData.FILL_BOTH); - saveKeyPair.setLayoutData(gd); - - SelectionAdapter keygenadapter=new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - boolean ok=true; - String _type=""; //$NON-NLS-1$ - - try{ - int type=0; - if(e.widget==keyGenerateDSA){ - type=KeyPair.DSA; - _type=IConstants.DSA; - } - else if(e.widget==keyGenerateRSA){ - type=KeyPair.RSA; - _type=IConstants.RSA; - } - else{ - return; - } - - final KeyPair[] _kpair=new KeyPair[1]; - final int __type=type; - final JSchException[] _e=new JSchException[1]; + keyPassphrase2Text.addFocusListener(new FocusListener(){ + @Override + public void focusGained(FocusEvent e){ + String pass1=keyPassphrase1Text.getText(); + String pass2=keyPassphrase2Text.getText(); + if(pass2.length()<pass1.length()){ + if(pass1.startsWith(pass2)){ + setErrorMessage(null); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_48); + } + return; + } + if(pass1.equals(pass2)){ + setErrorMessage(null); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_48); + } + } + + @Override + public void focusLost(FocusEvent e){ + String pass1=keyPassphrase1Text.getText(); + String pass2=keyPassphrase2Text.getText(); + if(pass1.equals(pass2)){ + setErrorMessage(null); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_48); + } + } + }); + + Composite buttons=new Composite(group, SWT.NONE); + layout=new GridLayout(2, true); + layout.marginWidth=0; + layout.marginHeight=0; + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + buttons.setLayout(layout); + gd=new GridData(GridData.HORIZONTAL_ALIGN_END); + gd.horizontalSpan=columnSpan; + buttons.setLayoutData(gd); + + keyExport=new Button(buttons, SWT.NULL); + keyExport.setText(Messages.CVSSSH2PreferencePage_105); + gd=new GridData(GridData.FILL_BOTH); + keyExport.setLayoutData(gd); + + saveKeyPair=new Button(buttons, SWT.NULL); + saveKeyPair.setText(Messages.CVSSSH2PreferencePage_45); + gd=new GridData(GridData.FILL_BOTH); + saveKeyPair.setLayoutData(gd); + + SelectionAdapter keygenadapter=new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + boolean ok=true; + String _type=""; //$NON-NLS-1$ + + try{ + int type=0; + if(e.widget==keyGenerateDSA){ + type=KeyPair.DSA; + _type=IConstants.DSA; + } + else if(e.widget==keyGenerateRSA){ + type=KeyPair.RSA; + _type=IConstants.RSA; + } + else{ + return; + } + + final KeyPair[] _kpair=new KeyPair[1]; + final int __type=type; + final JSchException[] _e=new JSchException[1]; BusyIndicator.showWhile(getShell().getDisplay(), () -> { try { _kpair[0] = KeyPair.genKeyPair(getJSch(), __type); @@ -503,148 +503,148 @@ protected Control createContents(Composite parent){ _e[0] = e1; } }); - if(_e[0]!=null){ - throw _e[0]; - } - kpair=_kpair[0]; - - ByteArrayOutputStream out=new ByteArrayOutputStream(); - kpairComment=_type+"-1024"; //$NON-NLS-1$ - kpair.writePublicKey(out, kpairComment); - out.close(); - publicKeyText.setText(out.toString()); - keyFingerPrintText.setText(kpair.getFingerPrint()); - keyCommentText.setText(kpairComment); - keyPassphrase1Text.setText(""); //$NON-NLS-1$ - keyPassphrase2Text.setText(""); //$NON-NLS-1$ - updateControls(); - } - catch(IOException ee){ - ok=false; - } - catch(JSchException ee){ - ok=false; - } - if(!ok){ - MessageDialog.openError(getShell(), - Messages.CVSSSH2PreferencePage_error, - Messages.CVSSSH2PreferencePage_47); - } - } - }; - keyGenerateDSA.addSelectionListener(keygenadapter); - keyGenerateRSA.addSelectionListener(keygenadapter); - - keyLoad.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - boolean ok=true; - String home=ssh2HomeText.getText(); - FileDialog fd=new FileDialog(getShell(), SWT.OPEN); - fd.setFilterPath(home); - Object o=fd.open(); - if(o==null){ // cancel - return; - } - String pkey=fd.getFileName(); - String pkeyab=(new File(fd.getFilterPath(), pkey)).getAbsolutePath(); - try{ - KeyPair _kpair=KeyPair.load(getJSch(), pkeyab); - PassphrasePrompt prompt=null; - while(_kpair.isEncrypted()){ - if(prompt==null){ - prompt=new PassphrasePrompt(NLS.bind( - Messages.CVSSSH2PreferencePage_126, new String[] {pkey})); - } - Display.getDefault().syncExec(prompt); - String passphrase=prompt.getPassphrase(); - if(passphrase==null) - break; - if(_kpair.decrypt(passphrase)){ - break; - } - MessageDialog.openError(getShell(), - Messages.CVSSSH2PreferencePage_error, NLS.bind( - Messages.CVSSSH2PreferencePage_129, new String[] {pkey})); - } - if(_kpair.isEncrypted()){ - return; - } - kpair=_kpair; - String _type=(kpair.getKeyType()==KeyPair.DSA) ? IConstants.DSA - : IConstants.RSA; - kpairComment=_type+"-1024"; //$NON-NLS-1$ - - // TODO Bug 351094 The comment should be from kpair object, - // but the JSch API does not provided such a method. - // In the version 0.1.45, JSch will support such a method, - // and the following code should be replaced with it at that time. - java.io.FileInputStream fis=null; - try{ - java.io.File f=new java.io.File(pkeyab+".pub"); //$NON-NLS-1$ - int i=0; - fis=new java.io.FileInputStream(f); - byte[] buf=new byte[(int)f.length()]; - while(i<buf.length){ - int j=fis.read(buf, i, buf.length-i); - if(j<=0) - break; - i+=j; - } - String pubkey=new String(buf); - if(pubkey.indexOf(' ')>0 - &&pubkey.indexOf(' ', pubkey.indexOf(' ')+1)>0){ - int j=pubkey.indexOf(' ', pubkey.indexOf(' ')+1)+1; - kpairComment=pubkey.substring(j); - if(kpairComment.indexOf('\n')>0){ - kpairComment=kpairComment.substring(0, - kpairComment.indexOf('\n')); - } - } - } - catch(IOException ioe){ - // ignore if public-key does not exist. - } - finally{ - if(fis!=null) - fis.close(); - } - - ByteArrayOutputStream out=new ByteArrayOutputStream(); - - kpair.writePublicKey(out, kpairComment); - out.close(); - publicKeyText.setText(out.toString()); - keyFingerPrintText.setText(kpair.getFingerPrint()); - keyCommentText.setText(kpairComment); - keyPassphrase1Text.setText(""); //$NON-NLS-1$ - keyPassphrase2Text.setText(""); //$NON-NLS-1$ - updateControls(); - } - catch(IOException ee){ - ok=false; - } - catch(JSchException ee){ - ok=false; - } - if(!ok){ - MessageDialog.openError(getShell(), - Messages.CVSSSH2PreferencePage_error, - Messages.CVSSSH2PreferencePage_130); - } - } - }); - - keyExport.addSelectionListener(new SelectionAdapter(){ - @Override - public void widgetSelected(SelectionEvent e){ - if(kpair==null) - return; + if(_e[0]!=null){ + throw _e[0]; + } + kpair=_kpair[0]; + + ByteArrayOutputStream out=new ByteArrayOutputStream(); + kpairComment=_type+"-1024"; //$NON-NLS-1$ + kpair.writePublicKey(out, kpairComment); + out.close(); + publicKeyText.setText(out.toString()); + keyFingerPrintText.setText(kpair.getFingerPrint()); + keyCommentText.setText(kpairComment); + keyPassphrase1Text.setText(""); //$NON-NLS-1$ + keyPassphrase2Text.setText(""); //$NON-NLS-1$ + updateControls(); + } + catch(IOException ee){ + ok=false; + } + catch(JSchException ee){ + ok=false; + } + if(!ok){ + MessageDialog.openError(getShell(), + Messages.CVSSSH2PreferencePage_error, + Messages.CVSSSH2PreferencePage_47); + } + } + }; + keyGenerateDSA.addSelectionListener(keygenadapter); + keyGenerateRSA.addSelectionListener(keygenadapter); + + keyLoad.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + boolean ok=true; + String home=ssh2HomeText.getText(); + FileDialog fd=new FileDialog(getShell(), SWT.OPEN); + fd.setFilterPath(home); + Object o=fd.open(); + if(o==null){ // cancel + return; + } + String pkey=fd.getFileName(); + String pkeyab=(new File(fd.getFilterPath(), pkey)).getAbsolutePath(); + try{ + KeyPair _kpair=KeyPair.load(getJSch(), pkeyab); + PassphrasePrompt prompt=null; + while(_kpair.isEncrypted()){ + if(prompt==null){ + prompt=new PassphrasePrompt(NLS.bind( + Messages.CVSSSH2PreferencePage_126, new String[] {pkey})); + } + Display.getDefault().syncExec(prompt); + String passphrase=prompt.getPassphrase(); + if(passphrase==null) + break; + if(_kpair.decrypt(passphrase)){ + break; + } + MessageDialog.openError(getShell(), + Messages.CVSSSH2PreferencePage_error, NLS.bind( + Messages.CVSSSH2PreferencePage_129, new String[] {pkey})); + } + if(_kpair.isEncrypted()){ + return; + } + kpair=_kpair; + String _type=(kpair.getKeyType()==KeyPair.DSA) ? IConstants.DSA + : IConstants.RSA; + kpairComment=_type+"-1024"; //$NON-NLS-1$ + + // TODO Bug 351094 The comment should be from kpair object, + // but the JSch API does not provided such a method. + // In the version 0.1.45, JSch will support such a method, + // and the following code should be replaced with it at that time. + java.io.FileInputStream fis=null; + try{ + java.io.File f=new java.io.File(pkeyab+".pub"); //$NON-NLS-1$ + int i=0; + fis=new java.io.FileInputStream(f); + byte[] buf=new byte[(int)f.length()]; + while(i<buf.length){ + int j=fis.read(buf, i, buf.length-i); + if(j<=0) + break; + i+=j; + } + String pubkey=new String(buf); + if(pubkey.indexOf(' ')>0 + &&pubkey.indexOf(' ', pubkey.indexOf(' ')+1)>0){ + int j=pubkey.indexOf(' ', pubkey.indexOf(' ')+1)+1; + kpairComment=pubkey.substring(j); + if(kpairComment.indexOf('\n')>0){ + kpairComment=kpairComment.substring(0, + kpairComment.indexOf('\n')); + } + } + } + catch(IOException ioe){ + // ignore if public-key does not exist. + } + finally{ + if(fis!=null) + fis.close(); + } + + ByteArrayOutputStream out=new ByteArrayOutputStream(); + + kpair.writePublicKey(out, kpairComment); + out.close(); + publicKeyText.setText(out.toString()); + keyFingerPrintText.setText(kpair.getFingerPrint()); + keyCommentText.setText(kpairComment); + keyPassphrase1Text.setText(""); //$NON-NLS-1$ + keyPassphrase2Text.setText(""); //$NON-NLS-1$ + updateControls(); + } + catch(IOException ee){ + ok=false; + } + catch(JSchException ee){ + ok=false; + } + if(!ok){ + MessageDialog.openError(getShell(), + Messages.CVSSSH2PreferencePage_error, + Messages.CVSSSH2PreferencePage_130); + } + } + }); + + keyExport.addSelectionListener(new SelectionAdapter(){ + @Override + public void widgetSelected(SelectionEvent e){ + if(kpair==null) + return; - setErrorMessage(null); + setErrorMessage(null); - final String[] target=new String[1]; - final String title=Messages.CVSSSH2PreferencePage_106; + final String[] target=new String[1]; + final String title=Messages.CVSSSH2PreferencePage_106; final String message = Messages.CVSSSH2PreferencePage_107; Display.getDefault().syncExec(() -> { Display display = Display.getCurrent(); @@ -657,1043 +657,1043 @@ protected Control createContents(Composite parent){ if (target[0] == null) { return; } - String user=""; //$NON-NLS-1$ - String host=""; //$NON-NLS-1$ - int port=22; - - if(target[0].indexOf('@')>0){ - user=target[0].substring(0, target[0].indexOf('@')); - host=target[0].substring(target[0].indexOf('@')+1); - } - if(host.indexOf(':')>0){ - try{ - port=Integer.parseInt(host.substring(host.indexOf(':')+1)); - } - catch(NumberFormatException ee){ - port=-1; - } - host=host.substring(0, host.indexOf(':')); - } - - if(user.length()==0||host.length()==0||port==-1){ - setErrorMessage(NLS.bind(Messages.CVSSSH2PreferencePage_108, - new String[] {target[0]})); - return; - } - - String options=""; //$NON-NLS-1$ - try{ - ByteArrayOutputStream bos=new ByteArrayOutputStream(); - if(options.length()!=0){ - try{ - bos.write((options+" ").getBytes());} //$NON-NLS-1$ - catch(IOException eeee){ - // Ignore - } - } - kpair.writePublicKey(bos, kpairComment); - bos.close(); - export_via_sftp(user, host, port, /* ".ssh/authorized_keys", //$NON-NLS-1$ */ - bos.toByteArray()); - } - catch(IOException ee){ - // Ignore - } - catch(JSchException ee){ - setErrorMessage(Messages.CVSSSH2PreferencePage_111); - } - } - }); - - saveKeyPair.addSelectionListener(new SelectionAdapter(){ - @Override + String user=""; //$NON-NLS-1$ + String host=""; //$NON-NLS-1$ + int port=22; + + if(target[0].indexOf('@')>0){ + user=target[0].substring(0, target[0].indexOf('@')); + host=target[0].substring(target[0].indexOf('@')+1); + } + if(host.indexOf(':')>0){ + try{ + port=Integer.parseInt(host.substring(host.indexOf(':')+1)); + } + catch(NumberFormatException ee){ + port=-1; + } + host=host.substring(0, host.indexOf(':')); + } + + if(user.length()==0||host.length()==0||port==-1){ + setErrorMessage(NLS.bind(Messages.CVSSSH2PreferencePage_108, + new String[] {target[0]})); + return; + } + + String options=""; //$NON-NLS-1$ + try{ + ByteArrayOutputStream bos=new ByteArrayOutputStream(); + if(options.length()!=0){ + try{ + bos.write((options+" ").getBytes());} //$NON-NLS-1$ + catch(IOException eeee){ + // Ignore + } + } + kpair.writePublicKey(bos, kpairComment); + bos.close(); + export_via_sftp(user, host, port, /* ".ssh/authorized_keys", //$NON-NLS-1$ */ + bos.toByteArray()); + } + catch(IOException ee){ + // Ignore + } + catch(JSchException ee){ + setErrorMessage(Messages.CVSSSH2PreferencePage_111); + } + } + }); + + saveKeyPair.addSelectionListener(new SelectionAdapter(){ + @Override public void widgetSelected(SelectionEvent e){ - if(kpair==null) - return; - - String pass=keyPassphrase1Text.getText(); - /* - * if(!pass.equals(keyPassphrase2Text.getText())){ - * setErrorMessage(Policy.bind("CVSSSH2PreferencePage.48")); - * //$NON-NLS-1$ return; } - */ - if(pass.length()==0){ - if(!MessageDialog.openConfirm(getShell(), - Messages.CVSSSH2PreferencePage_confirmation, - Messages.CVSSSH2PreferencePage_49)){ - return; - } - } - - kpair.setPassphrase(pass); - - String home=ssh2HomeText.getText(); - - File _home=new File(home); - - if(!_home.exists()){ - if(!MessageDialog.openConfirm(getShell(), - Messages.CVSSSH2PreferencePage_confirmation, NLS.bind( - Messages.CVSSSH2PreferencePage_50, new String[] {home}))){ - return; - } - if(!_home.mkdirs()){ - setErrorMessage(Messages.CVSSSH2PreferencePage_100+home); - return; - } - } - - FileDialog fd=new FileDialog(getShell(), SWT.SAVE); - fd.setFilterPath(home); - String file=(kpair.getKeyType()==KeyPair.RSA) ? "id_rsa" : "id_dsa"; //$NON-NLS-1$ //$NON-NLS-2$ - fd.setFileName(file); - file=fd.open(); - if(file==null){ // cancel - return; - } - - if(new File(file).exists()){ - if(!MessageDialog.openConfirm(getShell(), - Messages.CVSSSH2PreferencePage_confirmation, // - NLS.bind(Messages.CVSSSH2PreferencePage_53, new String[] {file}))){ - return; - } - } - - boolean ok=true; - try{ - kpair.writePrivateKey(file); - kpair.writePublicKey(file+".pub", kpairComment); //$NON-NLS-1$ - } - catch(Exception ee){ - ok=false; - } - - if(ok){ - MessageDialog.openInformation(getShell(), - Messages.CVSSSH2PreferencePage_information, - Messages.CVSSSH2PreferencePage_55+"\n"+ //$NON-NLS-1$ - Messages.CVSSSH2PreferencePage_57+file+"\n"+ //$NON-NLS-1$ - Messages.CVSSSH2PreferencePage_59+file+".pub"); //$NON-NLS-1$ - } - else{ - return; - } - - // The generated key should be added to privateKeyText. - - String dir=fd.getFilterPath(); - File mypkey=new java.io.File(dir, fd.getFileName()); - String pkeys=privateKeyText.getText(); - - // Check if the generated key has been included in pkeys? - String[] pkeysa=pkeys.split(","); //$NON-NLS-1$ - for(int i=0; i<pkeysa.length; i++){ - File pkey=new java.io.File(pkeysa[i]); - if(!pkey.isAbsolute()){ - pkey=new java.io.File(home, pkeysa[i]); - } - if(pkey.equals(mypkey)) - return; - } - - if(dir.equals(home)){ - dir="";} //$NON-NLS-1$ - else{ - dir+=java.io.File.separator; - } - if(pkeys.length()>0) - pkeys+=","; //$NON-NLS-1$ - pkeys=pkeys+dir+fd.getFileName(); - privateKeyText.setText(pkeys); - } - }); - - return group; - } - - private TableViewer viewer; - private Button removeHostKeyButton; - - Table preferedAuthMethodTable; - Table preferedSSHAgentTable; - Table preferedKeyExchangeMethodTable; - Table preferedMACMethodTable; - - Button up; - Button down; - Button kex_up; - Button kex_down; - Button mac_up; - Button mac_down; - - class TableLabelProvider extends LabelProvider implements ITableLabelProvider{ - @Override - public String getColumnText(Object element, int columnIndex){ - HostKey entry=(HostKey)element; - switch(columnIndex){ - case 0: - return entry.getHost(); - case 1: - return entry.getType(); - case 2: - return entry.getFingerPrint(getJSch()); - default: - return null; - } - } - - @Override - public Image getColumnImage(Object element, int columnIndex){ - return null; - } - } - - private Control createHostKeyManagementPage(Composite parent){ - Composite group=new Composite(parent, SWT.NULL); - GridLayout layout=new GridLayout(); - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.numColumns=2; - group.setLayout(layout); - GridData gd=new GridData(); - gd.horizontalAlignment=GridData.FILL; - gd.verticalAlignment=GridData.FILL; - group.setLayoutData(gd); - - Label label=new Label(group, SWT.NONE); - label.setText(Messages.CVSSSH2PreferencePage_139); - gd=new GridData(); - gd.horizontalSpan=2; - label.setLayoutData(gd); - - viewer=new TableViewer(group, SWT.MULTI|SWT.FULL_SELECTION|SWT.H_SCROLL - |SWT.V_SCROLL|SWT.BORDER); - Table table=viewer.getTable(); - new TableEditor(table); - table.setHeaderVisible(true); - table.setLinesVisible(true); - gd=new GridData(GridData.FILL_BOTH); - gd.widthHint=convertWidthInCharsToPixels(30); - /* - * The hardcoded hint does not look elegant, but in reality it does not make - * anything bound to this 100-pixel value, because in any case the tree on - * the left is taller and that's what really determines the height. - */ - gd.heightHint=100; - table.setLayoutData(gd); + if(kpair==null) + return; + + String pass=keyPassphrase1Text.getText(); + /* + * if(!pass.equals(keyPassphrase2Text.getText())){ + * setErrorMessage(Policy.bind("CVSSSH2PreferencePage.48")); + * //$NON-NLS-1$ return; } + */ + if(pass.length()==0){ + if(!MessageDialog.openConfirm(getShell(), + Messages.CVSSSH2PreferencePage_confirmation, + Messages.CVSSSH2PreferencePage_49)){ + return; + } + } + + kpair.setPassphrase(pass); + + String home=ssh2HomeText.getText(); + + File _home=new File(home); + + if(!_home.exists()){ + if(!MessageDialog.openConfirm(getShell(), + Messages.CVSSSH2PreferencePage_confirmation, NLS.bind( + Messages.CVSSSH2PreferencePage_50, new String[] {home}))){ + return; + } + if(!_home.mkdirs()){ + setErrorMessage(Messages.CVSSSH2PreferencePage_100+home); + return; + } + } + + FileDialog fd=new FileDialog(getShell(), SWT.SAVE); + fd.setFilterPath(home); + String file=(kpair.getKeyType()==KeyPair.RSA) ? "id_rsa" : "id_dsa"; //$NON-NLS-1$ //$NON-NLS-2$ + fd.setFileName(file); + file=fd.open(); + if(file==null){ // cancel + return; + } + + if(new File(file).exists()){ + if(!MessageDialog.openConfirm(getShell(), + Messages.CVSSSH2PreferencePage_confirmation, // + NLS.bind(Messages.CVSSSH2PreferencePage_53, new String[] {file}))){ + return; + } + } + + boolean ok=true; + try{ + kpair.writePrivateKey(file); + kpair.writePublicKey(file+".pub", kpairComment); //$NON-NLS-1$ + } + catch(Exception ee){ + ok=false; + } + + if(ok){ + MessageDialog.openInformation(getShell(), + Messages.CVSSSH2PreferencePage_information, + Messages.CVSSSH2PreferencePage_55+"\n"+ //$NON-NLS-1$ + Messages.CVSSSH2PreferencePage_57+file+"\n"+ //$NON-NLS-1$ + Messages.CVSSSH2PreferencePage_59+file+".pub"); //$NON-NLS-1$ + } + else{ + return; + } + + // The generated key should be added to privateKeyText. + + String dir=fd.getFilterPath(); + File mypkey=new java.io.File(dir, fd.getFileName()); + String pkeys=privateKeyText.getText(); + + // Check if the generated key has been included in pkeys? + String[] pkeysa=pkeys.split(","); //$NON-NLS-1$ + for(int i=0; i<pkeysa.length; i++){ + File pkey=new java.io.File(pkeysa[i]); + if(!pkey.isAbsolute()){ + pkey=new java.io.File(home, pkeysa[i]); + } + if(pkey.equals(mypkey)) + return; + } + + if(dir.equals(home)){ + dir="";} //$NON-NLS-1$ + else{ + dir+=java.io.File.separator; + } + if(pkeys.length()>0) + pkeys+=","; //$NON-NLS-1$ + pkeys=pkeys+dir+fd.getFileName(); + privateKeyText.setText(pkeys); + } + }); + + return group; + } + + private TableViewer viewer; + private Button removeHostKeyButton; + + Table preferedAuthMethodTable; + Table preferedSSHAgentTable; + Table preferedKeyExchangeMethodTable; + Table preferedMACMethodTable; + + Button up; + Button down; + Button kex_up; + Button kex_down; + Button mac_up; + Button mac_down; + + class TableLabelProvider extends LabelProvider implements ITableLabelProvider{ + @Override + public String getColumnText(Object element, int columnIndex){ + HostKey entry=(HostKey)element; + switch(columnIndex){ + case 0: + return entry.getHost(); + case 1: + return entry.getType(); + case 2: + return entry.getFingerPrint(getJSch()); + default: + return null; + } + } + + @Override + public Image getColumnImage(Object element, int columnIndex){ + return null; + } + } + + private Control createHostKeyManagementPage(Composite parent){ + Composite group=new Composite(parent, SWT.NULL); + GridLayout layout=new GridLayout(); + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.numColumns=2; + group.setLayout(layout); + GridData gd=new GridData(); + gd.horizontalAlignment=GridData.FILL; + gd.verticalAlignment=GridData.FILL; + group.setLayoutData(gd); + + Label label=new Label(group, SWT.NONE); + label.setText(Messages.CVSSSH2PreferencePage_139); + gd=new GridData(); + gd.horizontalSpan=2; + label.setLayoutData(gd); + + viewer=new TableViewer(group, SWT.MULTI|SWT.FULL_SELECTION|SWT.H_SCROLL + |SWT.V_SCROLL|SWT.BORDER); + Table table=viewer.getTable(); + new TableEditor(table); + table.setHeaderVisible(true); + table.setLinesVisible(true); + gd=new GridData(GridData.FILL_BOTH); + gd.widthHint=convertWidthInCharsToPixels(30); + /* + * The hardcoded hint does not look elegant, but in reality it does not make + * anything bound to this 100-pixel value, because in any case the tree on + * the left is taller and that's what really determines the height. + */ + gd.heightHint=100; + table.setLayoutData(gd); table.addListener(SWT.Selection, e -> handleSelection()); - // Create the table columns - new TableColumn(table, SWT.NULL); - new TableColumn(table, SWT.NULL); - new TableColumn(table, SWT.NULL); - TableColumn[] columns=table.getColumns(); - columns[0].setText(Messages.CVSSSH2PreferencePage_134); - columns[1].setText(Messages.CVSSSH2PreferencePage_135); - columns[2].setText(Messages.CVSSSH2PreferencePage_136); - viewer.setColumnProperties(new String[] { - Messages.CVSSSH2PreferencePage_134, // - Messages.CVSSSH2PreferencePage_135, // - Messages.CVSSSH2PreferencePage_136}); - viewer.setLabelProvider(new TableLabelProvider()); - viewer.setContentProvider(new IStructuredContentProvider(){ - @Override - public void dispose(){ - // nothing to do - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput){ - // nothing to do - } - - @Override - public Object[] getElements(Object inputElement){ - if(inputElement==null) - return null; - return (Object[])inputElement; - } - }); - TableLayout tl=new TableLayout(); - tl.addColumnData(new ColumnWeightData(30)); - tl.addColumnData(new ColumnWeightData(20)); - tl.addColumnData(new ColumnWeightData(70)); - table.setLayout(tl); - - Composite buttons=new Composite(group, SWT.NULL); - buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); - layout=new GridLayout(); - layout.marginHeight=0; - layout.marginWidth=0; - buttons.setLayout(layout); - - removeHostKeyButton=new Button(buttons, SWT.PUSH); - removeHostKeyButton.setText(Messages.CVSSSH2PreferencePage_138); - int buttonWidth=SWTUtils - .calculateControlSize(SWTUtils.createDialogPixelConverter(parent), - new Button[] {removeHostKeyButton}); - removeHostKeyButton.setLayoutData(SWTUtils.createGridData(buttonWidth, - SWT.DEFAULT, SWT.END, SWT.CENTER, false, false)); - removeHostKeyButton.setEnabled(false); + // Create the table columns + new TableColumn(table, SWT.NULL); + new TableColumn(table, SWT.NULL); + new TableColumn(table, SWT.NULL); + TableColumn[] columns=table.getColumns(); + columns[0].setText(Messages.CVSSSH2PreferencePage_134); + columns[1].setText(Messages.CVSSSH2PreferencePage_135); + columns[2].setText(Messages.CVSSSH2PreferencePage_136); + viewer.setColumnProperties(new String[] { + Messages.CVSSSH2PreferencePage_134, // + Messages.CVSSSH2PreferencePage_135, // + Messages.CVSSSH2PreferencePage_136}); + viewer.setLabelProvider(new TableLabelProvider()); + viewer.setContentProvider(new IStructuredContentProvider(){ + @Override + public void dispose(){ + // nothing to do + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput){ + // nothing to do + } + + @Override + public Object[] getElements(Object inputElement){ + if(inputElement==null) + return null; + return (Object[])inputElement; + } + }); + TableLayout tl=new TableLayout(); + tl.addColumnData(new ColumnWeightData(30)); + tl.addColumnData(new ColumnWeightData(20)); + tl.addColumnData(new ColumnWeightData(70)); + table.setLayout(tl); + + Composite buttons=new Composite(group, SWT.NULL); + buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); + layout=new GridLayout(); + layout.marginHeight=0; + layout.marginWidth=0; + buttons.setLayout(layout); + + removeHostKeyButton=new Button(buttons, SWT.PUSH); + removeHostKeyButton.setText(Messages.CVSSSH2PreferencePage_138); + int buttonWidth=SWTUtils + .calculateControlSize(SWTUtils.createDialogPixelConverter(parent), + new Button[] {removeHostKeyButton}); + removeHostKeyButton.setLayoutData(SWTUtils.createGridData(buttonWidth, + SWT.DEFAULT, SWT.END, SWT.CENTER, false, false)); + removeHostKeyButton.setEnabled(false); removeHostKeyButton.addListener(SWT.Selection, e -> removeHostKey()); - Dialog.applyDialogFont(parent); - - // JSchSession.loadKnownHosts(JSchContext.getDefaultContext().getJSch()); - JSchCorePlugin.getPlugin().loadKnownHosts(); - HostKeyRepository hkr=getJSch().getHostKeyRepository(); - viewer.setInput(hkr.getHostKey()); - handleSelection(); - - return group; - } - - private Control createPreferredAuthenticationPage(Composite parent){ - Composite root = new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.numColumns = 2; - root.setLayout(layout); - - Label label=new Label(root, SWT.NONE); - GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); - textLayoutData.horizontalSpan = 2; - label.setLayoutData(textLayoutData); - label.setText(Messages.CVSSSH2PreferencePage_4); - - preferedAuthMethodTable=new Table(root, SWT.CHECK | SWT.BORDER); - GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); - layoutData.verticalSpan = 3; - preferedAuthMethodTable.setLayoutData(layoutData); - layoutData.minimumHeight = 150; - layoutData.minimumWidth = 200; - populateAuthMethods(); - - up=new Button(root, SWT.PUSH); - up.setText(Messages.CVSSSH2PreferencePage_2); - up.setEnabled(false); - setButtonLayoutData(up); - - down=new Button(root, SWT.PUSH); - down.setText(Messages.CVSSSH2PreferencePage_3); - down.setEnabled(false); - setButtonLayoutData(down); - - preferedAuthMethodTable.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - boolean anySelected = false; - for(int i = 0; i < preferedAuthMethodTable.getItemCount(); i++){ - anySelected |= preferedAuthMethodTable.getItem(i).getChecked(); - } - - if(anySelected){ - setErrorMessage(null); - setValid(true); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_5); - setValid(false); - } - up.setEnabled(preferedAuthMethodTable.getSelectionIndex()>0); - down - .setEnabled(preferedAuthMethodTable.getSelectionIndex()<preferedAuthMethodTable - .getItemCount()-1); - } - - }); - up.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - int selectedIndex=preferedAuthMethodTable.getSelectionIndex(); - if(selectedIndex == 1){ //this is the last possible swap - up.setEnabled(false); - } - down.setEnabled(true); - TableItem sourceItem = preferedAuthMethodTable.getItem(selectedIndex); - TableItem targetItem = preferedAuthMethodTable.getItem(selectedIndex-1); - - //switch text - String stemp = targetItem.getText(); - targetItem.setText(sourceItem.getText()); - sourceItem.setText(stemp); - - //switch selection - boolean btemp = targetItem.getChecked(); - targetItem.setChecked(sourceItem.getChecked()); - sourceItem.setChecked(btemp); - - preferedAuthMethodTable.setSelection(targetItem); - } - }); - - down.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - int selectedIndex=preferedAuthMethodTable.getSelectionIndex(); - if(selectedIndex == preferedAuthMethodTable.getItemCount()-2){ //this is the last possible swap - down.setEnabled(false); - } - up.setEnabled(true); - TableItem sourceItem = preferedAuthMethodTable.getItem(selectedIndex); - TableItem targetItem = preferedAuthMethodTable.getItem(selectedIndex+1); - - //switch text - String stemp = targetItem.getText(); - targetItem.setText(sourceItem.getText()); - sourceItem.setText(stemp); - - //switch selection - boolean btemp = targetItem.getChecked(); - targetItem.setChecked(sourceItem.getChecked()); - sourceItem.setChecked(btemp); - - preferedAuthMethodTable.setSelection(targetItem); - } - }); - - return root; - } - - private void populateAuthMethods(){ - preferedAuthMethodTable.removeAll(); - String[] methods = Utils.getEnabledPreferredAuthMethods().split(","); //$NON-NLS-1$ + Dialog.applyDialogFont(parent); + + // JSchSession.loadKnownHosts(JSchContext.getDefaultContext().getJSch()); + JSchCorePlugin.getPlugin().loadKnownHosts(); + HostKeyRepository hkr=getJSch().getHostKeyRepository(); + viewer.setInput(hkr.getHostKey()); + handleSelection(); + + return group; + } + + private Control createPreferredAuthenticationPage(Composite parent){ + Composite root = new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.numColumns = 2; + root.setLayout(layout); + + Label label=new Label(root, SWT.NONE); + GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); + textLayoutData.horizontalSpan = 2; + label.setLayoutData(textLayoutData); + label.setText(Messages.CVSSSH2PreferencePage_4); + + preferedAuthMethodTable=new Table(root, SWT.CHECK | SWT.BORDER); + GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); + layoutData.verticalSpan = 3; + preferedAuthMethodTable.setLayoutData(layoutData); + layoutData.minimumHeight = 150; + layoutData.minimumWidth = 200; + populateAuthMethods(); + + up=new Button(root, SWT.PUSH); + up.setText(Messages.CVSSSH2PreferencePage_2); + up.setEnabled(false); + setButtonLayoutData(up); + + down=new Button(root, SWT.PUSH); + down.setText(Messages.CVSSSH2PreferencePage_3); + down.setEnabled(false); + setButtonLayoutData(down); + + preferedAuthMethodTable.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + boolean anySelected = false; + for(int i = 0; i < preferedAuthMethodTable.getItemCount(); i++){ + anySelected |= preferedAuthMethodTable.getItem(i).getChecked(); + } + + if(anySelected){ + setErrorMessage(null); + setValid(true); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_5); + setValid(false); + } + up.setEnabled(preferedAuthMethodTable.getSelectionIndex()>0); + down + .setEnabled(preferedAuthMethodTable.getSelectionIndex()<preferedAuthMethodTable + .getItemCount()-1); + } + + }); + up.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + int selectedIndex=preferedAuthMethodTable.getSelectionIndex(); + if(selectedIndex == 1){ //this is the last possible swap + up.setEnabled(false); + } + down.setEnabled(true); + TableItem sourceItem = preferedAuthMethodTable.getItem(selectedIndex); + TableItem targetItem = preferedAuthMethodTable.getItem(selectedIndex-1); + + //switch text + String stemp = targetItem.getText(); + targetItem.setText(sourceItem.getText()); + sourceItem.setText(stemp); + + //switch selection + boolean btemp = targetItem.getChecked(); + targetItem.setChecked(sourceItem.getChecked()); + sourceItem.setChecked(btemp); + + preferedAuthMethodTable.setSelection(targetItem); + } + }); + + down.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + int selectedIndex=preferedAuthMethodTable.getSelectionIndex(); + if(selectedIndex == preferedAuthMethodTable.getItemCount()-2){ //this is the last possible swap + down.setEnabled(false); + } + up.setEnabled(true); + TableItem sourceItem = preferedAuthMethodTable.getItem(selectedIndex); + TableItem targetItem = preferedAuthMethodTable.getItem(selectedIndex+1); + + //switch text + String stemp = targetItem.getText(); + targetItem.setText(sourceItem.getText()); + sourceItem.setText(stemp); + + //switch selection + boolean btemp = targetItem.getChecked(); + targetItem.setChecked(sourceItem.getChecked()); + sourceItem.setChecked(btemp); + + preferedAuthMethodTable.setSelection(targetItem); + } + }); + + return root; + } + + private void populateAuthMethods(){ + preferedAuthMethodTable.removeAll(); + String[] methods = Utils.getEnabledPreferredAuthMethods().split(","); //$NON-NLS-1$ Set<String> smethods = new HashSet<>(Arrays.asList(methods)); - String[] order = Utils.getMethodsOrder().split(","); //$NON-NLS-1$ - - for(int i=0; i<order.length; i++){ - TableItem tableItem= new TableItem(preferedAuthMethodTable, SWT.NONE); - tableItem.setText(0, order[i]); - if(smethods.contains(order[i])){ - tableItem.setChecked(true); - } - } - } - - private Control createPreferredKeyExchangePage(Composite parent){ - Composite root = new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.numColumns = 2; - root.setLayout(layout); - - Label label=new Label(root, SWT.NONE); - GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); - textLayoutData.horizontalSpan = 2; - label.setLayoutData(textLayoutData); - label.setText(Messages.CVSSSH2PreferencePage_140); - - preferedKeyExchangeMethodTable=new Table(root, SWT.CHECK | SWT.BORDER); - GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); - layoutData.verticalSpan = 3; - preferedKeyExchangeMethodTable.setLayoutData(layoutData); - layoutData.minimumHeight = 150; - layoutData.minimumWidth = 200; - populateAuthMethods(); - - kex_up=new Button(root, SWT.PUSH); - kex_up.setText(Messages.CVSSSH2PreferencePage_2); - kex_up.setEnabled(false); - setButtonLayoutData(kex_up); - - kex_down=new Button(root, SWT.PUSH); - kex_down.setText(Messages.CVSSSH2PreferencePage_3); - kex_down.setEnabled(false); - setButtonLayoutData(kex_down); - - preferedKeyExchangeMethodTable.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - boolean anySelected = false; - for(int i = 0; i < preferedKeyExchangeMethodTable.getItemCount(); i++){ - anySelected |= preferedKeyExchangeMethodTable.getItem(i).getChecked(); - } - - if(anySelected){ - setErrorMessage(null); - setValid(true); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_142); - setValid(false); - } - kex_up.setEnabled(preferedKeyExchangeMethodTable.getSelectionIndex()>0); - kex_down - .setEnabled(preferedKeyExchangeMethodTable.getSelectionIndex()<preferedKeyExchangeMethodTable - .getItemCount()-1); - } - - }); - kex_up.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - int selectedIndex=preferedKeyExchangeMethodTable.getSelectionIndex(); - if(selectedIndex == 1){ //this is the last possible swap - kex_up.setEnabled(false); - } - kex_down.setEnabled(true); - TableItem sourceItem = preferedKeyExchangeMethodTable.getItem(selectedIndex); - TableItem targetItem = preferedKeyExchangeMethodTable.getItem(selectedIndex-1); - - //switch text - String stemp = targetItem.getText(); - targetItem.setText(sourceItem.getText()); - sourceItem.setText(stemp); - - //switch selection - boolean btemp = targetItem.getChecked(); - targetItem.setChecked(sourceItem.getChecked()); - sourceItem.setChecked(btemp); - - preferedKeyExchangeMethodTable.setSelection(targetItem); - } - }); - - kex_down.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - int selectedIndex=preferedKeyExchangeMethodTable.getSelectionIndex(); - if(selectedIndex == preferedKeyExchangeMethodTable.getItemCount()-2){ //this is the last possible swap - kex_down.setEnabled(false); - } - kex_up.setEnabled(true); - TableItem sourceItem = preferedKeyExchangeMethodTable.getItem(selectedIndex); - TableItem targetItem = preferedKeyExchangeMethodTable.getItem(selectedIndex+1); - - //switch text - String stemp = targetItem.getText(); - targetItem.setText(sourceItem.getText()); - sourceItem.setText(stemp); - - //switch selection - boolean btemp = targetItem.getChecked(); - targetItem.setChecked(sourceItem.getChecked()); - sourceItem.setChecked(btemp); - - preferedKeyExchangeMethodTable.setSelection(targetItem); - } - }); - - return root; - } - - private void populateKeyExchangeMethods(){ - preferedKeyExchangeMethodTable.removeAll(); - String[] methods = Utils.getEnabledPreferredKEXMethods().split(","); //$NON-NLS-1$ - Set<String> smethods = new HashSet<>(Arrays.asList(methods)); - - String[] order = Utils.getKEXMethodsOrder().split(","); //$NON-NLS-1$ - - for(int i=0; i<order.length; i++){ - TableItem tableItem= new TableItem(preferedKeyExchangeMethodTable, SWT.NONE); - tableItem.setText(0, order[i]); - if(smethods.contains(order[i])){ - tableItem.setChecked(true); - } - } - } - - private Control createPreferredMACPage(Composite parent){ - Composite root = new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.numColumns = 2; - root.setLayout(layout); - - Label label=new Label(root, SWT.NONE); - GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); - textLayoutData.horizontalSpan = 2; - label.setLayoutData(textLayoutData); - label.setText(Messages.CVSSSH2PreferencePage_141); - - preferedMACMethodTable=new Table(root, SWT.CHECK | SWT.BORDER); - GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); - layoutData.verticalSpan = 3; - preferedMACMethodTable.setLayoutData(layoutData); - layoutData.minimumHeight = 150; - layoutData.minimumWidth = 200; - populateMACMethods(); - - mac_up=new Button(root, SWT.PUSH); - mac_up.setText(Messages.CVSSSH2PreferencePage_2); - mac_up.setEnabled(false); - setButtonLayoutData(mac_up); - - mac_down=new Button(root, SWT.PUSH); - mac_down.setText(Messages.CVSSSH2PreferencePage_3); - mac_down.setEnabled(false); - setButtonLayoutData(mac_down); - - preferedMACMethodTable.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - boolean anySelected = false; - for(int i = 0; i < preferedMACMethodTable.getItemCount(); i++){ - anySelected |= preferedMACMethodTable.getItem(i).getChecked(); - } - - if(anySelected){ - setErrorMessage(null); - setValid(true); - } - else{ - setErrorMessage(Messages.CVSSSH2PreferencePage_143); - setValid(false); - } - mac_up.setEnabled(preferedMACMethodTable.getSelectionIndex()>0); - mac_down - .setEnabled(preferedMACMethodTable.getSelectionIndex()<preferedMACMethodTable - .getItemCount()-1); - } - - }); - mac_up.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - int selectedIndex=preferedMACMethodTable.getSelectionIndex(); - if(selectedIndex == 1){ //this is the last possible swap - mac_up.setEnabled(false); - } - mac_down.setEnabled(true); - TableItem sourceItem = preferedMACMethodTable.getItem(selectedIndex); - TableItem targetItem = preferedMACMethodTable.getItem(selectedIndex-1); - - //switch text - String stemp = targetItem.getText(); - targetItem.setText(sourceItem.getText()); - sourceItem.setText(stemp); - - //switch selection - boolean btemp = targetItem.getChecked(); - targetItem.setChecked(sourceItem.getChecked()); - sourceItem.setChecked(btemp); - - preferedMACMethodTable.setSelection(targetItem); - } - }); - - mac_down.addSelectionListener(new SelectionAdapter(){ - - @Override - public void widgetSelected(SelectionEvent e){ - int selectedIndex=preferedMACMethodTable.getSelectionIndex(); - if(selectedIndex == preferedMACMethodTable.getItemCount()-2){ //this is the last possible swap - mac_down.setEnabled(false); - } - mac_up.setEnabled(true); - TableItem sourceItem = preferedMACMethodTable.getItem(selectedIndex); - TableItem targetItem = preferedMACMethodTable.getItem(selectedIndex+1); - - //switch text - String stemp = targetItem.getText(); - targetItem.setText(sourceItem.getText()); - sourceItem.setText(stemp); - - //switch selection - boolean btemp = targetItem.getChecked(); - targetItem.setChecked(sourceItem.getChecked()); - sourceItem.setChecked(btemp); - - preferedMACMethodTable.setSelection(targetItem); - } - }); - - return root; - } - - private Control createPreferredSSHAgentPage(Composite parent){ - Composite root = new Composite(parent, SWT.NONE); - GridLayout layout=new GridLayout(); - layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.numColumns = 2; - root.setLayout(layout); - - Label label=new Label(root, SWT.NONE); - GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); - textLayoutData.horizontalSpan = 2; - label.setLayoutData(textLayoutData); - label.setText(Messages.CVSSSH2PreferencePage_147); - - preferedSSHAgentTable=new Table(root, SWT.CHECK | SWT.BORDER); - GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); - layoutData.verticalSpan = 3; - preferedSSHAgentTable.setLayoutData(layoutData); - layoutData.minimumHeight = 150; - layoutData.minimumWidth = 200; - populateSSHAgents(); - return root; - } - - private void populateSSHAgents(){ - preferedSSHAgentTable.removeAll(); - String[] methods = Utils.getAvailableSSHAgents().split(","); //$NON-NLS-1$ - String[] selected = Utils.getSelectedSSHAgent().split(","); //$NON-NLS-1$ - - for(int i=0; i<methods.length; i++){ - if(methods[i].length()==0) - continue; - TableItem tableItem= new TableItem(preferedSSHAgentTable, SWT.NONE); - tableItem.setText(0, methods[i]); - for(int j=0; j<selected.length; j++){ - if(selected[j].equals(methods[i])){ - tableItem.setChecked(true); - break; - } - } - } - } - - private void populateMACMethods(){ - preferedMACMethodTable.removeAll(); - String[] methods = Utils.getEnabledPreferredMACMethods().split(","); //$NON-NLS-1$ - Set<String> smethods = new HashSet<>(Arrays.asList(methods)); - - String[] order = Utils.getMACMethodsOrder().split(","); //$NON-NLS-1$ - - for(int i=0; i<order.length; i++){ - TableItem tableItem= new TableItem(preferedMACMethodTable, SWT.NONE); - tableItem.setText(0, order[i]); - if(smethods.contains(order[i])){ - tableItem.setChecked(true); - } - } - } - - void handleSelection(){ - boolean empty=viewer.getSelection().isEmpty(); - removeHostKeyButton.setEnabled(!empty); - } - - void removeHostKey(){ - IStructuredSelection selection=viewer.getStructuredSelection(); - HostKeyRepository hkr=getJSch().getHostKeyRepository(); - for(Iterator<?> iterator=selection.iterator(); iterator.hasNext();){ - HostKey hostkey=(HostKey)iterator.next(); - hkr.remove(hostkey.getHost(), hostkey.getType()); - viewer.remove(hostkey); - } - } - - void export_via_sftp(String user, String host, int port, byte[] pkey) throws JSchException{ - try{ - - int timeout = 60000; - IJSchService service = JSchUIPlugin.getPlugin().getJSchService(); - if (service == null) { - MessageDialog.openInformation(getShell(), Messages.PreferencePage_0, Messages.PreferencePage_1); - return; - } - - IJSchLocation location=service.getLocation(user, host, port); - // We hope that prompts for jsch are given by IJSchService, so "null" should be passed. - Session session = service.createSession(location, null); - session.setTimeout(timeout); - try { - service.connect(session, timeout, new NullProgressMonitor()); - if(session.getServerVersion().indexOf("OpenSSH")==-1){ //$NON-NLS-1$ - setErrorMessage(Messages.CVSSSH2PreferencePage_110); - return; - } - Channel channel=session.openChannel("sftp"); //$NON-NLS-1$ - channel.connect(); - ChannelSftp c=(ChannelSftp)channel; - - SftpATTRS attr=null; - - try{ - attr=c.stat(".ssh");} //$NON-NLS-1$ - catch(SftpException ee){ - // Ignore - } - if(attr==null){ - try{ - c.mkdir(".ssh");} //$NON-NLS-1$ - catch(SftpException ee){ - setErrorMessage(ee.getMessage()); - return; - } - } - try{ - c.cd(".ssh");} //$NON-NLS-1$ - catch(SftpException ee){ - setErrorMessage(ee.getMessage()); - return; - } - - try{ - ByteArrayInputStream bis=new ByteArrayInputStream(pkey); - c.put(bis, "authorized_keys", null, ChannelSftp.APPEND); //$NON-NLS-1$ - bis.close(); - checkPermission(c, "authorized_keys"); //$NON-NLS-1$ - checkPermission(c, "."); // .ssh //$NON-NLS-1$ - c.cd(".."); //$NON-NLS-1$ - checkPermission(c, "."); // home directory //$NON-NLS-1$ - } - catch(SftpException ee){ - // setErrorMessage(debug+ee.message); - } - - MessageDialog.openInformation(getShell(), - Messages.CVSSSH2PreferencePage_information, - NLS.bind(Messages.CVSSSH2PreferencePage_109, (user - +"@"+host+(port==22 ? "" : ":"+port)+":~/.ssh/authorized_keys"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - - c.quit(); - c.disconnect(); - } finally { - session.disconnect(); - } - } catch(IOException eee){ - setErrorMessage(eee.toString()); - } - } - - private void checkPermission(ChannelSftp c, String path) throws SftpException{ - SftpATTRS attr=c.stat(path); - int permissions=attr.getPermissions(); - if((permissions&00022)!=0){ - permissions&=~00022; - c.chmod(permissions, path); - } - } - - void updateControls(){ - boolean enable=(kpair!=null); - publicKeylabel.setEnabled(enable); - publicKeyText.setEnabled(enable); - keyFingerPrintLabel.setEnabled(enable); - keyFingerPrintText.setEnabled(enable); - keyCommentLabel.setEnabled(enable); - keyCommentText.setEnabled(enable); - keyPassphrase1Label.setEnabled(enable); - keyPassphrase1Text.setEnabled(enable); - keyPassphrase2Label.setEnabled(enable); - keyPassphrase2Text.setEnabled(enable); - keyExport.setEnabled(enable); - saveKeyPair.setEnabled(enable); - populateAuthMethods(); - populateKeyExchangeMethods(); - populateMACMethods(); - up.setEnabled(false); - down.setEnabled(false); - kex_up.setEnabled(false); - kex_down.setEnabled(false); - mac_up.setEnabled(false); - mac_down.setEnabled(false); - } - - @Override + String[] order = Utils.getMethodsOrder().split(","); //$NON-NLS-1$ + + for(int i=0; i<order.length; i++){ + TableItem tableItem= new TableItem(preferedAuthMethodTable, SWT.NONE); + tableItem.setText(0, order[i]); + if(smethods.contains(order[i])){ + tableItem.setChecked(true); + } + } + } + + private Control createPreferredKeyExchangePage(Composite parent){ + Composite root = new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.numColumns = 2; + root.setLayout(layout); + + Label label=new Label(root, SWT.NONE); + GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); + textLayoutData.horizontalSpan = 2; + label.setLayoutData(textLayoutData); + label.setText(Messages.CVSSSH2PreferencePage_140); + + preferedKeyExchangeMethodTable=new Table(root, SWT.CHECK | SWT.BORDER); + GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); + layoutData.verticalSpan = 3; + preferedKeyExchangeMethodTable.setLayoutData(layoutData); + layoutData.minimumHeight = 150; + layoutData.minimumWidth = 200; + populateAuthMethods(); + + kex_up=new Button(root, SWT.PUSH); + kex_up.setText(Messages.CVSSSH2PreferencePage_2); + kex_up.setEnabled(false); + setButtonLayoutData(kex_up); + + kex_down=new Button(root, SWT.PUSH); + kex_down.setText(Messages.CVSSSH2PreferencePage_3); + kex_down.setEnabled(false); + setButtonLayoutData(kex_down); + + preferedKeyExchangeMethodTable.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + boolean anySelected = false; + for(int i = 0; i < preferedKeyExchangeMethodTable.getItemCount(); i++){ + anySelected |= preferedKeyExchangeMethodTable.getItem(i).getChecked(); + } + + if(anySelected){ + setErrorMessage(null); + setValid(true); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_142); + setValid(false); + } + kex_up.setEnabled(preferedKeyExchangeMethodTable.getSelectionIndex()>0); + kex_down + .setEnabled(preferedKeyExchangeMethodTable.getSelectionIndex()<preferedKeyExchangeMethodTable + .getItemCount()-1); + } + + }); + kex_up.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + int selectedIndex=preferedKeyExchangeMethodTable.getSelectionIndex(); + if(selectedIndex == 1){ //this is the last possible swap + kex_up.setEnabled(false); + } + kex_down.setEnabled(true); + TableItem sourceItem = preferedKeyExchangeMethodTable.getItem(selectedIndex); + TableItem targetItem = preferedKeyExchangeMethodTable.getItem(selectedIndex-1); + + //switch text + String stemp = targetItem.getText(); + targetItem.setText(sourceItem.getText()); + sourceItem.setText(stemp); + + //switch selection + boolean btemp = targetItem.getChecked(); + targetItem.setChecked(sourceItem.getChecked()); + sourceItem.setChecked(btemp); + + preferedKeyExchangeMethodTable.setSelection(targetItem); + } + }); + + kex_down.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + int selectedIndex=preferedKeyExchangeMethodTable.getSelectionIndex(); + if(selectedIndex == preferedKeyExchangeMethodTable.getItemCount()-2){ //this is the last possible swap + kex_down.setEnabled(false); + } + kex_up.setEnabled(true); + TableItem sourceItem = preferedKeyExchangeMethodTable.getItem(selectedIndex); + TableItem targetItem = preferedKeyExchangeMethodTable.getItem(selectedIndex+1); + + //switch text + String stemp = targetItem.getText(); + targetItem.setText(sourceItem.getText()); + sourceItem.setText(stemp); + + //switch selection + boolean btemp = targetItem.getChecked(); + targetItem.setChecked(sourceItem.getChecked()); + sourceItem.setChecked(btemp); + + preferedKeyExchangeMethodTable.setSelection(targetItem); + } + }); + + return root; + } + + private void populateKeyExchangeMethods(){ + preferedKeyExchangeMethodTable.removeAll(); + String[] methods = Utils.getEnabledPreferredKEXMethods().split(","); //$NON-NLS-1$ + Set<String> smethods = new HashSet<>(Arrays.asList(methods)); + + String[] order = Utils.getKEXMethodsOrder().split(","); //$NON-NLS-1$ + + for(int i=0; i<order.length; i++){ + TableItem tableItem= new TableItem(preferedKeyExchangeMethodTable, SWT.NONE); + tableItem.setText(0, order[i]); + if(smethods.contains(order[i])){ + tableItem.setChecked(true); + } + } + } + + private Control createPreferredMACPage(Composite parent){ + Composite root = new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.numColumns = 2; + root.setLayout(layout); + + Label label=new Label(root, SWT.NONE); + GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); + textLayoutData.horizontalSpan = 2; + label.setLayoutData(textLayoutData); + label.setText(Messages.CVSSSH2PreferencePage_141); + + preferedMACMethodTable=new Table(root, SWT.CHECK | SWT.BORDER); + GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); + layoutData.verticalSpan = 3; + preferedMACMethodTable.setLayoutData(layoutData); + layoutData.minimumHeight = 150; + layoutData.minimumWidth = 200; + populateMACMethods(); + + mac_up=new Button(root, SWT.PUSH); + mac_up.setText(Messages.CVSSSH2PreferencePage_2); + mac_up.setEnabled(false); + setButtonLayoutData(mac_up); + + mac_down=new Button(root, SWT.PUSH); + mac_down.setText(Messages.CVSSSH2PreferencePage_3); + mac_down.setEnabled(false); + setButtonLayoutData(mac_down); + + preferedMACMethodTable.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + boolean anySelected = false; + for(int i = 0; i < preferedMACMethodTable.getItemCount(); i++){ + anySelected |= preferedMACMethodTable.getItem(i).getChecked(); + } + + if(anySelected){ + setErrorMessage(null); + setValid(true); + } + else{ + setErrorMessage(Messages.CVSSSH2PreferencePage_143); + setValid(false); + } + mac_up.setEnabled(preferedMACMethodTable.getSelectionIndex()>0); + mac_down + .setEnabled(preferedMACMethodTable.getSelectionIndex()<preferedMACMethodTable + .getItemCount()-1); + } + + }); + mac_up.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + int selectedIndex=preferedMACMethodTable.getSelectionIndex(); + if(selectedIndex == 1){ //this is the last possible swap + mac_up.setEnabled(false); + } + mac_down.setEnabled(true); + TableItem sourceItem = preferedMACMethodTable.getItem(selectedIndex); + TableItem targetItem = preferedMACMethodTable.getItem(selectedIndex-1); + + //switch text + String stemp = targetItem.getText(); + targetItem.setText(sourceItem.getText()); + sourceItem.setText(stemp); + + //switch selection + boolean btemp = targetItem.getChecked(); + targetItem.setChecked(sourceItem.getChecked()); + sourceItem.setChecked(btemp); + + preferedMACMethodTable.setSelection(targetItem); + } + }); + + mac_down.addSelectionListener(new SelectionAdapter(){ + + @Override + public void widgetSelected(SelectionEvent e){ + int selectedIndex=preferedMACMethodTable.getSelectionIndex(); + if(selectedIndex == preferedMACMethodTable.getItemCount()-2){ //this is the last possible swap + mac_down.setEnabled(false); + } + mac_up.setEnabled(true); + TableItem sourceItem = preferedMACMethodTable.getItem(selectedIndex); + TableItem targetItem = preferedMACMethodTable.getItem(selectedIndex+1); + + //switch text + String stemp = targetItem.getText(); + targetItem.setText(sourceItem.getText()); + sourceItem.setText(stemp); + + //switch selection + boolean btemp = targetItem.getChecked(); + targetItem.setChecked(sourceItem.getChecked()); + sourceItem.setChecked(btemp); + + preferedMACMethodTable.setSelection(targetItem); + } + }); + + return root; + } + + private Control createPreferredSSHAgentPage(Composite parent){ + Composite root = new Composite(parent, SWT.NONE); + GridLayout layout=new GridLayout(); + layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.numColumns = 2; + root.setLayout(layout); + + Label label=new Label(root, SWT.NONE); + GridData textLayoutData=new GridData(SWT.BEGINNING, SWT.BEGINNING, true, false); + textLayoutData.horizontalSpan = 2; + label.setLayoutData(textLayoutData); + label.setText(Messages.CVSSSH2PreferencePage_147); + + preferedSSHAgentTable=new Table(root, SWT.CHECK | SWT.BORDER); + GridData layoutData=new GridData(SWT.FILL, SWT.BEGINNING, true, true); + layoutData.verticalSpan = 3; + preferedSSHAgentTable.setLayoutData(layoutData); + layoutData.minimumHeight = 150; + layoutData.minimumWidth = 200; + populateSSHAgents(); + return root; + } + + private void populateSSHAgents(){ + preferedSSHAgentTable.removeAll(); + String[] methods = Utils.getAvailableSSHAgents().split(","); //$NON-NLS-1$ + String[] selected = Utils.getSelectedSSHAgent().split(","); //$NON-NLS-1$ + + for(int i=0; i<methods.length; i++){ + if(methods[i].length()==0) + continue; + TableItem tableItem= new TableItem(preferedSSHAgentTable, SWT.NONE); + tableItem.setText(0, methods[i]); + for(int j=0; j<selected.length; j++){ + if(selected[j].equals(methods[i])){ + tableItem.setChecked(true); + break; + } + } + } + } + + private void populateMACMethods(){ + preferedMACMethodTable.removeAll(); + String[] methods = Utils.getEnabledPreferredMACMethods().split(","); //$NON-NLS-1$ + Set<String> smethods = new HashSet<>(Arrays.asList(methods)); + + String[] order = Utils.getMACMethodsOrder().split(","); //$NON-NLS-1$ + + for(int i=0; i<order.length; i++){ + TableItem tableItem= new TableItem(preferedMACMethodTable, SWT.NONE); + tableItem.setText(0, order[i]); + if(smethods.contains(order[i])){ + tableItem.setChecked(true); + } + } + } + + void handleSelection(){ + boolean empty=viewer.getSelection().isEmpty(); + removeHostKeyButton.setEnabled(!empty); + } + + void removeHostKey(){ + IStructuredSelection selection=viewer.getStructuredSelection(); + HostKeyRepository hkr=getJSch().getHostKeyRepository(); + for(Iterator<?> iterator=selection.iterator(); iterator.hasNext();){ + HostKey hostkey=(HostKey)iterator.next(); + hkr.remove(hostkey.getHost(), hostkey.getType()); + viewer.remove(hostkey); + } + } + + void export_via_sftp(String user, String host, int port, byte[] pkey) throws JSchException{ + try{ + + int timeout = 60000; + IJSchService service = JSchUIPlugin.getPlugin().getJSchService(); + if (service == null) { + MessageDialog.openInformation(getShell(), Messages.PreferencePage_0, Messages.PreferencePage_1); + return; + } + + IJSchLocation location=service.getLocation(user, host, port); + // We hope that prompts for jsch are given by IJSchService, so "null" should be passed. + Session session = service.createSession(location, null); + session.setTimeout(timeout); + try { + service.connect(session, timeout, new NullProgressMonitor()); + if(session.getServerVersion().indexOf("OpenSSH")==-1){ //$NON-NLS-1$ + setErrorMessage(Messages.CVSSSH2PreferencePage_110); + return; + } + Channel channel=session.openChannel("sftp"); //$NON-NLS-1$ + channel.connect(); + ChannelSftp c=(ChannelSftp)channel; + + SftpATTRS attr=null; + + try{ + attr=c.stat(".ssh");} //$NON-NLS-1$ + catch(SftpException ee){ + // Ignore + } + if(attr==null){ + try{ + c.mkdir(".ssh");} //$NON-NLS-1$ + catch(SftpException ee){ + setErrorMessage(ee.getMessage()); + return; + } + } + try{ + c.cd(".ssh");} //$NON-NLS-1$ + catch(SftpException ee){ + setErrorMessage(ee.getMessage()); + return; + } + + try{ + ByteArrayInputStream bis=new ByteArrayInputStream(pkey); + c.put(bis, "authorized_keys", null, ChannelSftp.APPEND); //$NON-NLS-1$ + bis.close(); + checkPermission(c, "authorized_keys"); //$NON-NLS-1$ + checkPermission(c, "."); // .ssh //$NON-NLS-1$ + c.cd(".."); //$NON-NLS-1$ + checkPermission(c, "."); // home directory //$NON-NLS-1$ + } + catch(SftpException ee){ + // setErrorMessage(debug+ee.message); + } + + MessageDialog.openInformation(getShell(), + Messages.CVSSSH2PreferencePage_information, + NLS.bind(Messages.CVSSSH2PreferencePage_109, (user + +"@"+host+(port==22 ? "" : ":"+port)+":~/.ssh/authorized_keys"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + c.quit(); + c.disconnect(); + } finally { + session.disconnect(); + } + } catch(IOException eee){ + setErrorMessage(eee.toString()); + } + } + + private void checkPermission(ChannelSftp c, String path) throws SftpException{ + SftpATTRS attr=c.stat(path); + int permissions=attr.getPermissions(); + if((permissions&00022)!=0){ + permissions&=~00022; + c.chmod(permissions, path); + } + } + + void updateControls(){ + boolean enable=(kpair!=null); + publicKeylabel.setEnabled(enable); + publicKeyText.setEnabled(enable); + keyFingerPrintLabel.setEnabled(enable); + keyFingerPrintText.setEnabled(enable); + keyCommentLabel.setEnabled(enable); + keyCommentText.setEnabled(enable); + keyPassphrase1Label.setEnabled(enable); + keyPassphrase1Text.setEnabled(enable); + keyPassphrase2Label.setEnabled(enable); + keyPassphrase2Text.setEnabled(enable); + keyExport.setEnabled(enable); + saveKeyPair.setEnabled(enable); + populateAuthMethods(); + populateKeyExchangeMethods(); + populateMACMethods(); + up.setEnabled(false); + down.setEnabled(false); + kex_up.setEnabled(false); + kex_down.setEnabled(false); + mac_up.setEnabled(false); + mac_down.setEnabled(false); + } + + @Override public void init(IWorkbench workbench){ - // super.init(workbench); - // initControls(); - } - - public void initialize(){ - initControls(); - } - - private void initControls(){ - Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); - ssh2HomeText.setText(preferences - .getString(org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME)); - privateKeyText.setText(preferences - .getString(org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY)); - updateControls(); - } - - @Override + // super.init(workbench); + // initControls(); + } + + public void initialize(){ + initControls(); + } + + private void initControls(){ + Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); + ssh2HomeText.setText(preferences + .getString(org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME)); + privateKeyText.setText(preferences + .getString(org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY)); + updateControls(); + } + + @Override public boolean performOk(){ - boolean result=super.performOk(); - storeAuthenticationMethodSettings(); - storeSSHAgentSettings(); - storeKeyExchangeMethodSettings(); - storeMACMethodSettings(); - - if(result){ - setErrorMessage(null); - String home=ssh2HomeText.getText(); - File _home=new File(home); - if(!_home.exists()){ - if(MessageDialog.openQuestion(getShell(), - Messages.CVSSSH2PreferencePage_question, NLS.bind( - Messages.CVSSSH2PreferencePage_99, new String[] {home}))){ - if(!(_home.mkdirs())){ - setErrorMessage(Messages.CVSSSH2PreferencePage_100+home); - return false; - } - } - } - - Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); - preferences.setValue( - org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME, home); - preferences.setValue( - org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY, - privateKeyText.getText()); - } - JSchCorePlugin.getPlugin().setNeedToLoadKnownHosts(true); - JSchCorePlugin.getPlugin().setNeedToLoadKeys(true); - JSchCorePlugin.getPlugin().setIdentityRepository(); - JSchCorePlugin.getPlugin().savePluginPreferences(); - return result; - } - - private void storeAuthenticationMethodSettings(){ - String selected = null; - String order = null; - for(int i = 0; i < preferedAuthMethodTable.getItemCount(); i++){ - TableItem item=preferedAuthMethodTable.getItem(i); - if(item.getChecked()){ - if(selected==null){ - selected=item.getText(); - } - else{ - selected+=","+item.getText(); //$NON-NLS-1$ - } - } - if(order == null){ - order = item.getText(); - } else { - order += "," + item.getText(); //$NON-NLS-1$ - } - } - Utils.setEnabledPreferredAuthMethods(selected, order); - } - - private void storeSSHAgentSettings(){ - String selected = ""; //$NON-NLS-1$ - for(int i = 0; i < preferedSSHAgentTable.getItemCount(); i++){ - TableItem item=preferedSSHAgentTable.getItem(i); - if(item.getChecked()){ - if(selected.length()==0){ - selected=item.getText(); - } - else{ - selected+=","+item.getText(); //$NON-NLS-1$ - } - } - } - Utils.setSelectedSSHAgents(selected); - } - - private void storeKeyExchangeMethodSettings(){ - String selected = null; - String order = null; - for(int i = 0; i < preferedKeyExchangeMethodTable.getItemCount(); i++){ - TableItem item=preferedKeyExchangeMethodTable.getItem(i); - if(item.getChecked()){ - if(selected==null){ - selected=item.getText(); - } - else{ - selected+=","+item.getText(); //$NON-NLS-1$ - } - } - if(order == null){ - order = item.getText(); - } else { - order += "," + item.getText(); //$NON-NLS-1$ - } - } - Utils.setEnabledPreferredKEXMethods(selected, order); - } - - private void storeMACMethodSettings(){ - String selected = null; - String order = null; - for(int i = 0; i < preferedMACMethodTable.getItemCount(); i++){ - TableItem item=preferedMACMethodTable.getItem(i); - if(item.getChecked()){ - if(selected==null){ - selected=item.getText(); - } - else{ - selected+=","+item.getText(); //$NON-NLS-1$ - } - } - if(order == null){ - order = item.getText(); - } else { - order += "," + item.getText(); //$NON-NLS-1$ - } - } - Utils.setEnabledPreferredMACMethods(selected, order); - } - - @Override + boolean result=super.performOk(); + storeAuthenticationMethodSettings(); + storeSSHAgentSettings(); + storeKeyExchangeMethodSettings(); + storeMACMethodSettings(); + + if(result){ + setErrorMessage(null); + String home=ssh2HomeText.getText(); + File _home=new File(home); + if(!_home.exists()){ + if(MessageDialog.openQuestion(getShell(), + Messages.CVSSSH2PreferencePage_question, NLS.bind( + Messages.CVSSSH2PreferencePage_99, new String[] {home}))){ + if(!(_home.mkdirs())){ + setErrorMessage(Messages.CVSSSH2PreferencePage_100+home); + return false; + } + } + } + + Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); + preferences.setValue( + org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME, home); + preferences.setValue( + org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY, + privateKeyText.getText()); + } + JSchCorePlugin.getPlugin().setNeedToLoadKnownHosts(true); + JSchCorePlugin.getPlugin().setNeedToLoadKeys(true); + JSchCorePlugin.getPlugin().setIdentityRepository(); + JSchCorePlugin.getPlugin().savePluginPreferences(); + return result; + } + + private void storeAuthenticationMethodSettings(){ + String selected = null; + String order = null; + for(int i = 0; i < preferedAuthMethodTable.getItemCount(); i++){ + TableItem item=preferedAuthMethodTable.getItem(i); + if(item.getChecked()){ + if(selected==null){ + selected=item.getText(); + } + else{ + selected+=","+item.getText(); //$NON-NLS-1$ + } + } + if(order == null){ + order = item.getText(); + } else { + order += "," + item.getText(); //$NON-NLS-1$ + } + } + Utils.setEnabledPreferredAuthMethods(selected, order); + } + + private void storeSSHAgentSettings(){ + String selected = ""; //$NON-NLS-1$ + for(int i = 0; i < preferedSSHAgentTable.getItemCount(); i++){ + TableItem item=preferedSSHAgentTable.getItem(i); + if(item.getChecked()){ + if(selected.length()==0){ + selected=item.getText(); + } + else{ + selected+=","+item.getText(); //$NON-NLS-1$ + } + } + } + Utils.setSelectedSSHAgents(selected); + } + + private void storeKeyExchangeMethodSettings(){ + String selected = null; + String order = null; + for(int i = 0; i < preferedKeyExchangeMethodTable.getItemCount(); i++){ + TableItem item=preferedKeyExchangeMethodTable.getItem(i); + if(item.getChecked()){ + if(selected==null){ + selected=item.getText(); + } + else{ + selected+=","+item.getText(); //$NON-NLS-1$ + } + } + if(order == null){ + order = item.getText(); + } else { + order += "," + item.getText(); //$NON-NLS-1$ + } + } + Utils.setEnabledPreferredKEXMethods(selected, order); + } + + private void storeMACMethodSettings(){ + String selected = null; + String order = null; + for(int i = 0; i < preferedMACMethodTable.getItemCount(); i++){ + TableItem item=preferedMACMethodTable.getItem(i); + if(item.getChecked()){ + if(selected==null){ + selected=item.getText(); + } + else{ + selected+=","+item.getText(); //$NON-NLS-1$ + } + } + if(order == null){ + order = item.getText(); + } else { + order += "," + item.getText(); //$NON-NLS-1$ + } + } + Utils.setEnabledPreferredMACMethods(selected, order); + } + + @Override public void performApply(){ - performOk(); - } + performOk(); + } - @Override + @Override protected void performDefaults(){ - super.performDefaults(); - Utils.setEnabledPreferredAuthMethods(Utils.getDefaultAuthMethods(), Utils - .getDefaultAuthMethods()); - Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); - ssh2HomeText - .setText(preferences - .getDefaultString(org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME)); - privateKeyText - .setText(preferences - .getDefaultString(org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY)); - updateControls(); - } - - protected void createSpacer(Composite composite, int columnSpan){ - Label label=new Label(composite, SWT.NONE); - GridData gd=new GridData(); - gd.horizontalSpan=columnSpan; - label.setLayoutData(gd); - } - - JSch getJSch(){ - return JSchCorePlugin.getPlugin().getJSch(); - } - - class PassphrasePrompt implements Runnable{ - private String message; - private String passphrase; - - PassphrasePrompt(String message){ - this.message=message; - } - - @Override - public void run(){ - Display display=Display.getCurrent(); - Shell shell=new Shell(display); - PassphraseDialog dialog=new PassphraseDialog(shell, message); - dialog.open(); - shell.dispose(); - passphrase=dialog.getPassphrase(); - } - - public String getPassphrase(){ - return passphrase; - } - } + super.performDefaults(); + Utils.setEnabledPreferredAuthMethods(Utils.getDefaultAuthMethods(), Utils + .getDefaultAuthMethods()); + Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); + ssh2HomeText + .setText(preferences + .getDefaultString(org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME)); + privateKeyText + .setText(preferences + .getDefaultString(org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY)); + updateControls(); + } + + protected void createSpacer(Composite composite, int columnSpan){ + Label label=new Label(composite, SWT.NONE); + GridData gd=new GridData(); + gd.horizontalSpan=columnSpan; + label.setLayoutData(gd); + } + + JSch getJSch(){ + return JSchCorePlugin.getPlugin().getJSch(); + } + + class PassphrasePrompt implements Runnable{ + private String message; + private String passphrase; + + PassphrasePrompt(String message){ + this.message=message; + } + + @Override + public void run(){ + Display display=Display.getCurrent(); + Shell shell=new Shell(display); + PassphraseDialog dialog=new PassphraseDialog(shell, message); + dialog.open(); + shell.dispose(); + passphrase=dialog.getPassphrase(); + } + + public String getPassphrase(){ + return passphrase; + } + } } diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/SWTUtils.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/SWTUtils.java index 8a5ace145..8523a9c16 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/SWTUtils.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/internal/ui/preference/SWTUtils.java @@ -31,96 +31,96 @@ public class SWTUtils { public static final int MARGINS_DIALOG= 1; public static PreferenceLinkArea createPreferenceLink(IWorkbenchPreferenceContainer container, Composite parent, String pageId, String text) { - final PreferenceLinkArea area = new PreferenceLinkArea(parent, SWT.NONE, pageId, text, container, null); - return area; - } - - public static GridData createGridData(int width, int height, boolean hFill, boolean vFill) { - return createGridData(width, height, hFill ? SWT.FILL : SWT.BEGINNING, vFill ? SWT.FILL : SWT.CENTER, hFill, vFill); - } - - public static GridData createGridData(int width, int height, int hAlign, int vAlign, boolean hGrab, boolean vGrab) { - final GridData gd= new GridData(hAlign, vAlign, hGrab, vGrab); - gd.widthHint= width; - gd.heightHint= height; - return gd; - } - - public static GridData createHFillGridData() { - return createHFillGridData(1); - } - - public static GridData createHFillGridData(int span) { - final GridData gd= createGridData(0, SWT.DEFAULT, SWT.FILL, SWT.CENTER, true, false); - gd.horizontalSpan= span; - return gd; - } - - public static Composite createHFillComposite(Composite parent, int margins) { - return createHFillComposite(parent, margins, 1); - } - - public static Composite createHFillComposite(Composite parent, int margins, int columns) { - final Composite composite= new Composite(parent, SWT.NONE); - composite.setFont(parent.getFont()); - composite.setLayoutData(createHFillGridData()); - composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); - return composite; - } - - public static Composite createHVFillComposite(Composite parent, int margins) { - return createHVFillComposite(parent, margins, 1); - } - - public static Composite createHVFillComposite(Composite parent, int margins, int columns) { - final Composite composite= new Composite(parent, SWT.NONE); - composite.setFont(parent.getFont()); - composite.setLayoutData(createHVFillGridData()); - composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); - return composite; - } - - - public static Group createHFillGroup(Composite parent, String text, int margins) { - return createHFillGroup(parent, text, margins, 1); - } - - public static Group createHFillGroup(Composite parent, String text, int margins, int rows) { - final Group group= new Group(parent, SWT.NONE); - group.setFont(parent.getFont()); - group.setLayoutData(createHFillGridData()); - if (text != null) - group.setText(text); - group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); - return group; - } - - public static Group createHVFillGroup(Composite parent, String text, int margins) { - return createHVFillGroup(parent, text, margins, 1); - } - - public static Group createHVFillGroup(Composite parent, String text, int margins, int rows) { - final Group group= new Group(parent, SWT.NONE); - group.setFont(parent.getFont()); - group.setLayoutData(createHVFillGridData()); - if (text != null) - group.setText(text); - group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); - return group; - } - - public static GridData createHVFillGridData() { - return createHVFillGridData(1); - } - - public static GridData createHVFillGridData(int span) { - final GridData gd= createGridData(0, 0, true, true); - gd.horizontalSpan= span; - return gd; - } - - - /** + final PreferenceLinkArea area = new PreferenceLinkArea(parent, SWT.NONE, pageId, text, container, null); + return area; + } + + public static GridData createGridData(int width, int height, boolean hFill, boolean vFill) { + return createGridData(width, height, hFill ? SWT.FILL : SWT.BEGINNING, vFill ? SWT.FILL : SWT.CENTER, hFill, vFill); + } + + public static GridData createGridData(int width, int height, int hAlign, int vAlign, boolean hGrab, boolean vGrab) { + final GridData gd= new GridData(hAlign, vAlign, hGrab, vGrab); + gd.widthHint= width; + gd.heightHint= height; + return gd; + } + + public static GridData createHFillGridData() { + return createHFillGridData(1); + } + + public static GridData createHFillGridData(int span) { + final GridData gd= createGridData(0, SWT.DEFAULT, SWT.FILL, SWT.CENTER, true, false); + gd.horizontalSpan= span; + return gd; + } + + public static Composite createHFillComposite(Composite parent, int margins) { + return createHFillComposite(parent, margins, 1); + } + + public static Composite createHFillComposite(Composite parent, int margins, int columns) { + final Composite composite= new Composite(parent, SWT.NONE); + composite.setFont(parent.getFont()); + composite.setLayoutData(createHFillGridData()); + composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); + return composite; + } + + public static Composite createHVFillComposite(Composite parent, int margins) { + return createHVFillComposite(parent, margins, 1); + } + + public static Composite createHVFillComposite(Composite parent, int margins, int columns) { + final Composite composite= new Composite(parent, SWT.NONE); + composite.setFont(parent.getFont()); + composite.setLayoutData(createHVFillGridData()); + composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); + return composite; + } + + + public static Group createHFillGroup(Composite parent, String text, int margins) { + return createHFillGroup(parent, text, margins, 1); + } + + public static Group createHFillGroup(Composite parent, String text, int margins, int rows) { + final Group group= new Group(parent, SWT.NONE); + group.setFont(parent.getFont()); + group.setLayoutData(createHFillGridData()); + if (text != null) + group.setText(text); + group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); + return group; + } + + public static Group createHVFillGroup(Composite parent, String text, int margins) { + return createHVFillGroup(parent, text, margins, 1); + } + + public static Group createHVFillGroup(Composite parent, String text, int margins, int rows) { + final Group group= new Group(parent, SWT.NONE); + group.setFont(parent.getFont()); + group.setLayoutData(createHVFillGridData()); + if (text != null) + group.setText(text); + group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); + return group; + } + + public static GridData createHVFillGridData() { + return createHVFillGridData(1); + } + + public static GridData createHVFillGridData(int span) { + final GridData gd= createGridData(0, 0, true, true); + gd.horizontalSpan= span; + return gd; + } + + + /** * Create a grid layout with the specified number of columns and the * standard spacings. * @@ -133,96 +133,96 @@ public class SWTUtils { * <code>MARGINS_NONE</code> or <code>MARGINS_DIALOG</code>. * @return the grid layout */ - public static GridLayout createGridLayout(int numColumns, PixelConverter converter, int margins) { - Assert.isTrue(margins == MARGINS_DEFAULT || margins == MARGINS_NONE || margins == MARGINS_DIALOG); - - final GridLayout layout= new GridLayout(numColumns, false); - layout.horizontalSpacing= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.verticalSpacing= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - - switch (margins) { - case MARGINS_NONE: - layout.marginLeft= layout.marginRight= 0; - layout.marginTop= layout.marginBottom= 0; - break; - case MARGINS_DIALOG: - layout.marginLeft= layout.marginRight= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.marginTop= layout.marginBottom= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - break; - case MARGINS_DEFAULT: - layout.marginLeft= layout.marginRight= layout.marginWidth; - layout.marginTop= layout.marginBottom= layout.marginHeight; - } - layout.marginWidth= layout.marginHeight= 0; - return layout; - } - - - public static Label createLabel(Composite parent, String message) { - return createLabel(parent, message, 1); - } - - public static Label createLabel(Composite parent, String message, int span) { - final Label label= new Label(parent, SWT.WRAP); - if (message != null) - label.setText(message); - label.setLayoutData(createHFillGridData(span)); - return label; - } - - public static Button createCheckBox(Composite parent, String message) { - return createCheckBox(parent, message, 1); - } - - public static Button createCheckBox(Composite parent, String message, int span) { - final Button button= new Button(parent, SWT.CHECK); - button.setText(message); - button.setLayoutData(createHFillGridData(span)); - return button; - } - - public static Button createRadioButton(Composite parent, String message) { - return createRadioButton(parent, message, 1); - } - - public static Button createRadioButton(Composite parent, String message, int span) { - final Button button= new Button(parent, SWT.RADIO); - button.setText(message); - button.setLayoutData(createHFillGridData(span)); - return button; - } - - - public static Text createText(Composite parent) { - return createText(parent, 1); - } - - public static Text createText(Composite parent, int span) { - final Text text= new Text(parent, SWT.SINGLE | SWT.BORDER); - text.setLayoutData(createHFillGridData(span)); - return text; - } - - - public static Control createPlaceholder(Composite parent, int heightInChars, int span) { - Assert.isTrue(heightInChars > 0); - final Control placeHolder= new Composite(parent, SWT.NONE); - final GridData gd= new GridData(SWT.BEGINNING, SWT.TOP, false, false); - gd.heightHint= new PixelConverter(parent).convertHeightInCharsToPixels(heightInChars); - gd.horizontalSpan= span; - placeHolder.setLayoutData(gd); - return placeHolder; - } - - - public static Control createPlaceholder(Composite parent, int heightInChars) { - return createPlaceholder(parent, heightInChars, 1); - } - - public static PixelConverter createDialogPixelConverter(Control control) { - Dialog.applyDialogFont(control); - return new PixelConverter(control); - } + public static GridLayout createGridLayout(int numColumns, PixelConverter converter, int margins) { + Assert.isTrue(margins == MARGINS_DEFAULT || margins == MARGINS_NONE || margins == MARGINS_DIALOG); + + final GridLayout layout= new GridLayout(numColumns, false); + layout.horizontalSpacing= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.verticalSpacing= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + + switch (margins) { + case MARGINS_NONE: + layout.marginLeft= layout.marginRight= 0; + layout.marginTop= layout.marginBottom= 0; + break; + case MARGINS_DIALOG: + layout.marginLeft= layout.marginRight= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.marginTop= layout.marginBottom= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + break; + case MARGINS_DEFAULT: + layout.marginLeft= layout.marginRight= layout.marginWidth; + layout.marginTop= layout.marginBottom= layout.marginHeight; + } + layout.marginWidth= layout.marginHeight= 0; + return layout; + } + + + public static Label createLabel(Composite parent, String message) { + return createLabel(parent, message, 1); + } + + public static Label createLabel(Composite parent, String message, int span) { + final Label label= new Label(parent, SWT.WRAP); + if (message != null) + label.setText(message); + label.setLayoutData(createHFillGridData(span)); + return label; + } + + public static Button createCheckBox(Composite parent, String message) { + return createCheckBox(parent, message, 1); + } + + public static Button createCheckBox(Composite parent, String message, int span) { + final Button button= new Button(parent, SWT.CHECK); + button.setText(message); + button.setLayoutData(createHFillGridData(span)); + return button; + } + + public static Button createRadioButton(Composite parent, String message) { + return createRadioButton(parent, message, 1); + } + + public static Button createRadioButton(Composite parent, String message, int span) { + final Button button= new Button(parent, SWT.RADIO); + button.setText(message); + button.setLayoutData(createHFillGridData(span)); + return button; + } + + + public static Text createText(Composite parent) { + return createText(parent, 1); + } + + public static Text createText(Composite parent, int span) { + final Text text= new Text(parent, SWT.SINGLE | SWT.BORDER); + text.setLayoutData(createHFillGridData(span)); + return text; + } + + + public static Control createPlaceholder(Composite parent, int heightInChars, int span) { + Assert.isTrue(heightInChars > 0); + final Control placeHolder= new Composite(parent, SWT.NONE); + final GridData gd= new GridData(SWT.BEGINNING, SWT.TOP, false, false); + gd.heightHint= new PixelConverter(parent).convertHeightInCharsToPixels(heightInChars); + gd.horizontalSpan= span; + placeHolder.setLayoutData(gd); + return placeHolder; + } + + + public static Control createPlaceholder(Composite parent, int heightInChars) { + return createPlaceholder(parent, heightInChars, 1); + } + + public static PixelConverter createDialogPixelConverter(Control control) { + Dialog.applyDialogFont(control); + return new PixelConverter(control); + } public static int calculateControlSize(PixelConverter converter, Control [] controls) { return calculateControlSize(converter, controls, 0, controls.length - 1); diff --git a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/ui/UserInfoPrompter.java b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/ui/UserInfoPrompter.java index 85791a697..c22515f2c 100644 --- a/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/ui/UserInfoPrompter.java +++ b/bundles/org.eclipse.jsch.ui/src/org/eclipse/jsch/ui/UserInfoPrompter.java @@ -40,227 +40,227 @@ import com.jcraft.jsch.UserInfo; */ public class UserInfoPrompter implements UserInfo, UIKeyboardInteractive{ - private String passphrase; - private String password; - private final Session session; - private int attemptCount; + private String passphrase; + private String password; + private final Session session; + private int attemptCount; - /** - * Create a prompter for the given session. This constructor will associate - * this prompter with the session using {@link Session#setUserInfo(UserInfo)}. - * - * @param session - * the session - */ - public UserInfoPrompter(Session session){ - super(); - this.session=session; - session.setUserInfo(this); - } + /** + * Create a prompter for the given session. This constructor will associate + * this prompter with the session using {@link Session#setUserInfo(UserInfo)}. + * + * @param session + * the session + */ + public UserInfoPrompter(Session session){ + super(); + this.session=session; + session.setUserInfo(this); + } - /** - * Return the session to which this prompter is assigned. - * - * @return the session to which this prompter is assigned - */ - public Session getSession(){ - return session; - } + /** + * Return the session to which this prompter is assigned. + * + * @return the session to which this prompter is assigned + */ + public Session getSession(){ + return session; + } - @Override + @Override public String getPassphrase(){ - return passphrase; - } + return passphrase; + } - @Override + @Override public String getPassword(){ - return password; - } + return password; + } - /** - * Set the pass phrase to be used when connecting the session. Return - * <code>null</code> if the pass phrase is not known. - * - * @param passphrase - * the pass phrase to be used when connecting the session or - * <code>null</code> - */ - public void setPassphrase(String passphrase){ - this.passphrase=passphrase; - } + /** + * Set the pass phrase to be used when connecting the session. Return + * <code>null</code> if the pass phrase is not known. + * + * @param passphrase + * the pass phrase to be used when connecting the session or + * <code>null</code> + */ + public void setPassphrase(String passphrase){ + this.passphrase=passphrase; + } - /** - * Set the password to be used when connecting the session. Return - * <code>null</code> if the password is not known. - * - * @param password - * the password to be used when connecting the session or - * <code>null</code> - */ - public void setPassword(String password){ - this.password=password; - } + /** + * Set the password to be used when connecting the session. Return + * <code>null</code> if the password is not known. + * + * @param password + * the password to be used when connecting the session or + * <code>null</code> + */ + public void setPassword(String password){ + this.password=password; + } - @Override + @Override public boolean promptPassphrase(String message){ - String _passphrase=promptSecret(message); - if(_passphrase!=null){ - setPassphrase(_passphrase); - } - return _passphrase!=null; - } + String _passphrase=promptSecret(message); + if(_passphrase!=null){ + setPassphrase(_passphrase); + } + return _passphrase!=null; + } - @Override + @Override public boolean promptPassword(String message){ - String _password=promptSecret(message); - if(_password!=null){ - setPassword(_password); - } - return _password!=null; - } + String _password=promptSecret(message); + if(_password!=null){ + setPassword(_password); + } + return _password!=null; + } - private String promptSecret(final String message){ - // ask the user for a password - final String[] result=new String[1]; - Display display=Display.getCurrent(); - if(display!=null){ - result[0]=promptForPassword(message); - } - else{ - // sync exec in default thread + private String promptSecret(final String message){ + // ask the user for a password + final String[] result=new String[1]; + Display display=Display.getCurrent(); + if(display!=null){ + result[0]=promptForPassword(message); + } + else{ + // sync exec in default thread Display.getDefault().syncExec(() -> result[0] = promptForPassword(message)); - } + } - if(result[0]==null){ - throw new OperationCanceledException(); - } - return result[0]; - } + if(result[0]==null){ + throw new OperationCanceledException(); + } + return result[0]; + } - /* package */String promptForPassword(final String message){ - String username=getSession().getUserName(); - UserValidationDialog dialog=new UserValidationDialog(null, null, - (username==null) ? "" : username, message); //$NON-NLS-1$ - dialog.setUsernameMutable(false); - dialog.open(); - return dialog.getPassword(); - } + /* package */String promptForPassword(final String message){ + String username=getSession().getUserName(); + UserValidationDialog dialog=new UserValidationDialog(null, null, + (username==null) ? "" : username, message); //$NON-NLS-1$ + dialog.setUsernameMutable(false); + dialog.open(); + return dialog.getPassword(); + } - @Override + @Override public String[] promptKeyboardInteractive(String destination, String name, - String instruction, String[] prompt, boolean[] echo){ - if(prompt.length==0){ - // No need to prompt, just return an empty String array - return new String[0]; - } - try{ - if(attemptCount==0&&password!=null&&prompt.length==1 - &&prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ - // Return the provided password the first time but always prompt on - // subsequent tries - attemptCount++; - return new String[] {password}; - } - String[] result=promptForKeyboradInteractiveInUI(destination, name, - instruction, prompt, echo); - if(result==null) - return null; // canceled - if(result.length==1&&prompt.length==1 - &&prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ - password=result[0]; - } - attemptCount++; - return result; - } - catch(OperationCanceledException e){ - return null; - } - } + String instruction, String[] prompt, boolean[] echo){ + if(prompt.length==0){ + // No need to prompt, just return an empty String array + return new String[0]; + } + try{ + if(attemptCount==0&&password!=null&&prompt.length==1 + &&prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ + // Return the provided password the first time but always prompt on + // subsequent tries + attemptCount++; + return new String[] {password}; + } + String[] result=promptForKeyboradInteractiveInUI(destination, name, + instruction, prompt, echo); + if(result==null) + return null; // canceled + if(result.length==1&&prompt.length==1 + &&prompt[0].trim().equalsIgnoreCase("password:")){ //$NON-NLS-1$ + password=result[0]; + } + attemptCount++; + return result; + } + catch(OperationCanceledException e){ + return null; + } + } - private String[] promptForKeyboradInteractiveInUI(final String destination, - final String name, final String instruction, final String[] prompt, - final boolean[] echo){ - final String[][] result=new String[1][]; - Display display=Display.getCurrent(); - if(display!=null){ - result[0]=internalPromptForUserInteractive(destination, name, - instruction, prompt, echo); - } - else{ - // sync exec in default thread + private String[] promptForKeyboradInteractiveInUI(final String destination, + final String name, final String instruction, final String[] prompt, + final boolean[] echo){ + final String[][] result=new String[1][]; + Display display=Display.getCurrent(); + if(display!=null){ + result[0]=internalPromptForUserInteractive(destination, name, + instruction, prompt, echo); + } + else{ + // sync exec in default thread Display.getDefault().syncExec( () -> result[0] = internalPromptForUserInteractive(destination, name, instruction, prompt, echo)); - } - return result[0]; - } + } + return result[0]; + } - /* package */ String[] internalPromptForUserInteractive(String destination, - String name, String instruction, String[] prompt, boolean[] echo){ - String domain=null; - String userName=getSession().getUserName(); - KeyboardInteractiveDialog dialog=new KeyboardInteractiveDialog(null, - domain, destination, name, userName, instruction, prompt, echo); - dialog.open(); - String[] _result=dialog.getResult(); - return _result; - } + /* package */ String[] internalPromptForUserInteractive(String destination, + String name, String instruction, String[] prompt, boolean[] echo){ + String domain=null; + String userName=getSession().getUserName(); + KeyboardInteractiveDialog dialog=new KeyboardInteractiveDialog(null, + domain, destination, name, userName, instruction, prompt, echo); + dialog.open(); + String[] _result=dialog.getResult(); + return _result; + } - @Override + @Override public boolean promptYesNo(String question){ - int prompt=prompt(MessageDialog.QUESTION, Messages.UserInfoPrompter_0, - question, new int[] {IDialogConstants.YES_ID, IDialogConstants.NO_ID}, - 0 // yes - // the - // default - ); - return prompt==0; - } + int prompt=prompt(MessageDialog.QUESTION, Messages.UserInfoPrompter_0, + question, new int[] {IDialogConstants.YES_ID, IDialogConstants.NO_ID}, + 0 // yes + // the + // default + ); + return prompt==0; + } - @Override + @Override public void showMessage(String message){ - prompt(MessageDialog.INFORMATION, Messages.UserInfoPrompter_1, message, - new int[] {IDialogConstants.OK_ID}, 0); - } + prompt(MessageDialog.INFORMATION, Messages.UserInfoPrompter_1, message, + new int[] {IDialogConstants.OK_ID}, 0); + } - private int prompt(final int promptType, final String title, - final String message, final int[] promptResponses, - final int defaultResponse){ - final Display display=getStandardDisplay(); - final int[] retval=new int[1]; - final String[] buttons=new String[promptResponses.length]; - for(int i=0; i<promptResponses.length; i++){ - int prompt=promptResponses[i]; - switch(prompt){ - case IDialogConstants.OK_ID: - buttons[i]=IDialogConstants.OK_LABEL; - break; - case IDialogConstants.CANCEL_ID: - buttons[i]=IDialogConstants.CANCEL_LABEL; - break; - case IDialogConstants.NO_ID: - buttons[i]=IDialogConstants.NO_LABEL; - break; - case IDialogConstants.YES_ID: - buttons[i]=IDialogConstants.YES_LABEL; - break; - } - } + private int prompt(final int promptType, final String title, + final String message, final int[] promptResponses, + final int defaultResponse){ + final Display display=getStandardDisplay(); + final int[] retval=new int[1]; + final String[] buttons=new String[promptResponses.length]; + for(int i=0; i<promptResponses.length; i++){ + int prompt=promptResponses[i]; + switch(prompt){ + case IDialogConstants.OK_ID: + buttons[i]=IDialogConstants.OK_LABEL; + break; + case IDialogConstants.CANCEL_ID: + buttons[i]=IDialogConstants.CANCEL_LABEL; + break; + case IDialogConstants.NO_ID: + buttons[i]=IDialogConstants.NO_LABEL; + break; + case IDialogConstants.YES_ID: + buttons[i]=IDialogConstants.YES_LABEL; + break; + } + } display.syncExec(() -> { - final MessageDialog dialog=new MessageDialog(new Shell(display), title, - null /* title image */, message, promptType, buttons, - defaultResponse); - retval[0]=dialog.open(); + final MessageDialog dialog=new MessageDialog(new Shell(display), title, + null /* title image */, message, promptType, buttons, + defaultResponse); + retval[0]=dialog.open(); }); - return retval[0]; - } + return retval[0]; + } - private Display getStandardDisplay(){ - Display display=Display.getCurrent(); - if(display==null){ - display=Display.getDefault(); - } - return display; - } + private Display getStandardDisplay(){ + Display display=Display.getCurrent(); + if(display==null){ + display=Display.getDefault(); + } + return display; + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IFileContentManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IFileContentManager.java index e8c63f69c..bbc9a275c 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IFileContentManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IFileContentManager.java @@ -46,145 +46,145 @@ import org.eclipse.core.resources.IStorage; */ public interface IFileContentManager { - /** - * Get the content type for a given instance of <code>IStorage</code>. User-defined mappings - * take precedence over plugin-contributed mappings; further, mappings for the entire file name - * take precedence over mappings for the file extension only. - * - * @param storage the instance of <code>IStorage</code>. - * @return one of <code>Team.UNKNOWN</code>, <code>Team.TEXT</code> or <code>Team.BINARY</code>. - * - * @since 3.1 - */ - int getType(IStorage storage); - - /** - * Check whether the given file name is assigned to a specific type in the content type registry. - * @param filename the file name to check for - * @return True if the file name is registered in the system and assigned to a content type, false - * if the file name is unknown. - * - * @since 3.1 - */ - boolean isKnownFilename(String filename); - - /** - * Check whether the given file extension is assigned to a specific type in the content type registry. - * @param extension the extension to check for - * @return True if the extension is registered in the system and assigned to a content type, false - * if the extension is unknown. - * - * @since 3.1 - */ - boolean isKnownExtension(String extension); - - /** - * Get the content type for a given file name. - * @param filename The file name - * @return one of <code>Team.UNKNOWN</code>, <code>Team.TEXT</code> or <code>Team.BINARY</code>. - * - * @since 3.1 - */ - int getTypeForName(String filename); - - /** - * Get the content type for a given file extension. - * @param extension The extension - * @return one of <code>Team.UNKNOWN</code>, <code>Team.TEXT</code> or <code>Team.BINARY</code>. - * - * @since 3.1 - */ - int getTypeForExtension(String extension); - - /** - * Map a set of file names to a set of content types and save the mappings in - * the preferences. Already existing mappings for these file names are updated - * with the new ones, other mappings will be preserved. - * - * @param names The file names - * @param types The corresponding types, each one being one of - * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or - * <code>Team.BINARY</code>. - * - * @since 3.1 - */ - void addNameMappings(String[] names, int[] types); - - /** - * Map a set of file extensions to a set of content types and save the mapping in - * the preferences. Already existing mappings for these extensions are updated - * with the new ones, other mappings will be preserved. - * - * @param extensions The extensions - * @param types The corresponding types, each one being one of - * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or - * <code>Team.BINARY</code>. - * - * @since 3.1 - */ - void addExtensionMappings(String[] extensions, int[] types); - - /** - * Map a set of file names to a set of content types and save the mappings in - * the preferences. All existing user-defined mappings for <b>any - * </b> file names are deleted and replaced by the new ones. - * - * @param names The file names - * @param types The corresponding types, each one being one of - * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or - * <code>Team.BINARY</code>. - * - * @since 3.1 - */ - void setNameMappings(String[] names, int[] types); - - /** - * Map a set of file extensions to a set of content types and save the - * mapping in the preferences. All existing user-defined mappings for <b>any - * </b> file extensions are deleted and replaced by the new ones. - * - * @param extensions The extensions - * @param types The corresponding types, each one being one of - * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or - * <code>Team.BINARY</code>. - * - * @since 3.1 - */ - void setExtensionMappings(String[] extensions, int[] types); - - /** - * Get all the currently defined mappings from file names to content types. - * - * @return the mappings - * - * @since 3.1 - */ - IStringMapping [] getNameMappings(); - - /** - * Get all the currently defined mappings from file names to content types. - * - * @return the mappings - * - * @since 3.1 - */ - IStringMapping [] getExtensionMappings(); - - /** - * Get all the plugin-contributed mappings from file names to content types. - * - * @return the mappings - * - * @since 3.1 - */ - IStringMapping [] getDefaultNameMappings(); - - /** - * Get all the plugin-contributed mappings from file extensions to content types. - * - * @return the mappings - - * @since 3.1 - */ - IStringMapping [] getDefaultExtensionMappings(); + /** + * Get the content type for a given instance of <code>IStorage</code>. User-defined mappings + * take precedence over plugin-contributed mappings; further, mappings for the entire file name + * take precedence over mappings for the file extension only. + * + * @param storage the instance of <code>IStorage</code>. + * @return one of <code>Team.UNKNOWN</code>, <code>Team.TEXT</code> or <code>Team.BINARY</code>. + * + * @since 3.1 + */ + int getType(IStorage storage); + + /** + * Check whether the given file name is assigned to a specific type in the content type registry. + * @param filename the file name to check for + * @return True if the file name is registered in the system and assigned to a content type, false + * if the file name is unknown. + * + * @since 3.1 + */ + boolean isKnownFilename(String filename); + + /** + * Check whether the given file extension is assigned to a specific type in the content type registry. + * @param extension the extension to check for + * @return True if the extension is registered in the system and assigned to a content type, false + * if the extension is unknown. + * + * @since 3.1 + */ + boolean isKnownExtension(String extension); + + /** + * Get the content type for a given file name. + * @param filename The file name + * @return one of <code>Team.UNKNOWN</code>, <code>Team.TEXT</code> or <code>Team.BINARY</code>. + * + * @since 3.1 + */ + int getTypeForName(String filename); + + /** + * Get the content type for a given file extension. + * @param extension The extension + * @return one of <code>Team.UNKNOWN</code>, <code>Team.TEXT</code> or <code>Team.BINARY</code>. + * + * @since 3.1 + */ + int getTypeForExtension(String extension); + + /** + * Map a set of file names to a set of content types and save the mappings in + * the preferences. Already existing mappings for these file names are updated + * with the new ones, other mappings will be preserved. + * + * @param names The file names + * @param types The corresponding types, each one being one of + * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or + * <code>Team.BINARY</code>. + * + * @since 3.1 + */ + void addNameMappings(String[] names, int[] types); + + /** + * Map a set of file extensions to a set of content types and save the mapping in + * the preferences. Already existing mappings for these extensions are updated + * with the new ones, other mappings will be preserved. + * + * @param extensions The extensions + * @param types The corresponding types, each one being one of + * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or + * <code>Team.BINARY</code>. + * + * @since 3.1 + */ + void addExtensionMappings(String[] extensions, int[] types); + + /** + * Map a set of file names to a set of content types and save the mappings in + * the preferences. All existing user-defined mappings for <b>any + * </b> file names are deleted and replaced by the new ones. + * + * @param names The file names + * @param types The corresponding types, each one being one of + * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or + * <code>Team.BINARY</code>. + * + * @since 3.1 + */ + void setNameMappings(String[] names, int[] types); + + /** + * Map a set of file extensions to a set of content types and save the + * mapping in the preferences. All existing user-defined mappings for <b>any + * </b> file extensions are deleted and replaced by the new ones. + * + * @param extensions The extensions + * @param types The corresponding types, each one being one of + * <code>Team.UNKNOWN</code>,<code>Team.TEXT</code> or + * <code>Team.BINARY</code>. + * + * @since 3.1 + */ + void setExtensionMappings(String[] extensions, int[] types); + + /** + * Get all the currently defined mappings from file names to content types. + * + * @return the mappings + * + * @since 3.1 + */ + IStringMapping [] getNameMappings(); + + /** + * Get all the currently defined mappings from file names to content types. + * + * @return the mappings + * + * @since 3.1 + */ + IStringMapping [] getExtensionMappings(); + + /** + * Get all the plugin-contributed mappings from file names to content types. + * + * @return the mappings + * + * @since 3.1 + */ + IStringMapping [] getDefaultNameMappings(); + + /** + * Get all the plugin-contributed mappings from file extensions to content types. + * + * @return the mappings + + * @since 3.1 + */ + IStringMapping [] getDefaultExtensionMappings(); } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IStringMapping.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IStringMapping.java index f62bbe399..ac54d1ddd 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IStringMapping.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/IStringMapping.java @@ -24,21 +24,21 @@ package org.eclipse.team.core; */ public interface IStringMapping { - /** - * The string part of the mapping - * - * @return the string - * - * @since 3.1 - */ - String getString(); + /** + * The string part of the mapping + * + * @return the string + * + * @since 3.1 + */ + String getString(); - /** - * The content type associated with the string - * - * @return the content type - * - * @since 3.1 - */ - int getType(); + /** + * The content type associated with the string + * + * @return the content type + * + * @since 3.1 + */ + int getType(); } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/ProjectSetCapability.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/ProjectSetCapability.java index e2a5c5e19..b6473385a 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/ProjectSetCapability.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/ProjectSetCapability.java @@ -244,9 +244,9 @@ public abstract class ProjectSetCapability { IProject eachProj = projects[i]; if (eachProj.exists()) { existingProjects.add(eachProj); - } else if (new File(eachProj.getParent().getLocation().toFile(), eachProj.getName()).exists()) { - existingProjects.add(eachProj); - } + } else if (new File(eachProj.getParent().getLocation().toFile(), eachProj.getName()).exists()) { + existingProjects.add(eachProj); + } } if (existingProjects.size() == 0) return projects; diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProvider.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProvider.java index d2f4c70f9..8e4ba1259 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProvider.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProvider.java @@ -100,8 +100,8 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { // lock to ensure that map/unmap and getProvider support concurrency private static final ILock mappingLock = Job.getJobManager().newLock(); - // Session property used to identify projects that are not mapped - private static final Object NOT_MAPPED = new Object(); + // Session property used to identify projects that are not mapped + private static final Object NOT_MAPPED = new Object(); /** * Instantiate a new RepositoryProvider with concrete class by given providerID @@ -330,10 +330,10 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { */ private static RepositoryProvider lookupProviderProp(IProject project) throws CoreException { Object provider = project.getSessionProperty(TeamPlugin.PROVIDER_PROP_KEY); - if (provider instanceof RepositoryProvider) { - return (RepositoryProvider) provider; - } - return null; + if (provider instanceof RepositoryProvider) { + return (RepositoryProvider) provider; + } + return null; } @@ -394,12 +394,12 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { /** * Returns an <code>IFileModificationValidator</code> for pre-checking operations - * that modify the contents of files. - * Returns <code>null</code> if the provider does not wish to participate in - * file modification validation. + * that modify the contents of files. + * Returns <code>null</code> if the provider does not wish to participate in + * file modification validation. * @return an <code>IFileModificationValidator</code> for pre-checking operations - * that modify the contents of files - * + * that modify the contents of files + * * @see org.eclipse.core.resources.IFileModificationValidator * @deprecated use {@link #getFileModificationValidator2()} */ @@ -460,7 +460,7 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { * @since 3.2 */ public IFileHistoryProvider getFileHistoryProvider(){ - return null; + return null; } /** @@ -532,10 +532,10 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { RepositoryProvider provider = lookupProviderProp(project); if(provider != null) return provider; - // Do a quick check to see it the project is known to be unshared. - // This is done to avoid accessing the persistent property store - if (isMarkedAsUnshared(project)) - return null; + // Do a quick check to see it the project is known to be unshared. + // This is done to avoid accessing the persistent property store + if (isMarkedAsUnshared(project)) + return null; // ----------------------------- //Next, check if it has the ID as a persistent property, if yes then instantiate provider @@ -603,10 +603,10 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { return null; } } - // Do a quick check to see it the project is known to be unshared. - // This is done to avoid accessing the persistent property store - if (isMarkedAsUnshared(project)) - return null; + // Do a quick check to see it the project is known to be unshared. + // This is done to avoid accessing the persistent property store + if (isMarkedAsUnshared(project)) + return null; // There isn't one so check the persistent property String existingID = project.getPersistentProperty(TeamPlugin.PROVIDER_PROP_KEY); @@ -666,14 +666,14 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { if (!project.isAccessible()) return false; try { if (lookupProviderProp(project) != null) return true; - // Do a quick check to see it the project is known to be unshared. - // This is done to avoid accessing the persistent property store - if (isMarkedAsUnshared(project)) - return false; + // Do a quick check to see it the project is known to be unshared. + // This is done to avoid accessing the persistent property store + if (isMarkedAsUnshared(project)) + return false; boolean shared = project.getPersistentProperty(TeamPlugin.PROVIDER_PROP_KEY) != null; - if (!shared) - markAsUnshared(project); - return shared; + if (!shared) + markAsUnshared(project); + return shared; } catch (CoreException e) { TeamPlugin.log(e); return false; @@ -681,20 +681,20 @@ public abstract class RepositoryProvider implements IProjectNature, IAdaptable { } private static boolean isMarkedAsUnshared(IProject project) { - try { - return project.getSessionProperty(TeamPlugin.PROVIDER_PROP_KEY) == NOT_MAPPED; - } catch (CoreException e) { - return false; - } - } - - private static void markAsUnshared(IProject project) { - try { - project.setSessionProperty(TeamPlugin.PROVIDER_PROP_KEY, NOT_MAPPED); - } catch (CoreException e) { - // Just ignore the error as this is just an optimization - } - } + try { + return project.getSessionProperty(TeamPlugin.PROVIDER_PROP_KEY) == NOT_MAPPED; + } catch (CoreException e) { + return false; + } + } + + private static void markAsUnshared(IProject project) { + try { + project.setSessionProperty(TeamPlugin.PROVIDER_PROP_KEY, NOT_MAPPED); + } catch (CoreException e) { + // Just ignore the error as this is just an optimization + } + } @Override public IProject getProject() { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProviderType.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProviderType.java index 219100a99..62ca83791 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProviderType.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/RepositoryProviderType.java @@ -233,9 +233,9 @@ public abstract class RepositoryProviderType extends PlatformObject { * or in any way modify workspace resources (including auto-sharing the project). However, * auto-sharing (or other modification) could be performed by a background job scheduled from * this callback. - * - * @since 3.1 - * + * + * @since 3.1 + * * @param project the project that contains the detected meta-files. * @param containers the folders (possibly including the project folder) in which meta-files were found */ diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/Team.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/Team.java index 480c90177..d65e49f24 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/Team.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/Team.java @@ -65,25 +65,25 @@ import org.eclipse.team.internal.core.importing.BundleImporterExtension; */ public final class Team { - private static class StringMappingWrapper implements IFileTypeInfo { + private static class StringMappingWrapper implements IFileTypeInfo { - private final IStringMapping fMapping; + private final IStringMapping fMapping; - public StringMappingWrapper(IStringMapping mapping) { - fMapping= mapping; - } + public StringMappingWrapper(IStringMapping mapping) { + fMapping= mapping; + } - @Override + @Override public String getExtension() { - return fMapping.getString(); - } + return fMapping.getString(); + } - @Override + @Override public int getType() { - return fMapping.getType(); - } + return fMapping.getType(); + } - } + } private static final String PREF_TEAM_IGNORES = "ignore_files"; //$NON-NLS-1$ private static final String PREF_TEAM_SEPARATOR = "\n"; //$NON-NLS-1$ @@ -99,19 +99,19 @@ public final class Team { protected static SortedMap<String, Boolean> globalIgnore, pluginIgnore; private static StringMatcher[] ignoreMatchers; - private final static FileContentManager fFileContentManager; + private final static FileContentManager fFileContentManager; private static List<IBundleImporter> fBundleImporters; - static { - fFileContentManager= new FileContentManager(); - } + static { + fFileContentManager= new FileContentManager(); + } /** - * Return the type of the given IStorage. First, we check whether a mapping has - * been defined for the name of the IStorage. If this is not the case, we check for - * a mapping with the extension. If no mapping is defined, UNKNOWN is returned. + * Return the type of the given IStorage. First, we check whether a mapping has + * been defined for the name of the IStorage. If this is not the case, we check for + * a mapping with the extension. If no mapping is defined, UNKNOWN is returned. * * Valid return values are: * Team.TEXT @@ -120,12 +120,12 @@ public final class Team { * * @param storage the IStorage * @return whether the given IStorage is TEXT, BINARY, or UNKNOWN - * - * @deprecated Use <code>getFileContentManager().getType(IStorage storage)</code> instead. + * + * @deprecated Use <code>getFileContentManager().getType(IStorage storage)</code> instead. */ @Deprecated public static int getType(IStorage storage) { - return fFileContentManager.getType(storage); + return fFileContentManager.getType(storage); } /** @@ -179,19 +179,19 @@ public final class Team { /** - * Return all known file types. + * Return all known file types. * * @return all known file types - * @deprecated Use <code>getFileContentManager().getExtensionMappings()</code> instead. + * @deprecated Use <code>getFileContentManager().getExtensionMappings()</code> instead. */ @Deprecated public static IFileTypeInfo[] getAllTypes() { - final IStringMapping [] mappings= fFileContentManager.getExtensionMappings(); - final IFileTypeInfo [] infos= new IFileTypeInfo[mappings.length]; - for (int i = 0; i < infos.length; i++) { - infos[i]= new StringMappingWrapper(mappings[i]); - } - return infos; + final IStringMapping [] mappings= fFileContentManager.getExtensionMappings(); + final IFileTypeInfo [] infos= new IFileTypeInfo[mappings.length]; + for (int i = 0; i < infos.length; i++) { + infos[i]= new StringMappingWrapper(mappings[i]); + } + return infos; } /** @@ -262,8 +262,8 @@ public final class Team { /** - * Set the file type for the give extensions. This - * will replace the existing file types with this new list. + * Set the file type for the give extensions. This + * will replace the existing file types with this new list. * * Valid types are: * Team.TEXT @@ -272,12 +272,12 @@ public final class Team { * * @param extensions the file extensions * @param types the file types - * - * @deprecated Use <code>getFileContentManager().setExtensionMappings()</code> instead. + * + * @deprecated Use <code>getFileContentManager().setExtensionMappings()</code> instead. */ @Deprecated public static void setAllTypes(String[] extensions, int[] types) { - fFileContentManager.addExtensionMappings(extensions, types); + fFileContentManager.addExtensionMappings(extensions, types); } /** @@ -529,40 +529,40 @@ public final class Team { } /** - * TODO: change to file content manager + * TODO: change to file content manager * Return the default file type bindings * (i.e. those that are specified in * plugin manifests). * @return the default file type bindings * @since 3.0 - * @deprecated Use Team.getFileContentManager().getDefaultExtensionMappings() instead. + * @deprecated Use Team.getFileContentManager().getDefaultExtensionMappings() instead. */ @Deprecated public static IFileTypeInfo[] getDefaultTypes() { - return asFileTypeInfo(getFileContentManager().getDefaultExtensionMappings()); + return asFileTypeInfo(getFileContentManager().getDefaultExtensionMappings()); } - private static IFileTypeInfo [] asFileTypeInfo(IStringMapping [] mappings) { - final IFileTypeInfo [] infos= new IFileTypeInfo[mappings.length]; - for (int i = 0; i < infos.length; i++) { - infos[i]= new StringMappingWrapper(mappings[i]); - } - return infos; - } - - /** - * Get the file content manager which implements the API for manipulating the mappings between - * file names, file extensions and content types. - * - * @return an instance of IFileContentManager - * - * @see IFileContentManager - * - * @since 3.1 - */ - public static IFileContentManager getFileContentManager() { - return fFileContentManager; - } + private static IFileTypeInfo [] asFileTypeInfo(IStringMapping [] mappings) { + final IFileTypeInfo [] infos= new IFileTypeInfo[mappings.length]; + for (int i = 0; i < infos.length; i++) { + infos[i]= new StringMappingWrapper(mappings[i]); + } + return infos; + } + + /** + * Get the file content manager which implements the API for manipulating the mappings between + * file names, file extensions and content types. + * + * @return an instance of IFileContentManager + * + * @see IFileContentManager + * + * @since 3.1 + */ + public static IFileContentManager getFileContentManager() { + return fFileContentManager; + } /** * Creates a storage merger for the given content type. @@ -574,9 +574,9 @@ public final class Team { * * @since 3.4 */ - public static IStorageMerger createMerger(IContentType type) { - return StorageMergerRegistry.getInstance().createStreamMerger(type); - } + public static IStorageMerger createMerger(IContentType type) { + return StorageMergerRegistry.getInstance().createStreamMerger(type); + } /** * Creates a storage merger for the given file extension. @@ -588,9 +588,9 @@ public final class Team { * * @since 3.4 */ - public static IStorageMerger createMerger(String extension) { - return StorageMergerRegistry.getInstance().createStreamMerger(extension); - } + public static IStorageMerger createMerger(String extension) { + return StorageMergerRegistry.getInstance().createStreamMerger(extension); + } /** * Creates a storage merger for the given content type. @@ -602,10 +602,10 @@ public final class Team { * @deprecated Use {@link #createMerger(IContentType)} instead. * @since 3.2 */ - @Deprecated + @Deprecated public IStorageMerger createStorageMerger(IContentType type) { - return createMerger(type); - } + return createMerger(type); + } /** * Creates a storage merger for the given file extension. @@ -617,10 +617,10 @@ public final class Team { * @deprecated Use {@link #createMerger(String)} instead. * @since 3.2 */ - @Deprecated + @Deprecated public IStorageMerger createStorageMerger(String extension) { - return createMerger(extension); - } + return createMerger(extension); + } /** * Returns the available bundle importers. diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/TeamException.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/TeamException.java index 1a9cb6870..d97a47cb6 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/TeamException.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/TeamException.java @@ -32,10 +32,10 @@ import org.eclipse.team.internal.core.TeamPlugin; */ public class TeamException extends CoreException { - // Field required to avoid compiler warning + // Field required to avoid compiler warning private static final long serialVersionUID = 1L; - // The operation completed successfully. + // The operation completed successfully. public static final int OK = 0; // The operation failed because the resource is not checked-in. diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/history/IFileRevision.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/history/IFileRevision.java index a4bdf84c3..80fcc52ea 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/history/IFileRevision.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/history/IFileRevision.java @@ -102,8 +102,8 @@ public interface IFileRevision { * Returns the branches names of file revision. * * @return an array of ITag's if branch names exist for this revision - * or an empty ITag array if no names exist - * @since 3.6 + * or an empty ITag array if no names exist + * @since 3.6 */ public ITag[] getBranches(); diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IResourceMappingMerger.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IResourceMappingMerger.java index 36a95954f..1180d7bdf 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IResourceMappingMerger.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IResourceMappingMerger.java @@ -49,7 +49,7 @@ import org.eclipse.core.runtime.jobs.ISchedulingRule; */ public interface IResourceMappingMerger { - /** + /** * Attempt to automatically merge the mappings of the merge context(<code>MergeContext#getMappings()</code>). * The merge context provides access to the out-of-sync resources (<code>MergeContext#getSyncInfoTree()</code>) * associated with the mappings to be merged. The set of provided mappings @@ -86,48 +86,48 @@ public interface IResourceMappingMerger { * <code>MergeStatus#getConflictingMappings()</code> * @throws CoreException if errors occurred */ - public IStatus merge(IMergeContext mergeContext, - IProgressMonitor monitor) throws CoreException; + public IStatus merge(IMergeContext mergeContext, + IProgressMonitor monitor) throws CoreException; - /** - * Return the scheduling rule that is required to merge - * all the changes that apply to this merger in the given - * context. When calling {@link #merge(IMergeContext, IProgressMonitor)}, - * clients must ensure that they either have obtained - * a rule that covers the rule returned by this method or - * they must not hold any rule. - * @param context the context that contains the changes to be merged - * @return the scheduling rule required by this merger to merge all - * the changes in the given context belonging to the merger's - * model provider. - */ - public ISchedulingRule getMergeRule(IMergeContext context); + /** + * Return the scheduling rule that is required to merge + * all the changes that apply to this merger in the given + * context. When calling {@link #merge(IMergeContext, IProgressMonitor)}, + * clients must ensure that they either have obtained + * a rule that covers the rule returned by this method or + * they must not hold any rule. + * @param context the context that contains the changes to be merged + * @return the scheduling rule required by this merger to merge all + * the changes in the given context belonging to the merger's + * model provider. + */ + public ISchedulingRule getMergeRule(IMergeContext context); - /** - * Validate an auto-merge for the given context. This - * method must be invoked for all mergers involved - * in the merge before the auto-merge is attempted. - * The purpose of the validation is to indicate whether there - * are conditions in the merge context that make an auto-merge - * undesirable. The purpose is not to indicate that conflicts - * exist (this is done by the <code>merge</code> method) but instead - * to indicate that the nature of one of more incoming changes - * is such that performing an auto-merge may be undesirable. - * <p> - * Clients should validate before performing the merge and, if - * any of the returned status are not OK, should prompt the - * user to make them aware of the potential side effects. - * The user may still decide to attempt an auto-merge, in which case - * the client may still invoke the <code>merge</code> method. - * + /** + * Validate an auto-merge for the given context. This + * method must be invoked for all mergers involved + * in the merge before the auto-merge is attempted. + * The purpose of the validation is to indicate whether there + * are conditions in the merge context that make an auto-merge + * undesirable. The purpose is not to indicate that conflicts + * exist (this is done by the <code>merge</code> method) but instead + * to indicate that the nature of one of more incoming changes + * is such that performing an auto-merge may be undesirable. + * <p> + * Clients should validate before performing the merge and, if + * any of the returned status are not OK, should prompt the + * user to make them aware of the potential side effects. + * The user may still decide to attempt an auto-merge, in which case + * the client may still invoke the <code>merge</code> method. + * * @param mergeContext a context that provides access to the resources * involved in the merge. The context must not be * <code>null</code>. * @param monitor a progress monitor - * @return a status indicating any potential side effects of - * performing an auto-merge. - */ - public IStatus validateMerge(IMergeContext mergeContext, - IProgressMonitor monitor); + * @return a status indicating any potential side effects of + * performing an auto-merge. + */ + public IStatus validateMerge(IMergeContext mergeContext, + IProgressMonitor monitor); } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IStorageMerger.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IStorageMerger.java index 5fcbdd1c0..53d3327ab 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IStorageMerger.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/IStorageMerger.java @@ -33,46 +33,46 @@ import org.eclipse.core.runtime.IStatus; */ public interface IStorageMerger { - /** - * Indicates the successful completion of the merge operation (value <code>IStatus.OK</code>) - */ - public static final int OK= IStatus.OK; + /** + * Indicates the successful completion of the merge operation (value <code>IStatus.OK</code>) + */ + public static final int OK= IStatus.OK; - /** - * Indicates that a change conflict prevented the merge from successful completion (value <code>1</code>) - */ - public static final int CONFLICT= 1; + /** + * Indicates that a change conflict prevented the merge from successful completion (value <code>1</code>) + */ + public static final int CONFLICT= 1; - /** - * Status code describing an internal error (value <code>2</code>) - */ - public static final int INTERNAL_ERROR= 2; + /** + * Status code describing an internal error (value <code>2</code>) + */ + public static final int INTERNAL_ERROR= 2; - /** - * Indicates that at least one of the encodings associated with the input was unsupported (value <code>3</code>) - */ - public static final int UNSUPPORTED_ENCODING= 3; + /** + * Indicates that at least one of the encodings associated with the input was unsupported (value <code>3</code>) + */ + public static final int UNSUPPORTED_ENCODING= 3; - /** - * Performs a merge operation on the given storage instances and writes the merge result to the output stream. - * On success a status <code>IStatus.OK</code> is returned, on error a status <code>IStatus.ERROR</code>. - * If the merge operation cannot deal with conflicts, the code of the error status has the value <code>IStreamMerger.CONFLICT</code>. - * For text oriented mergers the encoding for the input and output is honored if they implement - * {@link IEncodedStorage}. - * It is the responsibility of callers to close the output stream. - * <p> - * The provided ancestor may be <code>null</code> if this merger - * returns <code>true</code> from {@link #canMergeWithoutAncestor()}. - * - * @param output the byte stream to which the merge result is written; the merger will not close the stream - * @param outputEncoding the encoding to use when writing to the output stream - * @param ancestor the storage from which the common ancestor is read - * @param target the storage containing the target of the merge - * @param other the storage containing the target of the merge - * @param monitor reports progress of the merge operation - * @return returns the completion status of the operation - * @throws CoreException if an error occurs - */ + /** + * Performs a merge operation on the given storage instances and writes the merge result to the output stream. + * On success a status <code>IStatus.OK</code> is returned, on error a status <code>IStatus.ERROR</code>. + * If the merge operation cannot deal with conflicts, the code of the error status has the value <code>IStreamMerger.CONFLICT</code>. + * For text oriented mergers the encoding for the input and output is honored if they implement + * {@link IEncodedStorage}. + * It is the responsibility of callers to close the output stream. + * <p> + * The provided ancestor may be <code>null</code> if this merger + * returns <code>true</code> from {@link #canMergeWithoutAncestor()}. + * + * @param output the byte stream to which the merge result is written; the merger will not close the stream + * @param outputEncoding the encoding to use when writing to the output stream + * @param ancestor the storage from which the common ancestor is read + * @param target the storage containing the target of the merge + * @param other the storage containing the target of the merge + * @param monitor reports progress of the merge operation + * @return returns the completion status of the operation + * @throws CoreException if an error occurs + */ IStatus merge(OutputStream output, String outputEncoding, IStorage ancestor, IStorage target, IStorage other, IProgressMonitor monitor) throws CoreException; diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/ResourceMappingMerger.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/ResourceMappingMerger.java index 37ef3cbcd..b3c994661 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/ResourceMappingMerger.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/ResourceMappingMerger.java @@ -61,10 +61,10 @@ public abstract class ResourceMappingMerger implements IResourceMappingMerger { * changes in the context for the model provider of this merger. * By default, return a rule that covers all the projects for the mappings * that belong to the model provider of this merger. - * @param context the context that contains the changes to be merged - * @return the scheduling rule required by this merger to merge all - * the changes in the given context belonging to the merger's - * model provider. + * @param context the context that contains the changes to be merged + * @return the scheduling rule required by this merger to merge all + * the changes in the given context belonging to the merger's + * model provider. * @see org.eclipse.team.core.mapping.IResourceMappingMerger#getMergeRule(org.eclipse.team.core.mapping.IMergeContext) */ @Override diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeContext.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeContext.java index f30286846..5a29fe4ea 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeContext.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeContext.java @@ -79,11 +79,11 @@ public abstract class MergeContext extends SynchronizationContext implements IMe * @param type the type of synchronization (ONE_WAY or TWO_WAY) * @param deltaTree the sync info tree that contains all out-of-sync resources */ - protected MergeContext(ISynchronizationScopeManager manager, int type, IResourceDiffTree deltaTree) { - super(manager, type, deltaTree); - } + protected MergeContext(ISynchronizationScopeManager manager, int type, IResourceDiffTree deltaTree) { + super(manager, type, deltaTree); + } - @Override + @Override public void reject(final IDiff[] diffs, IProgressMonitor monitor) throws CoreException { run(monitor1 -> { for (int i = 0; i < diffs.length; i++) { @@ -91,9 +91,9 @@ public abstract class MergeContext extends SynchronizationContext implements IMe reject(node, monitor1); } }, getMergeRule(diffs), IResource.NONE, monitor); - } + } - @Override + @Override public void markAsMerged(final IDiff[] nodes, final boolean inSyncHint, IProgressMonitor monitor) throws CoreException { run(monitor1 -> { for (int i = 0; i < nodes.length; i++) { @@ -101,9 +101,9 @@ public abstract class MergeContext extends SynchronizationContext implements IMe markAsMerged(node, inSyncHint, monitor1); } }, getMergeRule(nodes), IResource.NONE, monitor); - } + } - @Override + @Override public IStatus merge(final IDiff[] deltas, final boolean force, IProgressMonitor monitor) throws CoreException { final List<IFile> failedFiles = new ArrayList<>(); run(monitor1 -> { @@ -129,7 +129,7 @@ public abstract class MergeContext extends SynchronizationContext implements IMe } else { return new MergeStatus(TeamPlugin.ID, Messages.MergeContext_0, failedFiles.toArray(new IFile[failedFiles.size()])); } - } + } @Override public IStatus merge(IDiff diff, boolean ignoreLocalChanges, IProgressMonitor monitor) throws CoreException { @@ -156,30 +156,30 @@ public abstract class MergeContext extends SynchronizationContext implements IMe } return Status.OK_STATUS; } - if (diff instanceof IThreeWayDiff && !ignoreLocalChanges && getMergeType() == THREE_WAY) { + if (diff instanceof IThreeWayDiff && !ignoreLocalChanges && getMergeType() == THREE_WAY) { IThreeWayDiff twDelta = (IThreeWayDiff) diff; - int direction = twDelta.getDirection(); - if (direction == IThreeWayDiff.OUTGOING) { - // There's nothing to do so return OK - return Status.OK_STATUS; - } - if (direction == IThreeWayDiff.INCOMING) { - // Just copy the stream since there are no conflicts - performReplace(diff, monitor); - return Status.OK_STATUS; - } + int direction = twDelta.getDirection(); + if (direction == IThreeWayDiff.OUTGOING) { + // There's nothing to do so return OK + return Status.OK_STATUS; + } + if (direction == IThreeWayDiff.INCOMING) { + // Just copy the stream since there are no conflicts + performReplace(diff, monitor); + return Status.OK_STATUS; + } // direction == SyncInfo.CONFLICTING - int type = twDelta.getKind(); - if (type == IDiff.REMOVE) { - makeInSync(diff, monitor); - return Status.OK_STATUS; - } + int type = twDelta.getKind(); + if (type == IDiff.REMOVE) { + makeInSync(diff, monitor); + return Status.OK_STATUS; + } // type == SyncInfo.CHANGE IResourceDiff remoteChange = (IResourceDiff)twDelta.getRemoteChange(); IFileRevision remote = null; - if (remoteChange != null) { - remote = remoteChange.getAfterState(); - } + if (remoteChange != null) { + remote = remoteChange.getAfterState(); + } if (remote == null || !getLocalFile(diff).exists()) { // Nothing we can do so return a conflict status // TODO: Should we handle the case where the local and remote have the same contents for a conflicting addition? @@ -187,11 +187,11 @@ public abstract class MergeContext extends SynchronizationContext implements IMe } // We have a conflict, a local, base and remote so we can do // a three-way merge - return performThreeWayMerge(twDelta, monitor); - } else { - performReplace(diff, monitor); - return Status.OK_STATUS; - } + return performThreeWayMerge(twDelta, monitor); + } else { + performReplace(diff, monitor); + return Status.OK_STATUS; + } } @@ -236,70 +236,70 @@ public abstract class MergeContext extends SynchronizationContext implements IMe status = new MergeStatus(status.getPlugin(), status.getMessage(), new IFile[]{file}); } result[0] = status; - } finally { - disposeTempOutputStream(file, os); - } - monitor1.done(); + } finally { + disposeTempOutputStream(file, os); + } + monitor1.done(); }, getMergeRule(diff), IWorkspace.AVOID_UPDATE, monitor); return result[0]; } - private void disposeTempOutputStream(IFile file, OutputStream output) { - if (output instanceof ByteArrayOutputStream) - return; - // We created a temporary file so we need to clean it up - try { - // First make sure the output stream is closed - // so that file deletion will not fail because of that. - if (output != null) - output.close(); - } catch (IOException e) { - // Ignore - } - File tmpFile = getTempFile(file); - if (tmpFile.exists()) - tmpFile.delete(); - } + private void disposeTempOutputStream(IFile file, OutputStream output) { + if (output instanceof ByteArrayOutputStream) + return; + // We created a temporary file so we need to clean it up + try { + // First make sure the output stream is closed + // so that file deletion will not fail because of that. + if (output != null) + output.close(); + } catch (IOException e) { + // Ignore + } + File tmpFile = getTempFile(file); + if (tmpFile.exists()) + tmpFile.delete(); + } - private OutputStream getTempOutputStream(IFile file) throws CoreException { - File tmpFile = getTempFile(file); - if (tmpFile.exists()) - tmpFile.delete(); - File parent = tmpFile.getParentFile(); - if (!parent.exists()) - parent.mkdirs(); - try { - return new BufferedOutputStream(new FileOutputStream(tmpFile)); - } catch (FileNotFoundException e) { - TeamPlugin.log(IStatus.ERROR, NLS.bind("Could not open temporary file {0} for writing: {1}", new String[] { tmpFile.getAbsolutePath(), e.getMessage() }), e); //$NON-NLS-1$ - return new ByteArrayOutputStream(); - } - } + private OutputStream getTempOutputStream(IFile file) throws CoreException { + File tmpFile = getTempFile(file); + if (tmpFile.exists()) + tmpFile.delete(); + File parent = tmpFile.getParentFile(); + if (!parent.exists()) + parent.mkdirs(); + try { + return new BufferedOutputStream(new FileOutputStream(tmpFile)); + } catch (FileNotFoundException e) { + TeamPlugin.log(IStatus.ERROR, NLS.bind("Could not open temporary file {0} for writing: {1}", new String[] { tmpFile.getAbsolutePath(), e.getMessage() }), e); //$NON-NLS-1$ + return new ByteArrayOutputStream(); + } + } - private InputStream getTempInputStream(IFile file, OutputStream output) throws CoreException { - if (output instanceof ByteArrayOutputStream) { - ByteArrayOutputStream baos = (ByteArrayOutputStream) output; - return new ByteArrayInputStream(baos.toByteArray()); - } - // We created a temporary file so we need to open an input stream on it - try { - // First make sure the output stream is closed - if (output != null) - output.close(); - } catch (IOException e) { - // Ignore - } - File tmpFile = getTempFile(file); - try { - return new BufferedInputStream(new FileInputStream(tmpFile)); - } catch (FileNotFoundException e) { - throw new CoreException(new Status(IStatus.ERROR, TeamPlugin.ID, IMergeStatus.INTERNAL_ERROR, NLS.bind(Messages.MergeContext_4, new String[] { tmpFile.getAbsolutePath(), e.getMessage() }), e)); - } - } + private InputStream getTempInputStream(IFile file, OutputStream output) throws CoreException { + if (output instanceof ByteArrayOutputStream) { + ByteArrayOutputStream baos = (ByteArrayOutputStream) output; + return new ByteArrayInputStream(baos.toByteArray()); + } + // We created a temporary file so we need to open an input stream on it + try { + // First make sure the output stream is closed + if (output != null) + output.close(); + } catch (IOException e) { + // Ignore + } + File tmpFile = getTempFile(file); + try { + return new BufferedInputStream(new FileInputStream(tmpFile)); + } catch (FileNotFoundException e) { + throw new CoreException(new Status(IStatus.ERROR, TeamPlugin.ID, IMergeStatus.INTERNAL_ERROR, NLS.bind(Messages.MergeContext_4, new String[] { tmpFile.getAbsolutePath(), e.getMessage() }), e)); + } + } - private File getTempFile(IFile file) { - return TeamPlugin.getPlugin().getStateLocation().append(".tmp").append(file.getName() + ".tmp").toFile(); //$NON-NLS-1$ //$NON-NLS-2$ - } + private File getTempFile(IFile file) { + return TeamPlugin.getPlugin().getStateLocation().append(".tmp").append(file.getName() + ".tmp").toFile(); //$NON-NLS-1$ //$NON-NLS-2$ + } private IFile getLocalFile(IDiff delta) { return ResourcesPlugin.getWorkspace().getRoot().getFile(delta.getPath()); @@ -321,31 +321,31 @@ public abstract class MergeContext extends SynchronizationContext implements IMe * a progress monitor * @throws CoreException */ - protected void performReplace(final IDiff diff, IProgressMonitor monitor) throws CoreException { - IResourceDiff d; - IFile file = getLocalFile(diff); - IFileRevision remote = null; - if (diff instanceof IResourceDiff) { - d = (IResourceDiff) diff; - remote = d.getAfterState(); - } else { - d = (IResourceDiff)((IThreeWayDiff)diff).getRemoteChange(); - if (d != null) - remote = d.getAfterState(); - } - if (d == null) { - d = (IResourceDiff)((IThreeWayDiff)diff).getLocalChange(); - if (d != null) - remote = d.getBeforeState(); - } + protected void performReplace(final IDiff diff, IProgressMonitor monitor) throws CoreException { + IResourceDiff d; + IFile file = getLocalFile(diff); + IFileRevision remote = null; + if (diff instanceof IResourceDiff) { + d = (IResourceDiff) diff; + remote = d.getAfterState(); + } else { + d = (IResourceDiff)((IThreeWayDiff)diff).getRemoteChange(); + if (d != null) + remote = d.getAfterState(); + } + if (d == null) { + d = (IResourceDiff)((IThreeWayDiff)diff).getLocalChange(); + if (d != null) + remote = d.getBeforeState(); + } - // Only perform the replace if a local or remote change was found - if (d != null) { - performReplace(diff, file, remote, monitor); - } + // Only perform the replace if a local or remote change was found + if (d != null) { + performReplace(diff, file, remote, monitor); + } } - /** + /** * Method that is invoked from * {@link #performReplace(IDiff, IProgressMonitor)} after the local has been * changed to match the remote. Subclasses may override @@ -361,7 +361,7 @@ public abstract class MergeContext extends SynchronizationContext implements IMe * a progress monitor * @throws CoreException */ - protected abstract void makeInSync(IDiff diff, IProgressMonitor monitor) throws CoreException; + protected abstract void makeInSync(IDiff diff, IProgressMonitor monitor) throws CoreException; private void performReplace(final IDiff diff, final IFile file, final IFileRevision remote, IProgressMonitor monitor) throws CoreException { run(monitor1 -> { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeStatus.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeStatus.java index cf272544a..675fbd21c 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeStatus.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/MergeStatus.java @@ -34,40 +34,40 @@ import org.eclipse.team.core.mapping.IMergeStatus; */ public class MergeStatus extends Status implements IMergeStatus { - private ResourceMapping[] conflictingMappings; + private ResourceMapping[] conflictingMappings; private IFile[] conflictingFiles; - /** - * Create a merge status for reporting that some of the resource mappings - * for which a merge was attempted were not auto-mergable. - * @param pluginId the plugin id - * @param message the message for the status - * @param conflictingMappings the mappings which were not auto-mergable - */ - public MergeStatus(String pluginId, String message, ResourceMapping[] conflictingMappings) { - super(IStatus.ERROR, pluginId, CONFLICTS, message, null); - this.conflictingMappings = conflictingMappings; - } + /** + * Create a merge status for reporting that some of the resource mappings + * for which a merge was attempted were not auto-mergable. + * @param pluginId the plugin id + * @param message the message for the status + * @param conflictingMappings the mappings which were not auto-mergable + */ + public MergeStatus(String pluginId, String message, ResourceMapping[] conflictingMappings) { + super(IStatus.ERROR, pluginId, CONFLICTS, message, null); + this.conflictingMappings = conflictingMappings; + } - /** - * Create a merge status for reporting that some of the files - * for which a merge was attempted were not auto-mergable. - * @param pluginId the plugin id - * @param message the message for the status - * @param files the files which were not auto-mergable - */ - public MergeStatus(String pluginId, String message, IFile[] files) { - super(IStatus.ERROR, pluginId, CONFLICTS, message, null); - this.conflictingFiles = files; + /** + * Create a merge status for reporting that some of the files + * for which a merge was attempted were not auto-mergable. + * @param pluginId the plugin id + * @param message the message for the status + * @param files the files which were not auto-mergable + */ + public MergeStatus(String pluginId, String message, IFile[] files) { + super(IStatus.ERROR, pluginId, CONFLICTS, message, null); + this.conflictingFiles = files; } - @Override + @Override public ResourceMapping[] getConflictingMappings() { - return conflictingMappings; - } + return conflictingMappings; + } - @Override + @Override public IFile[] getConflictingFiles() { - return conflictingFiles; - } + return conflictingFiles; + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java index 75708813d..89349c548 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java @@ -36,22 +36,22 @@ import org.eclipse.team.internal.core.Policy; */ public abstract class SynchronizationContext extends PlatformObject implements ISynchronizationContext { - private final int type; - private final IResourceDiffTree diffTree; - private Cache cache; + private final int type; + private final IResourceDiffTree diffTree; + private Cache cache; private final ISynchronizationScopeManager manager; - /** - * Create a synchronization context. - * @param manager the manager that defines the scope of the synchronization - * @param type the type of synchronization (ONE_WAY or TWO_WAY) - * @param diffTree the sync info tree that contains all out-of-sync resources - */ - protected SynchronizationContext(ISynchronizationScopeManager manager, int type, IResourceDiffTree diffTree) { - this.manager = manager; + /** + * Create a synchronization context. + * @param manager the manager that defines the scope of the synchronization + * @param type the type of synchronization (ONE_WAY or TWO_WAY) + * @param diffTree the sync info tree that contains all out-of-sync resources + */ + protected SynchronizationContext(ISynchronizationScopeManager manager, int type, IResourceDiffTree diffTree) { + this.manager = manager; this.type = type; this.diffTree = diffTree; - } + } @Override public ISynchronizationScope getScope() { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/subscribers/SubscriberResourceMappingContext.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/subscribers/SubscriberResourceMappingContext.java index 3df0805ad..b1f3d8817 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/subscribers/SubscriberResourceMappingContext.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/subscribers/SubscriberResourceMappingContext.java @@ -45,126 +45,126 @@ import org.eclipse.team.internal.core.TeamPlugin; */ public class SubscriberResourceMappingContext extends RemoteResourceMappingContext { - private final Subscriber subscriber; + private final Subscriber subscriber; - // Lists used to keep track of resources that have been refreshed - private Set<IResource> shallowRefresh = new HashSet<>(); - private Set<IResource> deepRefresh = new HashSet<>(); - private boolean autoRefresh; + // Lists used to keep track of resources that have been refreshed + private Set<IResource> shallowRefresh = new HashSet<>(); + private Set<IResource> deepRefresh = new HashSet<>(); + private boolean autoRefresh; - /** - * Return a resource mapping context suitable for comparison operations. - * Comparisons require that any out-of-sync resources have contents - * that differ. - * @param subscriber the subscriber - * @return a resource mapping context suitable for compare operations - */ - public static RemoteResourceMappingContext createContext(Subscriber subscriber) { - return new SubscriberResourceMappingContext(subscriber, true); - } + /** + * Return a resource mapping context suitable for comparison operations. + * Comparisons require that any out-of-sync resources have contents + * that differ. + * @param subscriber the subscriber + * @return a resource mapping context suitable for compare operations + */ + public static RemoteResourceMappingContext createContext(Subscriber subscriber) { + return new SubscriberResourceMappingContext(subscriber, true); + } - /** - * Create a resource mapping context for the given subscriber - * @param subscriber the subscriber - * from the local contents - * @param autoRefresh whether the context should auto-refresh when queried - */ - public SubscriberResourceMappingContext(Subscriber subscriber, boolean autoRefresh) { - this.subscriber = subscriber; - this.autoRefresh = autoRefresh; - } + /** + * Create a resource mapping context for the given subscriber + * @param subscriber the subscriber + * from the local contents + * @param autoRefresh whether the context should auto-refresh when queried + */ + public SubscriberResourceMappingContext(Subscriber subscriber, boolean autoRefresh) { + this.subscriber = subscriber; + this.autoRefresh = autoRefresh; + } - @Override + @Override public final boolean hasRemoteChange(IResource resource, IProgressMonitor monitor) throws CoreException { - try { + try { monitor.beginTask(null, 100); ensureRefreshed(resource, IResource.DEPTH_ONE, NONE, monitor); SyncInfo syncInfo = subscriber.getSyncInfo(resource); validateRemote(resource, syncInfo); - if (syncInfo == null) return false; - int direction = SyncInfo.getDirection(syncInfo.getKind()); + if (syncInfo == null) return false; + int direction = SyncInfo.getDirection(syncInfo.getKind()); return direction == SyncInfo.INCOMING || direction == SyncInfo.CONFLICTING; } finally { monitor.done(); } - } + } - @Override + @Override public boolean hasLocalChange(IResource resource, IProgressMonitor monitor) throws CoreException { - SyncInfo syncInfo = subscriber.getSyncInfo(resource); - if (syncInfo == null) return false; - int direction = SyncInfo.getDirection(syncInfo.getKind()); + SyncInfo syncInfo = subscriber.getSyncInfo(resource); + if (syncInfo == null) return false; + int direction = SyncInfo.getDirection(syncInfo.getKind()); return direction == SyncInfo.OUTGOING || direction == SyncInfo.CONFLICTING; - } + } - @Override + @Override public final IStorage fetchRemoteContents(IFile file, IProgressMonitor monitor) throws CoreException { - try { + try { monitor.beginTask(null, 100); - ensureRefreshed(file, IResource.DEPTH_ZERO, FILE_CONTENTS_REQUIRED, Policy.subMonitorFor(monitor, 10)); - SyncInfo syncInfo = subscriber.getSyncInfo(file); - IResourceVariant remote = validateRemote(file, syncInfo); - if (remote == null) { - return null; - } - return remote.getStorage(Policy.subMonitorFor(monitor, 90)); + ensureRefreshed(file, IResource.DEPTH_ZERO, FILE_CONTENTS_REQUIRED, Policy.subMonitorFor(monitor, 10)); + SyncInfo syncInfo = subscriber.getSyncInfo(file); + IResourceVariant remote = validateRemote(file, syncInfo); + if (remote == null) { + return null; + } + return remote.getStorage(Policy.subMonitorFor(monitor, 90)); } finally { monitor.done(); } - } + } - @Override + @Override public final IStorage fetchBaseContents(IFile file, IProgressMonitor monitor) throws CoreException { - try { + try { monitor.beginTask(null, 100); - ensureRefreshed(file, IResource.DEPTH_ZERO, FILE_CONTENTS_REQUIRED, Policy.subMonitorFor(monitor, 10)); - SyncInfo syncInfo = subscriber.getSyncInfo(file); - IResourceVariant base = validateBase(file, syncInfo); - if (base == null) { - return null; - } - return base.getStorage(Policy.subMonitorFor(monitor, 90)); + ensureRefreshed(file, IResource.DEPTH_ZERO, FILE_CONTENTS_REQUIRED, Policy.subMonitorFor(monitor, 10)); + SyncInfo syncInfo = subscriber.getSyncInfo(file); + IResourceVariant base = validateBase(file, syncInfo); + if (base == null) { + return null; + } + return base.getStorage(Policy.subMonitorFor(monitor, 90)); } finally { monitor.done(); } - } + } - @Override + @Override public final IResource[] fetchMembers(IContainer container, IProgressMonitor monitor) throws CoreException { - try { + try { monitor.beginTask(null, 100); - ensureRefreshed(container, IResource.DEPTH_ONE, NONE, Policy.subMonitorFor(monitor, 100)); - SyncInfo syncInfo = subscriber.getSyncInfo(container); - if (validateRemote(container, syncInfo) == null) { - // There is no remote so return an empty array - return new IResource[0]; - } - return subscriber.members(container); + ensureRefreshed(container, IResource.DEPTH_ONE, NONE, Policy.subMonitorFor(monitor, 100)); + SyncInfo syncInfo = subscriber.getSyncInfo(container); + if (validateRemote(container, syncInfo) == null) { + // There is no remote so return an empty array + return new IResource[0]; + } + return subscriber.members(container); } finally { monitor.done(); } - } + } - @Override + @Override public final void refresh(ResourceTraversal[] traversals, int flags, IProgressMonitor monitor) throws CoreException { - subscriber.refresh(traversals, monitor); - for (int i = 0; i < traversals.length; i++) { + subscriber.refresh(traversals, monitor); + for (int i = 0; i < traversals.length; i++) { ResourceTraversal traversal = traversals[i]; refreshed(traversal.getResources(), traversal.getDepth()); } - } + } - /** - * Refresh the subscriber and cache the fact that the resources were refreshed by - * calling the <code>refreshed</code> method. The default implementation only refreshes - * the state and does not fetch contents in the <code>FILE_CONTENTS_REQUIRED</code> - * flag is passed. It is up to subclass to handle this. - * @param resources the resources to be refreshed - * @param depth the depth of the refresh - * @param flags the flags that indicate extra state that should be fetched - * @param monitor a progress monitor - * @throws TeamException - */ + /** + * Refresh the subscriber and cache the fact that the resources were refreshed by + * calling the <code>refreshed</code> method. The default implementation only refreshes + * the state and does not fetch contents in the <code>FILE_CONTENTS_REQUIRED</code> + * flag is passed. It is up to subclass to handle this. + * @param resources the resources to be refreshed + * @param depth the depth of the refresh + * @param flags the flags that indicate extra state that should be fetched + * @param monitor a progress monitor + * @throws TeamException + */ protected void refresh(IResource[] resources, int depth, int flags, IProgressMonitor monitor) throws TeamException { subscriber.refresh(resources, depth, monitor); refreshed(resources, depth); @@ -189,32 +189,32 @@ public class SubscriberResourceMappingContext extends RemoteResourceMappingConte } } - /* - * Ensure that the given resource has been refreshed to the specified depth - * since the context has been created. - */ - private void ensureRefreshed(IResource resource, int depth, int flags, IProgressMonitor monitor) throws TeamException { - if (autoRefresh) { - if (depth == IResource.DEPTH_INFINITE) { - // If the resource or a parent was refreshed deeply, no need to do it again - if (wasRefreshedDeeply(resource)) - return; - // if the resource is a file, a shallow refresh is enough - if (resource.getType() == IResource.FILE && wasRefreshedShallow(resource)) - return; - } else { - if (wasRefreshedShallow(resource)) - return; - } - refresh(new IResource[] { resource }, depth, flags, monitor); - } + /* + * Ensure that the given resource has been refreshed to the specified depth + * since the context has been created. + */ + private void ensureRefreshed(IResource resource, int depth, int flags, IProgressMonitor monitor) throws TeamException { + if (autoRefresh) { + if (depth == IResource.DEPTH_INFINITE) { + // If the resource or a parent was refreshed deeply, no need to do it again + if (wasRefreshedDeeply(resource)) + return; + // if the resource is a file, a shallow refresh is enough + if (resource.getType() == IResource.FILE && wasRefreshedShallow(resource)) + return; + } else { + if (wasRefreshedShallow(resource)) + return; + } + refresh(new IResource[] { resource }, depth, flags, monitor); + } } - /* - * Look for a shallow refresh of the resource. If not there, - * look fir a deep refresh of a parent or a shallow refresh of the - * direct parent if the resource is a file. - */ + /* + * Look for a shallow refresh of the resource. If not there, + * look fir a deep refresh of a parent or a shallow refresh of the + * direct parent if the resource is a file. + */ private boolean wasRefreshedShallow(IResource resource) { if (shallowRefresh.contains(resource)) return true; @@ -240,45 +240,45 @@ public class SubscriberResourceMappingContext extends RemoteResourceMappingConte * Validate that the remote resource is of the proper type and return the * remote resource if it is OK. A return of null indicates that there is no remote. */ - private IResourceVariant validateRemote(IResource resource, SyncInfo syncInfo) throws CoreException { - if (syncInfo == null) return null; - IResourceVariant remote = syncInfo.getRemote(); - if (remote == null) return null; - return validateRemote(resource, remote); - } + private IResourceVariant validateRemote(IResource resource, SyncInfo syncInfo) throws CoreException { + if (syncInfo == null) return null; + IResourceVariant remote = syncInfo.getRemote(); + if (remote == null) return null; + return validateRemote(resource, remote); + } private IResourceVariant validateRemote(IResource resource, IResourceVariant remote) throws CoreException { boolean containerExpected = resource.getType() != IResource.FILE; - if (remote.isContainer() && !containerExpected) { - throw new CoreException(new Status(IStatus.ERROR, TeamPlugin.ID, IResourceStatus.RESOURCE_WRONG_TYPE, Messages.SubscriberResourceMappingContext_0 + resource.getFullPath().toString(), null)); - } else if (!remote.isContainer() && containerExpected) { - throw new CoreException(new Status(IStatus.ERROR, TeamPlugin.ID, IResourceStatus.RESOURCE_WRONG_TYPE, Messages.SubscriberResourceMappingContext_1 + resource.getFullPath().toString(), null)); - } - return remote; + if (remote.isContainer() && !containerExpected) { + throw new CoreException(new Status(IStatus.ERROR, TeamPlugin.ID, IResourceStatus.RESOURCE_WRONG_TYPE, Messages.SubscriberResourceMappingContext_0 + resource.getFullPath().toString(), null)); + } else if (!remote.isContainer() && containerExpected) { + throw new CoreException(new Status(IStatus.ERROR, TeamPlugin.ID, IResourceStatus.RESOURCE_WRONG_TYPE, Messages.SubscriberResourceMappingContext_1 + resource.getFullPath().toString(), null)); + } + return remote; } /* * Validate that the base resource is of the proper type and return the * base resource if it is OK. A return of null indicates that there is no base. */ - private IResourceVariant validateBase(IResource resource, SyncInfo syncInfo) throws CoreException { - if (syncInfo == null) return null; - IResourceVariant base = syncInfo.getBase(); - if (base == null) return null; - return validateRemote(resource, base); - } + private IResourceVariant validateBase(IResource resource, SyncInfo syncInfo) throws CoreException { + if (syncInfo == null) return null; + IResourceVariant base = syncInfo.getBase(); + if (base == null) return null; + return validateRemote(resource, base); + } - /** - * Set whether the context should refresh the state of resources - * when their state is requested. The context keeps track of what - * resources were refreshed and only auto-refreshes a resource - * once. - * @param autoRefresh whether the context should refresh the state of resources - * when their state is requested - */ - public void setAutoRefresh(boolean autoRefresh) { - this.autoRefresh = autoRefresh; - } + /** + * Set whether the context should refresh the state of resources + * when their state is requested. The context keeps track of what + * resources were refreshed and only auto-refreshes a resource + * once. + * @param autoRefresh whether the context should refresh the state of resources + * when their state is requested + */ + public void setAutoRefresh(boolean autoRefresh) { + this.autoRefresh = autoRefresh; + } @Override public boolean isThreeWay() { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfo.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfo.java index 91103b8c6..5e5ae3c40 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfo.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfo.java @@ -148,20 +148,20 @@ public class SyncInfo implements IAdaptable { /*==================================================================== * Members: *====================================================================*/ - private IResource local; - private IResourceVariant base; - private IResourceVariant remote; - private IResourceVariantComparator comparator; - - private int syncKind; - - /** - * Construct a sync info object. - * @param local the local resource. Must be non-null but may not exist. - * @param base the base resource variant or <code>null</code> - * @param remote the remote resource variant or <code>null</code> - * @param comparator the comparator used to determine if resources differ - */ + private IResource local; + private IResourceVariant base; + private IResourceVariant remote; + private IResourceVariantComparator comparator; + + private int syncKind; + + /** + * Construct a sync info object. + * @param local the local resource. Must be non-null but may not exist. + * @param base the base resource variant or <code>null</code> + * @param remote the remote resource variant or <code>null</code> + * @param comparator the comparator used to determine if resources differ + */ public SyncInfo(IResource local, IResourceVariant base, IResourceVariant remote, IResourceVariantComparator comparator) { Assert.isNotNull(local); Assert.isNotNull(comparator); diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfoSet.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfoSet.java index cd6b35f63..beb723704 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfoSet.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/synchronize/SyncInfoSet.java @@ -667,14 +667,14 @@ public class SyncInfoSet { return errors.values().toArray(new ITeamStatus[errors.size()]); } - /** - * Return an iterator over all <code>SyncInfo</code> - * contained in this set. - * @return an iterator over all <code>SyncInfo</code> - * contained in this set. - * @since 3.1 - */ - public Iterator iterator() { - return resources.values().iterator(); - } + /** + * Return an iterator over all <code>SyncInfo</code> + * contained in this set. + * @return an iterator over all <code>SyncInfo</code> + * contained in this set. + * @since 3.1 + */ + public Iterator iterator() { + return resources.values().iterator(); + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/BackgroundEventHandler.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/BackgroundEventHandler.java index f1f2fbc29..0b6b9a1c8 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/BackgroundEventHandler.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/BackgroundEventHandler.java @@ -101,7 +101,7 @@ public abstract class BackgroundEventHandler { * General event class. The type is specific to subclasses. */ public static class Event { - private int type; + private int type; public Event(int type) { this.type = type; } @@ -116,7 +116,7 @@ public abstract class BackgroundEventHandler { return buffer.toString(); } public IResource getResource() { - return null; + return null; } protected String getTypeString() { return String.valueOf(type); @@ -130,7 +130,7 @@ public abstract class BackgroundEventHandler { private IResource resource; private int depth; public ResourceEvent(IResource resource, int type, int depth) { - super(type); + super(type); this.resource = resource; this.depth = depth; } @@ -249,14 +249,14 @@ public abstract class BackgroundEventHandler { /** * Return the family that the background job for this * event handler belongs to. - * @return the family that the background job for this + * @return the family that the background job for this * event handler belongs to - */ - protected Object getJobFamiliy() { - return null; - } + */ + protected Object getJobFamiliy() { + return null; + } - /** + /** * This method is invoked when the processing job completes. The * default behavior of the handler is to restart the job if the queue * is no longer empty and to clear the queue if the handler was shut down. @@ -467,28 +467,28 @@ public abstract class BackgroundEventHandler { return WAIT_DELAY; } - /** + /** * Return the value that is used to determine how often * the events are dispatched (i.e. how often the UI is * updated) for the first 3 cycles. The default value is 1.5 seconds. * After the first 3 cycles, a longer delay is used - * @return the dispatch delay used for the first 3 cycles. - */ - protected long getShortDispatchDelay() { - return DISPATCH_DELAY; - } + * @return the dispatch delay used for the first 3 cycles. + */ + protected long getShortDispatchDelay() { + return DISPATCH_DELAY; + } /** * Return the value that is used to determine how often * the events are dispatched (i.e. how often the UI is * updated) after the first 3 cycles. The default value is 10 seconds. - * @return the dispatch delay used after the first 3 cycles. - */ - protected long getLongDispatchDelay() { - return LONG_DISPATCH_DELAY; - } + * @return the dispatch delay used after the first 3 cycles. + */ + protected long getLongDispatchDelay() { + return LONG_DISPATCH_DELAY; + } - /** + /** * Handle the exception by recording it in the errors list. * @param e */ diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/DefaultFileModificationValidator.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/DefaultFileModificationValidator.java index 37f0f525b..a01b75680 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/DefaultFileModificationValidator.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/DefaultFileModificationValidator.java @@ -49,22 +49,22 @@ public class DefaultFileModificationValidator extends FileModificationValidator @Override public IStatus validateEdit(IFile[] files, FileModificationValidationContext context) { - IFile[] readOnlyFiles = getReadOnly(files); - if (readOnlyFiles.length == 0) - return Status.OK_STATUS; - synchronized (this) { - if (uiValidator == null) - uiValidator = loadUIValidator(); - } - if (uiValidator != null) { - return uiValidator.validateEdit(files, context); - } - // There was no plugged in validator so fail gracefully + IFile[] readOnlyFiles = getReadOnly(files); + if (readOnlyFiles.length == 0) + return Status.OK_STATUS; + synchronized (this) { + if (uiValidator == null) + uiValidator = loadUIValidator(); + } + if (uiValidator != null) { + return uiValidator.validateEdit(files, context); + } + // There was no plugged in validator so fail gracefully return getStatus(files); } - protected IStatus getStatus(IFile[] files) { - if (files.length == 1) { + protected IStatus getStatus(IFile[] files) { + if (files.length == 1) { return getDefaultStatus(files[0]); } @@ -83,51 +83,51 @@ public class DefaultFileModificationValidator extends FileModificationValidator ? Messages.ok : Messages.FileModificationValidator_someReadOnly, null); - } + } - private IFile[] getReadOnly(IFile[] files) { - List<IFile> result = new ArrayList<>(files.length); - for (int i = 0; i < files.length; i++) { - IFile file = files[i]; - if (file.isReadOnly()) { - result.add(file); - } - } - return result.toArray(new IFile[result.size()]); - } + private IFile[] getReadOnly(IFile[] files) { + List<IFile> result = new ArrayList<>(files.length); + for (int i = 0; i < files.length; i++) { + IFile file = files[i]; + if (file.isReadOnly()) { + result.add(file); + } + } + return result.toArray(new IFile[result.size()]); + } @Override public IStatus validateSave(IFile file) { - if (!file.isReadOnly()) - return Status.OK_STATUS; - synchronized (this) { - if (uiValidator == null) - uiValidator = loadUIValidator(); - } - if (uiValidator != null) { - return uiValidator.validateSave(file); - } + if (!file.isReadOnly()) + return Status.OK_STATUS; + synchronized (this) { + if (uiValidator == null) + uiValidator = loadUIValidator(); + } + if (uiValidator != null) { + return uiValidator.validateSave(file); + } return getDefaultStatus(file); } - private FileModificationValidator loadUIValidator() { - IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(TeamPlugin.ID, TeamPlugin.DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION); + private FileModificationValidator loadUIValidator() { + IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(TeamPlugin.ID, TeamPlugin.DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION); if (extension != null) { IExtension[] extensions = extension.getExtensions(); if (extensions.length > 0) { IConfigurationElement[] configElements = extensions[0].getConfigurationElements(); if (configElements.length > 0) { try { - Object o = configElements[0].createExecutableExtension("class"); //$NON-NLS-1$ - if (o instanceof FileModificationValidator) { - return (FileModificationValidator)o; - } - } catch (CoreException e) { - TeamPlugin.log(e); - } + Object o = configElements[0].createExecutableExtension("class"); //$NON-NLS-1$ + if (o instanceof FileModificationValidator) { + return (FileModificationValidator)o; + } + } catch (CoreException e) { + TeamPlugin.log(e); + } } } } return null; - } + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ExceptionCollector.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ExceptionCollector.java index d2e177404..8c956d1a9 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ExceptionCollector.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ExceptionCollector.java @@ -94,19 +94,19 @@ public class ExceptionCollector { * @param exception the exception to collect */ public void handleException(CoreException exception) { - // log the exception if we have a log - if(log != null) { - log.log(new Status(severity, pluginId, 0, message, exception)); - } - // Record each status individually to flatten the resulting multi-status - IStatus exceptionStatus = exception.getStatus(); - // Wrap the exception so the stack trace is not lost. - IStatus status = new Status(exceptionStatus.getSeverity(), exceptionStatus.getPlugin(), exceptionStatus.getCode(), exceptionStatus.getMessage(), exception); - recordStatus(status); + // log the exception if we have a log + if(log != null) { + log.log(new Status(severity, pluginId, 0, message, exception)); + } + // Record each status individually to flatten the resulting multi-status + IStatus exceptionStatus = exception.getStatus(); + // Wrap the exception so the stack trace is not lost. + IStatus status = new Status(exceptionStatus.getSeverity(), exceptionStatus.getPlugin(), exceptionStatus.getCode(), exceptionStatus.getMessage(), exception); + recordStatus(status); IStatus[] children = status.getChildren(); for (int i = 0; i < children.length; i++) { IStatus status2 = children[i]; - recordStatus(status2); + recordStatus(status2); } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileContentManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileContentManager.java index 2ef473292..4c7dd374f 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileContentManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileContentManager.java @@ -40,236 +40,236 @@ import org.eclipse.team.core.Team; */ public class FileContentManager implements IFileContentManager { - private static final String PREF_TEAM_EXTENSION_TYPES= "file_types"; //$NON-NLS-1$ - private static final String PREF_TEAM_FILENAME_TYPES= "cvs_mode_for_file_without_extensions"; //$NON-NLS-1$ + private static final String PREF_TEAM_EXTENSION_TYPES= "file_types"; //$NON-NLS-1$ + private static final String PREF_TEAM_FILENAME_TYPES= "cvs_mode_for_file_without_extensions"; //$NON-NLS-1$ - private static class StringMapping implements IStringMapping { + private static class StringMapping implements IStringMapping { - private final String fString; - private final int fType; + private final String fString; + private final int fType; - public StringMapping(String string, int type) { - fString= string; - fType= type; - } + public StringMapping(String string, int type) { + fString= string; + fType= type; + } - @Override + @Override public String getString() { - return fString; - } + return fString; + } - @Override + @Override public int getType() { - return fType; - } - } + return fType; + } + } - private static class UserExtensionMappings extends UserStringMappings { + private static class UserExtensionMappings extends UserStringMappings { - public UserExtensionMappings(String key) { - super(key); - } + public UserExtensionMappings(String key) { + super(key); + } - @Override + @Override protected Map<String, Integer> loadMappingsFromPreferences() { - final Map<String, Integer> result= super.loadMappingsFromPreferences(); - if (loadMappingsFromOldWorkspace(result)) { - TeamPlugin.getPlugin().savePluginPreferences(); - } - return result; - } - - /** - * If the workspace is an old 2.0 one, read the old file and delete it. - * - * @param A map where the new mappings should be added. - * - * @return true if the workspace was a 2.0 one and the old mappings have - * been added to the map, false otherwise. - * - */ - private boolean loadMappingsFromOldWorkspace(Map<String, Integer> map) { - // File name of the persisted file type information - String STATE_FILE = ".fileTypes"; //$NON-NLS-1$ - IPath pluginStateLocation = TeamPlugin.getPlugin().getStateLocation().append(STATE_FILE); - File f = pluginStateLocation.toFile(); - - if (!f.exists()) - return false; - - try { - DataInputStream input = new DataInputStream(new FileInputStream(f)); - try { - map.putAll(readOldFormatExtensionMappings(input)); - } finally { - input.close(); - f.delete(); - } - } catch (IOException ex) { - TeamPlugin.log(IStatus.ERROR, ex.getMessage(), ex); - return false; - } - return true; - } - - /** - * Read the saved file type state from the given input stream. - * - * @param input the input stream to read the saved state from - * @throws IOException if an I/O problem occurs - */ - private Map<String, Integer> readOldFormatExtensionMappings(DataInputStream input) throws IOException { - final Map<String, Integer> result= new TreeMap<>(); - int numberOfMappings = 0; - try { - numberOfMappings = input.readInt(); - } catch (EOFException e) { - // Ignore the exception, it will occur if there are no - // patterns stored in the state file. - return Collections.emptyMap(); - } - for (int i = 0; i < numberOfMappings; i++) { - final String extension = input.readUTF(); - final int type = input.readInt(); - result.put(extension, Integer.valueOf(type)); - } - return result; - } - } - - private final UserStringMappings fUserExtensionMappings, fUserNameMappings; - private PluginStringMappings fPluginExtensionMappings;//, fPluginNameMappings; - private IContentType textContentType; - - public FileContentManager() { - fUserExtensionMappings= new UserExtensionMappings(PREF_TEAM_EXTENSION_TYPES); - fUserNameMappings= new UserStringMappings(PREF_TEAM_FILENAME_TYPES); - fPluginExtensionMappings= new PluginStringMappings(TeamPlugin.FILE_TYPES_EXTENSION, "extension"); //$NON-NLS-1$ - } - - @Override + final Map<String, Integer> result= super.loadMappingsFromPreferences(); + if (loadMappingsFromOldWorkspace(result)) { + TeamPlugin.getPlugin().savePluginPreferences(); + } + return result; + } + + /** + * If the workspace is an old 2.0 one, read the old file and delete it. + * + * @param A map where the new mappings should be added. + * + * @return true if the workspace was a 2.0 one and the old mappings have + * been added to the map, false otherwise. + * + */ + private boolean loadMappingsFromOldWorkspace(Map<String, Integer> map) { + // File name of the persisted file type information + String STATE_FILE = ".fileTypes"; //$NON-NLS-1$ + IPath pluginStateLocation = TeamPlugin.getPlugin().getStateLocation().append(STATE_FILE); + File f = pluginStateLocation.toFile(); + + if (!f.exists()) + return false; + + try { + DataInputStream input = new DataInputStream(new FileInputStream(f)); + try { + map.putAll(readOldFormatExtensionMappings(input)); + } finally { + input.close(); + f.delete(); + } + } catch (IOException ex) { + TeamPlugin.log(IStatus.ERROR, ex.getMessage(), ex); + return false; + } + return true; + } + + /** + * Read the saved file type state from the given input stream. + * + * @param input the input stream to read the saved state from + * @throws IOException if an I/O problem occurs + */ + private Map<String, Integer> readOldFormatExtensionMappings(DataInputStream input) throws IOException { + final Map<String, Integer> result= new TreeMap<>(); + int numberOfMappings = 0; + try { + numberOfMappings = input.readInt(); + } catch (EOFException e) { + // Ignore the exception, it will occur if there are no + // patterns stored in the state file. + return Collections.emptyMap(); + } + for (int i = 0; i < numberOfMappings; i++) { + final String extension = input.readUTF(); + final int type = input.readInt(); + result.put(extension, Integer.valueOf(type)); + } + return result; + } + } + + private final UserStringMappings fUserExtensionMappings, fUserNameMappings; + private PluginStringMappings fPluginExtensionMappings;//, fPluginNameMappings; + private IContentType textContentType; + + public FileContentManager() { + fUserExtensionMappings= new UserExtensionMappings(PREF_TEAM_EXTENSION_TYPES); + fUserNameMappings= new UserStringMappings(PREF_TEAM_FILENAME_TYPES); + fPluginExtensionMappings= new PluginStringMappings(TeamPlugin.FILE_TYPES_EXTENSION, "extension"); //$NON-NLS-1$ + } + + @Override public int getTypeForName(String filename) { - final int userType= fUserNameMappings.getType(filename); + final int userType= fUserNameMappings.getType(filename); // final int pluginType= fPluginNameMappings.getType(filename); // return userType != Team.UNKNOWN ? userType : pluginType; - return userType; - } + return userType; + } - @Override + @Override public int getTypeForExtension(String extension) { - final int userType= fUserExtensionMappings.getType(extension); - final int pluginType= fPluginExtensionMappings.getType(extension); - return userType != Team.UNKNOWN ? userType : pluginType; - } + final int userType= fUserExtensionMappings.getType(extension); + final int pluginType= fPluginExtensionMappings.getType(extension); + return userType != Team.UNKNOWN ? userType : pluginType; + } - @Override + @Override public void addNameMappings(String[] names, int [] types) { - fUserNameMappings.addStringMappings(names, types); - } + fUserNameMappings.addStringMappings(names, types); + } - @Override + @Override public void addExtensionMappings(String[] extensions, int [] types) { - fUserExtensionMappings.addStringMappings(extensions, types); - } + fUserExtensionMappings.addStringMappings(extensions, types); + } - @Override + @Override public void setNameMappings(String[] names, int [] types) { - fUserNameMappings.setStringMappings(names, types); - } + fUserNameMappings.setStringMappings(names, types); + } - @Override + @Override public void setExtensionMappings(String[] extensions, int [] types) { - fUserExtensionMappings.setStringMappings(extensions, types); - } + fUserExtensionMappings.setStringMappings(extensions, types); + } - @Override + @Override public IStringMapping[] getNameMappings() { - return getMappings(fUserNameMappings, null);//fPluginNameMappings); - } + return getMappings(fUserNameMappings, null);//fPluginNameMappings); + } - @Override + @Override public IStringMapping[] getExtensionMappings() { - return getMappings(fUserExtensionMappings, fPluginExtensionMappings); - } + return getMappings(fUserExtensionMappings, fPluginExtensionMappings); + } - @Override + @Override public int getType(IStorage storage) { - int type; - - final String name= storage.getName(); - if (name != null && (type= getTypeForName(name)) != Team.UNKNOWN) - return type; - - final String extension= getFileExtension(name); - if (extension != null && (type= getTypeForExtension(extension)) != Team.UNKNOWN) - return type; - - IContentType contentType = Platform.getContentTypeManager().findContentTypeFor(name); - if (contentType != null) { - IContentType textType = getTextContentType(); - if (contentType.isKindOf(textType)) { - return Team.TEXT; - } - } - - return Team.UNKNOWN; - } - - private IContentType getTextContentType() { - if (textContentType == null) - textContentType = Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT); - return textContentType; - } - - @Override + int type; + + final String name= storage.getName(); + if (name != null && (type= getTypeForName(name)) != Team.UNKNOWN) + return type; + + final String extension= getFileExtension(name); + if (extension != null && (type= getTypeForExtension(extension)) != Team.UNKNOWN) + return type; + + IContentType contentType = Platform.getContentTypeManager().findContentTypeFor(name); + if (contentType != null) { + IContentType textType = getTextContentType(); + if (contentType.isKindOf(textType)) { + return Team.TEXT; + } + } + + return Team.UNKNOWN; + } + + private IContentType getTextContentType() { + if (textContentType == null) + textContentType = Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT); + return textContentType; + } + + @Override public IStringMapping[] getDefaultNameMappings() { - // TODO: There is currently no extension point for this - return new IStringMapping[0];//getStringMappings(fPluginNameMappings.referenceMap()); - } + // TODO: There is currently no extension point for this + return new IStringMapping[0];//getStringMappings(fPluginNameMappings.referenceMap()); + } - @Override + @Override public IStringMapping[] getDefaultExtensionMappings() { - return getStringMappings(fPluginExtensionMappings.referenceMap()); - } + return getStringMappings(fPluginExtensionMappings.referenceMap()); + } - @Override + @Override public boolean isKnownExtension(String extension) { - return fUserExtensionMappings.referenceMap().containsKey(extension) - || fPluginExtensionMappings.referenceMap().containsKey(extension); - } + return fUserExtensionMappings.referenceMap().containsKey(extension) + || fPluginExtensionMappings.referenceMap().containsKey(extension); + } - @Override + @Override public boolean isKnownFilename(String filename) { - return fUserNameMappings.referenceMap().containsKey(filename); + return fUserNameMappings.referenceMap().containsKey(filename); // || fPluginNameMappings.referenceMap().containsKey(filename); - } - - private static String getFileExtension(String name) { - if (name == null) - return null; - int index = name.lastIndexOf('.'); - if (index == -1) - return null; - if (index == (name.length() - 1)) - return ""; //$NON-NLS-1$ - return name.substring(index + 1); - } - - private static IStringMapping [] getStringMappings(Map map) { - final IStringMapping [] result= new IStringMapping [map.size()]; - int index= 0; - for (final Iterator iter = map.entrySet().iterator(); iter.hasNext();) { - final Map.Entry entry= (Map.Entry)iter.next(); - result[index++]= new StringMapping((String)entry.getKey(), ((Integer)entry.getValue()).intValue()); - } - return result; - } - - private IStringMapping [] getMappings(UserStringMappings userMappings, PluginStringMappings pluginMappings) { - final Map<String, Integer> mappings= new HashMap<>(); - if (pluginMappings != null) - mappings.putAll(pluginMappings.referenceMap()); - mappings.putAll(userMappings.referenceMap()); - return getStringMappings(mappings); - } + } + + private static String getFileExtension(String name) { + if (name == null) + return null; + int index = name.lastIndexOf('.'); + if (index == -1) + return null; + if (index == (name.length() - 1)) + return ""; //$NON-NLS-1$ + return name.substring(index + 1); + } + + private static IStringMapping [] getStringMappings(Map map) { + final IStringMapping [] result= new IStringMapping [map.size()]; + int index= 0; + for (final Iterator iter = map.entrySet().iterator(); iter.hasNext();) { + final Map.Entry entry= (Map.Entry)iter.next(); + result[index++]= new StringMapping((String)entry.getKey(), ((Integer)entry.getValue()).intValue()); + } + return result; + } + + private IStringMapping [] getMappings(UserStringMappings userMappings, PluginStringMappings pluginMappings) { + final Map<String, Integer> mappings= new HashMap<>(); + if (pluginMappings != null) + mappings.putAll(pluginMappings.referenceMap()); + mappings.putAll(userMappings.referenceMap()); + return getStringMappings(mappings); + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileModificationValidatorManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileModificationValidatorManager.java index e00379ea3..c8dc7055e 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileModificationValidatorManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/FileModificationValidatorManager.java @@ -102,9 +102,9 @@ public class FileModificationValidatorManager extends FileModificationValidator } private synchronized FileModificationValidator getDefaultValidator() { - if (defaultValidator == null) { - defaultValidator = new DefaultFileModificationValidator(); - } - return defaultValidator; + if (defaultValidator == null) { + defaultValidator = new DefaultFileModificationValidator(); + } + return defaultValidator; } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/Messages.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/Messages.java index fc01b4197..66017dc2a 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/Messages.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/Messages.java @@ -27,7 +27,7 @@ public class Messages extends NLS { public static String ok; public static String concatStrings; - public static String AbstractResourceVariantTree_0; + public static String AbstractResourceVariantTree_0; public static String Assert_assertionFailed; @@ -44,7 +44,7 @@ public class Messages extends NLS { public static String RepositoryProvider_linkedURIsNotSupported; public static String RepositoryProvider_couldNotClearAfterError; public static String RepositoryProvider_invalidClass; - public static String RepositoryProvider_toString; + public static String RepositoryProvider_toString; public static String SubscriberDiffTreeEventHandler_0; @@ -99,15 +99,15 @@ public class Messages extends NLS { public static String ProjectSetCapability_0; public static String ProjectSetCapability_1; - public static String SubscriberResourceMappingContext_0; - public static String SubscriberResourceMappingContext_1; + public static String SubscriberResourceMappingContext_0; + public static String SubscriberResourceMappingContext_1; public static String MergeContext_0; public static String MergeContext_1; public static String MergeContext_2; public static String MergeContext_3; public static String MergeContext_4; - public static String LocalFileRevision_currentVersion; + public static String LocalFileRevision_currentVersion; public static String LocalFileRevision_currentVersionTag; public static String LocalFileRevision_localRevisionTag; static { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/PluginStringMappings.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/PluginStringMappings.java index 3197bdc6e..8193e6ae4 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/PluginStringMappings.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/PluginStringMappings.java @@ -29,63 +29,63 @@ import org.eclipse.team.core.Team; */ public class PluginStringMappings { - private final String fExtensionID; - private final String fAttributeName; - - private SortedMap<String, Integer> fMappings; - - public PluginStringMappings(String extensionID, String stringAttributeName) { - fExtensionID= extensionID; - fAttributeName= stringAttributeName; - } - - /** - * Load all the extension patterns contributed by plugins. - * @return a map with the patterns - */ - private SortedMap<String, Integer> loadPluginPatterns() { - - final SortedMap<String, Integer> result= new TreeMap<>(); - - final TeamPlugin plugin = TeamPlugin.getPlugin(); - if (plugin == null) - return result; - - final IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(TeamPlugin.ID, fExtensionID);//TeamPlugin.FILE_TYPES_EXTENSION); - if (extension == null) - return result; - - final IExtension[] extensions = extension.getExtensions(); - - for (int i = 0; i < extensions.length; i++) { - IConfigurationElement[] configElements = extensions[i].getConfigurationElements(); - - for (int j = 0; j < configElements.length; j++) { - - final String ext = configElements[j].getAttribute(fAttributeName);//"extension"); - final String type = configElements[j].getAttribute("type"); //$NON-NLS-1$ - if (ext == null || type == null) - continue; - - if (type.equals("text")) { //$NON-NLS-1$ - result.put(ext, Integer.valueOf(Team.TEXT)); - } else if (type.equals("binary")) { //$NON-NLS-1$ - result.put(ext, Integer.valueOf(Team.BINARY)); - } - } - } - return result; - } - - public Map<String, Integer> referenceMap() { - if (fMappings == null) { - fMappings= loadPluginPatterns(); - } - return fMappings; - } - - public int getType(String filename) { - final Map<String, Integer> mappings= referenceMap(); - return mappings.containsKey(filename) ? mappings.get(filename).intValue() : Team.UNKNOWN; - } + private final String fExtensionID; + private final String fAttributeName; + + private SortedMap<String, Integer> fMappings; + + public PluginStringMappings(String extensionID, String stringAttributeName) { + fExtensionID= extensionID; + fAttributeName= stringAttributeName; + } + + /** + * Load all the extension patterns contributed by plugins. + * @return a map with the patterns + */ + private SortedMap<String, Integer> loadPluginPatterns() { + + final SortedMap<String, Integer> result= new TreeMap<>(); + + final TeamPlugin plugin = TeamPlugin.getPlugin(); + if (plugin == null) + return result; + + final IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(TeamPlugin.ID, fExtensionID);//TeamPlugin.FILE_TYPES_EXTENSION); + if (extension == null) + return result; + + final IExtension[] extensions = extension.getExtensions(); + + for (int i = 0; i < extensions.length; i++) { + IConfigurationElement[] configElements = extensions[i].getConfigurationElements(); + + for (int j = 0; j < configElements.length; j++) { + + final String ext = configElements[j].getAttribute(fAttributeName);//"extension"); + final String type = configElements[j].getAttribute("type"); //$NON-NLS-1$ + if (ext == null || type == null) + continue; + + if (type.equals("text")) { //$NON-NLS-1$ + result.put(ext, Integer.valueOf(Team.TEXT)); + } else if (type.equals("binary")) { //$NON-NLS-1$ + result.put(ext, Integer.valueOf(Team.BINARY)); + } + } + } + return result; + } + + public Map<String, Integer> referenceMap() { + if (fMappings == null) { + fMappings= loadPluginPatterns(); + } + return fMappings; + } + + public int getType(String filename) { + final Map<String, Integer> mappings= referenceMap(); + return mappings.containsKey(filename) ? mappings.get(filename).intValue() : Team.UNKNOWN; + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ResourceVariantCache.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ResourceVariantCache.java index c1702941c..ba1bf5be1 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ResourceVariantCache.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/ResourceVariantCache.java @@ -100,8 +100,8 @@ public class ResourceVariantCache { public static synchronized void shutdown() { String[] keys = caches.keySet().toArray(new String[caches.size()]); - for (int i = 0; i < keys.length; i++) { - String id = keys[i]; + for (int i = 0; i < keys.length; i++) { + String id = keys[i]; disableCache(id); } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/StorageMergerRegistry.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/StorageMergerRegistry.java index 27f3f40f1..4c6095879 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/StorageMergerRegistry.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/StorageMergerRegistry.java @@ -97,11 +97,11 @@ public class StorageMergerRegistry { // collect all IStreamMergers IConfigurationElement[] elements= registry.getConfigurationElementsFor(TeamPlugin.ID, STORAGE_MERGER_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; - if (STORAGE_MERGER.equals(element.getName())) - register(element, new StorageMergerDescriptor(element)); - else if (CONTENT_TYPE_BINDING.equals(element.getName())) - createBinding(element, STORAGE_MERGER_ID_ATTRIBUTE); + IConfigurationElement element= elements[i]; + if (STORAGE_MERGER.equals(element.getName())) + register(element, new StorageMergerDescriptor(element)); + else if (CONTENT_TYPE_BINDING.equals(element.getName())) + createBinding(element, STORAGE_MERGER_ID_ATTRIBUTE); } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/TeamPlugin.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/TeamPlugin.java index 82f2e7d8c..b2b22a7e7 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/TeamPlugin.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/TeamPlugin.java @@ -77,9 +77,9 @@ final public class TeamPlugin extends Plugin { // The id of the default file modification validator extension point public static final String DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION = "defaultFileModificationValidator"; //$NON-NLS-1$ - // The id used to associate a provider with a project - public final static QualifiedName PROVIDER_PROP_KEY = - new QualifiedName("org.eclipse.team.core", "repository"); //$NON-NLS-1$ //$NON-NLS-2$ + // The id used to associate a provider with a project + public final static QualifiedName PROVIDER_PROP_KEY = + new QualifiedName("org.eclipse.team.core", "repository"); //$NON-NLS-1$ //$NON-NLS-2$ // The id for the Bundle Import extension point public static final String EXTENSION_POINT_BUNDLE_IMPORTERS = ID + ".bundleImporters"; //$NON-NLS-1$ @@ -187,13 +187,13 @@ final public class TeamPlugin extends Plugin { for (int i = 0; i < extensions.length; i++) { IConfigurationElement [] configElements = extensions[i].getConfigurationElements(); for (int j = 0; j < configElements.length; j++) { - String aliasId = configElements[j].getAttribute("canImportId"); //$NON-NLS-1$ - if (aliasId != null && aliasId.equals(id)) { + String aliasId = configElements[j].getAttribute("canImportId"); //$NON-NLS-1$ + if (aliasId != null && aliasId.equals(id)) { String extensionId = configElements[j].getAttribute("id"); //$NON-NLS-1$ if (extensionId != null) { return RepositoryProviderType.getProviderType(extensionId); } - } + } } } } @@ -208,11 +208,11 @@ final public class TeamPlugin extends Plugin { IConfigurationElement [] configElements = extensions[i].getConfigurationElements(); for (int j = 0; j < configElements.length; j++) { String extensionId = configElements[j].getAttribute("id"); //$NON-NLS-1$ - String metaFilePaths = configElements[j].getAttribute("metaFilePaths"); //$NON-NLS-1$ - if (extensionId != null && extensionId.equals(id) && metaFilePaths != null) { + String metaFilePaths = configElements[j].getAttribute("metaFilePaths"); //$NON-NLS-1$ + if (extensionId != null && extensionId.equals(id) && metaFilePaths != null) { return getPaths(metaFilePaths); - } + } } } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/UserStringMappings.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/UserStringMappings.java index acac94a70..cfe1bc0cd 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/UserStringMappings.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/UserStringMappings.java @@ -28,96 +28,96 @@ import org.eclipse.team.core.Team; public class UserStringMappings implements Preferences.IPropertyChangeListener { - public static final Integer BINARY= Integer.valueOf(Team.BINARY); - public static final Integer TEXT= Integer.valueOf(Team.TEXT); - public static final Integer UNKNOWN= Integer.valueOf(Team.UNKNOWN); - - - private static final String PREF_TEAM_SEPARATOR = "\n"; //$NON-NLS-1$ - - private final Preferences fPreferences; - private final String fKey; - - private Map<String, Integer> fMap; - - public UserStringMappings(String key) { - fKey= key; - fPreferences= TeamPlugin.getPlugin().getPluginPreferences(); - fPreferences.addPropertyChangeListener(this); - } - - public Map<String, Integer> referenceMap() { - if (fMap == null) { - fMap= loadMappingsFromPreferences(); - } - return fMap; - } - - public void addStringMappings(String[] names, int[] types) { - Assert.isTrue(names.length == types.length); - final Map<String, Integer> map= referenceMap(); - - for (int i = 0; i < names.length; i++) { - switch (types[i]) { - case Team.BINARY: map.put(names[i], BINARY); break; - case Team.TEXT: map.put(names[i], TEXT); break; - case Team.UNKNOWN: map.put(names[i], UNKNOWN); break; - } - } - save(); - } - - public void setStringMappings(String [] names, int [] types) { - Assert.isTrue(names.length == types.length); - referenceMap().clear(); - addStringMappings(names, types); - } - - public int getType(String string) { - if (string == null) - return Team.UNKNOWN; - final Integer type= referenceMap().get(string); - return type != null ? type.intValue() : Team.UNKNOWN; - } - - @Override + public static final Integer BINARY= Integer.valueOf(Team.BINARY); + public static final Integer TEXT= Integer.valueOf(Team.TEXT); + public static final Integer UNKNOWN= Integer.valueOf(Team.UNKNOWN); + + + private static final String PREF_TEAM_SEPARATOR = "\n"; //$NON-NLS-1$ + + private final Preferences fPreferences; + private final String fKey; + + private Map<String, Integer> fMap; + + public UserStringMappings(String key) { + fKey= key; + fPreferences= TeamPlugin.getPlugin().getPluginPreferences(); + fPreferences.addPropertyChangeListener(this); + } + + public Map<String, Integer> referenceMap() { + if (fMap == null) { + fMap= loadMappingsFromPreferences(); + } + return fMap; + } + + public void addStringMappings(String[] names, int[] types) { + Assert.isTrue(names.length == types.length); + final Map<String, Integer> map= referenceMap(); + + for (int i = 0; i < names.length; i++) { + switch (types[i]) { + case Team.BINARY: map.put(names[i], BINARY); break; + case Team.TEXT: map.put(names[i], TEXT); break; + case Team.UNKNOWN: map.put(names[i], UNKNOWN); break; + } + } + save(); + } + + public void setStringMappings(String [] names, int [] types) { + Assert.isTrue(names.length == types.length); + referenceMap().clear(); + addStringMappings(names, types); + } + + public int getType(String string) { + if (string == null) + return Team.UNKNOWN; + final Integer type= referenceMap().get(string); + return type != null ? type.intValue() : Team.UNKNOWN; + } + + @Override public void propertyChange(PropertyChangeEvent event) { - if(event.getProperty().equals(fKey)) - fMap= null; - } - - public void save() { - // Now set into preferences - final StringBuilder buffer = new StringBuilder(); - final Iterator e = fMap.keySet().iterator(); - - while (e.hasNext()) { - final String filename = (String)e.next(); - buffer.append(filename); - buffer.append(PREF_TEAM_SEPARATOR); - final Integer type = fMap.get(filename); - buffer.append(type); - buffer.append(PREF_TEAM_SEPARATOR); - } - TeamPlugin.getPlugin().getPluginPreferences().setValue(fKey, buffer.toString()); - } - - protected Map<String, Integer> loadMappingsFromPreferences() { - final Map<String, Integer> result= new HashMap<>(); - - if (!fPreferences.contains(fKey)) - return result; - - final String prefTypes = fPreferences.getString(fKey); - final StringTokenizer tok = new StringTokenizer(prefTypes, PREF_TEAM_SEPARATOR); - try { - while (tok.hasMoreElements()) { - final String name = tok.nextToken(); - final String mode= tok.nextToken(); - result.put(name, Integer.valueOf(mode)); - } - } catch (NoSuchElementException e) { - } - return result; - } + if(event.getProperty().equals(fKey)) + fMap= null; + } + + public void save() { + // Now set into preferences + final StringBuilder buffer = new StringBuilder(); + final Iterator e = fMap.keySet().iterator(); + + while (e.hasNext()) { + final String filename = (String)e.next(); + buffer.append(filename); + buffer.append(PREF_TEAM_SEPARATOR); + final Integer type = fMap.get(filename); + buffer.append(type); + buffer.append(PREF_TEAM_SEPARATOR); + } + TeamPlugin.getPlugin().getPluginPreferences().setValue(fKey, buffer.toString()); + } + + protected Map<String, Integer> loadMappingsFromPreferences() { + final Map<String, Integer> result= new HashMap<>(); + + if (!fPreferences.contains(fKey)) + return result; + + final String prefTypes = fPreferences.getString(fKey); + final StringTokenizer tok = new StringTokenizer(prefTypes, PREF_TEAM_SEPARATOR); + try { + while (tok.hasMoreElements()) { + final String name = tok.nextToken(); + final String mode= tok.nextToken(); + result.put(name, Integer.valueOf(mode)); + } + } catch (NoSuchElementException e) { + } + return result; + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/LFtoCRLFInputStream.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/LFtoCRLFInputStream.java index b6b521cb2..92f4ab3b6 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/LFtoCRLFInputStream.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/LFtoCRLFInputStream.java @@ -107,11 +107,11 @@ public class LFtoCRLFInputStream extends FilterInputStream { count++; } buffer[off++] = b; - } - if (iioe != null) { - iioe.bytesTransferred = count; - throw iioe; - } + } + if (iioe != null) { + iioe.bytesTransferred = count; + throw iioe; + } return count; } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/PollingOutputStream.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/PollingOutputStream.java index f8aaefa67..f98e1331c 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/PollingOutputStream.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/streams/PollingOutputStream.java @@ -151,11 +151,11 @@ public class PollingOutputStream extends FilterOutputStream { @Override public void close() throws IOException { int attempts = numAttempts - 1; // fail fast if flush() does times out - try { - out.flush(); + try { + out.flush(); attempts = 0; - } finally { - boolean stop = false; + } finally { + boolean stop = false; while (!stop) { try { out.close(); @@ -167,7 +167,7 @@ public class PollingOutputStream extends FilterOutputStream { if (Policy.DEBUG_STREAMS) System.out.println("close retry=" + attempts); //$NON-NLS-1$ } } - } + } } /** diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSet.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSet.java index 0b6cfb1fb..59608f687 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSet.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSet.java @@ -35,194 +35,194 @@ import org.osgi.service.prefs.Preferences; */ public class ActiveChangeSet extends DiffChangeSet { - private static final String CTX_TITLE = "title"; //$NON-NLS-1$ - private static final String CTX_COMMENT = "comment"; //$NON-NLS-1$ - private static final String CTX_RESOURCES = "resources"; //$NON-NLS-1$ - private static final String CTX_USER_CREATED = "userCreated"; //$NON-NLS-1$ + private static final String CTX_TITLE = "title"; //$NON-NLS-1$ + private static final String CTX_COMMENT = "comment"; //$NON-NLS-1$ + private static final String CTX_RESOURCES = "resources"; //$NON-NLS-1$ + private static final String CTX_USER_CREATED = "userCreated"; //$NON-NLS-1$ - private final ActiveChangeSetManager manager; - private String comment; + private final ActiveChangeSetManager manager; + private String comment; private boolean userCreated = true; /** * Create a change set with the given title * @param manager the manager that owns this set - * @param title the title of the set - */ - public ActiveChangeSet(ActiveChangeSetManager manager, String title) { - super(title); - this.manager = manager; - } - - /** - * Get the title of the change set. The title is used - * as the comment when the set is checking in if no comment - * has been explicitly set using <code>setComment</code>. - * @return the title of the set - */ - public String getTitle() { - return getName(); - } - - /** - * Set the title of the set. The title is used - * as the comment when the set is committed if no comment - * has been explicitly set using <code>setComment</code>. - * @param title the title of the set - */ - public void setTitle(String title) { - setName(title); - getManager().fireNameChangedEvent(this); - } - - /** - * Get the comment of this change set. If the comment - * as never been set, the title is returned as the comment - * @return the comment to be used when the set is committed - */ - @Override + * @param title the title of the set + */ + public ActiveChangeSet(ActiveChangeSetManager manager, String title) { + super(title); + this.manager = manager; + } + + /** + * Get the title of the change set. The title is used + * as the comment when the set is checking in if no comment + * has been explicitly set using <code>setComment</code>. + * @return the title of the set + */ + public String getTitle() { + return getName(); + } + + /** + * Set the title of the set. The title is used + * as the comment when the set is committed if no comment + * has been explicitly set using <code>setComment</code>. + * @param title the title of the set + */ + public void setTitle(String title) { + setName(title); + getManager().fireNameChangedEvent(this); + } + + /** + * Get the comment of this change set. If the comment + * as never been set, the title is returned as the comment + * @return the comment to be used when the set is committed + */ + @Override public String getComment() { - if (comment == null) { - return getTitle(); - } - return comment; - } - - /** - * Set the comment to be used when the change set is committed. - * If <code>null</code> is passed, the title of the set - * will be used as the comment. - * @param comment the comment for the set or <code>null</code> - * if the title should be the comment - */ - public void setComment(String comment) { - if (comment != null && comment.equals(getTitle())) { - this.comment = null; - } else { - this.comment = comment; - } - } - - /* - * Override inherited method to only include outgoing changes - */ - @Override + if (comment == null) { + return getTitle(); + } + return comment; + } + + /** + * Set the comment to be used when the change set is committed. + * If <code>null</code> is passed, the title of the set + * will be used as the comment. + * @param comment the comment for the set or <code>null</code> + * if the title should be the comment + */ + public void setComment(String comment) { + if (comment != null && comment.equals(getTitle())) { + this.comment = null; + } else { + this.comment = comment; + } + } + + /* + * Override inherited method to only include outgoing changes + */ + @Override protected boolean isValidChange(IDiff diff) { - return getManager().isModified(diff); - } - - private void addResource(IResource resource) throws CoreException { - IDiff diff = getManager().getDiff(resource); - if (diff != null) { - add(diff); - } - } - - private ActiveChangeSetManager getManager() { - return manager; - } - - /** - * Return whether the set has a comment that differs from the title. - * @return whether the set has a comment that differs from the title - */ - public boolean hasComment() { - return comment != null; - } - - public void save(Preferences prefs) { - prefs.put(CTX_TITLE, getTitle()); - if (comment != null) { - prefs.put(CTX_COMMENT, comment); - } - if (!isEmpty()) { - StringBuilder buffer = new StringBuilder(); - IResource[] resources = getResources(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - buffer.append(resource.getFullPath().toString()); - buffer.append('\n'); - } - prefs.put(CTX_RESOURCES, buffer.toString()); - } - prefs.putBoolean(CTX_USER_CREATED, isUserCreated()); - } - - public void init(Preferences prefs) { - setName(prefs.get(CTX_TITLE, "")); //$NON-NLS-1$ - comment = prefs.get(CTX_COMMENT, null); - String resourcePaths = prefs.get(CTX_RESOURCES, null); - if (resourcePaths != null) { - ResourceDiffTree tree = internalGetDiffTree(); - try { - tree.beginInput(); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - StringTokenizer tokenizer = new StringTokenizer(resourcePaths, "\n"); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - String next = tokenizer.nextToken(); - if (next.trim().length() > 0) { - IResource resource = getResource(root, next); - // Only include the resource if it is out-of-sync - try { + return getManager().isModified(diff); + } + + private void addResource(IResource resource) throws CoreException { + IDiff diff = getManager().getDiff(resource); + if (diff != null) { + add(diff); + } + } + + private ActiveChangeSetManager getManager() { + return manager; + } + + /** + * Return whether the set has a comment that differs from the title. + * @return whether the set has a comment that differs from the title + */ + public boolean hasComment() { + return comment != null; + } + + public void save(Preferences prefs) { + prefs.put(CTX_TITLE, getTitle()); + if (comment != null) { + prefs.put(CTX_COMMENT, comment); + } + if (!isEmpty()) { + StringBuilder buffer = new StringBuilder(); + IResource[] resources = getResources(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + buffer.append(resource.getFullPath().toString()); + buffer.append('\n'); + } + prefs.put(CTX_RESOURCES, buffer.toString()); + } + prefs.putBoolean(CTX_USER_CREATED, isUserCreated()); + } + + public void init(Preferences prefs) { + setName(prefs.get(CTX_TITLE, "")); //$NON-NLS-1$ + comment = prefs.get(CTX_COMMENT, null); + String resourcePaths = prefs.get(CTX_RESOURCES, null); + if (resourcePaths != null) { + ResourceDiffTree tree = internalGetDiffTree(); + try { + tree.beginInput(); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + StringTokenizer tokenizer = new StringTokenizer(resourcePaths, "\n"); //$NON-NLS-1$ + while (tokenizer.hasMoreTokens()) { + String next = tokenizer.nextToken(); + if (next.trim().length() > 0) { + IResource resource = getResource(root, next); + // Only include the resource if it is out-of-sync + try { if (resource != null && getManager().getDiff(resource) != null) { addResource(resource); } } catch (CoreException e) { TeamPlugin.log(e); } - } - } - } finally { - tree.endInput(null); - } - } - userCreated = prefs.getBoolean(CTX_USER_CREATED, true); - } - - private IResource getResource(IWorkspaceRoot root, String next) { - IResource resource = root.findMember(next); - if (resource == null) { - // May be an outgoing deletion - Path path = new Path(null, next); - if (next.charAt(next.length()-1) == IPath.SEPARATOR) { - if (path.segmentCount() == 1) { - // resource is a project - resource = root.getProject(path.lastSegment()); - } else { - // resource is a folder - resource = root.getFolder(path); - } - } else { - // resource is a file - resource = root.getFile(path); - } - } - return resource; - } - - /** - * Add the resources to the change set if they are outgoing changes. - * @param resources the resources to add. - * @throws CoreException - */ - public void add(IResource[] resources) throws CoreException { - List<IDiff> toAdd = new ArrayList<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - IDiff diff = getManager().getDiff(resource); - if (diff != null) { - toAdd.add(diff); - } - } - if (!toAdd.isEmpty()) { - add(toAdd.toArray(new IDiff[toAdd.size()])); - } - } - - /** - * Set whether this set was created by the user. - * @param userCreated whether this set was created by the user - */ + } + } + } finally { + tree.endInput(null); + } + } + userCreated = prefs.getBoolean(CTX_USER_CREATED, true); + } + + private IResource getResource(IWorkspaceRoot root, String next) { + IResource resource = root.findMember(next); + if (resource == null) { + // May be an outgoing deletion + Path path = new Path(null, next); + if (next.charAt(next.length()-1) == IPath.SEPARATOR) { + if (path.segmentCount() == 1) { + // resource is a project + resource = root.getProject(path.lastSegment()); + } else { + // resource is a folder + resource = root.getFolder(path); + } + } else { + // resource is a file + resource = root.getFile(path); + } + } + return resource; + } + + /** + * Add the resources to the change set if they are outgoing changes. + * @param resources the resources to add. + * @throws CoreException + */ + public void add(IResource[] resources) throws CoreException { + List<IDiff> toAdd = new ArrayList<>(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + IDiff diff = getManager().getDiff(resource); + if (diff != null) { + toAdd.add(diff); + } + } + if (!toAdd.isEmpty()) { + add(toAdd.toArray(new IDiff[toAdd.size()])); + } + } + + /** + * Set whether this set was created by the user. + * @param userCreated whether this set was created by the user + */ public void setUserCreated(boolean userCreated) { this.userCreated = userCreated; } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSetManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSetManager.java index 0c57ee161..a5b35c1ef 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSetManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ActiveChangeSetManager.java @@ -48,61 +48,61 @@ import org.osgi.service.prefs.Preferences; */ public abstract class ActiveChangeSetManager extends ChangeSetManager implements IDiffChangeListener, IChangeGroupingRequestor { - private static final String CTX_DEFAULT_SET = "defaultSet"; //$NON-NLS-1$ + private static final String CTX_DEFAULT_SET = "defaultSet"; //$NON-NLS-1$ - private ActiveChangeSet defaultSet; + private ActiveChangeSet defaultSet; /** - * Return the Change Set whose sync info set is the - * one given. - * @param tree a diff tree - * @return the change set for the given diff tree - */ - protected ChangeSet getChangeSet(IResourceDiffTree tree) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { + * Return the Change Set whose sync info set is the + * one given. + * @param tree a diff tree + * @return the change set for the given diff tree + */ + protected ChangeSet getChangeSet(IResourceDiffTree tree) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { ChangeSet changeSet = sets[i]; - if (((DiffChangeSet)changeSet).getDiffTree() == tree) { - return changeSet; - } - } - return null; - } - - @Override + if (((DiffChangeSet)changeSet).getDiffTree() == tree) { + return changeSet; + } + } + return null; + } + + @Override public void add(ChangeSet set) { - Assert.isTrue(set instanceof ActiveChangeSet); - super.add(set); - } + Assert.isTrue(set instanceof ActiveChangeSet); + super.add(set); + } - @Override + @Override protected void handleSetAdded(ChangeSet set) { - Assert.isTrue(set instanceof ActiveChangeSet); - ((DiffChangeSet)set).getDiffTree().addDiffChangeListener(getDiffTreeListener()); - super.handleSetAdded(set); - handleAddedResources(set, ((ActiveChangeSet)set).internalGetDiffTree().getDiffs()); - } + Assert.isTrue(set instanceof ActiveChangeSet); + ((DiffChangeSet)set).getDiffTree().addDiffChangeListener(getDiffTreeListener()); + super.handleSetAdded(set); + handleAddedResources(set, ((ActiveChangeSet)set).internalGetDiffTree().getDiffs()); + } - @Override + @Override protected void handleSetRemoved(ChangeSet set) { - ((DiffChangeSet)set).getDiffTree().removeDiffChangeListener(getDiffTreeListener()); - super.handleSetRemoved(set); - } - - /** - * Return the listener that is registered with the diff trees associated with - * the sets for this manager. - * @return the listener that is registered with the diff trees associated with - * the sets for this manager - */ - protected IDiffChangeListener getDiffTreeListener() { - return this; - } + ((DiffChangeSet)set).getDiffTree().removeDiffChangeListener(getDiffTreeListener()); + super.handleSetRemoved(set); + } + + /** + * Return the listener that is registered with the diff trees associated with + * the sets for this manager. + * @return the listener that is registered with the diff trees associated with + * the sets for this manager + */ + protected IDiffChangeListener getDiffTreeListener() { + return this; + } @Override public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) { - IResourceDiffTree tree = (IResourceDiffTree)event.getTree(); - handleSyncSetChange(tree, event.getAdditions(), getAllResources(event)); + IResourceDiffTree tree = (IResourceDiffTree)event.getTree(); + handleSyncSetChange(tree, event.getAdditions(), getAllResources(event)); } @Override @@ -123,18 +123,18 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements * @param diff the diff * @return whether the given diff represents a local change */ - public boolean isModified(IDiff diff) { - if (diff != null) { - if (diff instanceof IThreeWayDiff) { + public boolean isModified(IDiff diff) { + if (diff != null) { + if (diff instanceof IThreeWayDiff) { IThreeWayDiff twd = (IThreeWayDiff) diff; int dir = twd.getDirection(); return dir == IThreeWayDiff.OUTGOING || dir == IThreeWayDiff.CONFLICTING; } else { return diff.getKind() != IDiff.NO_CHANGE; } - } - return false; - } + } + return false; + } /** * Return the set with the given name. @@ -152,48 +152,48 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements return null; } - /** - * Create a change set containing the given files if - * they have been modified locally. - * @param title the title of the commit set - * @param files the files contained in the set - * @return the created set - * @throws CoreException - */ - public ActiveChangeSet createSet(String title, IFile[] files) throws CoreException { - List<IDiff> infos = new ArrayList<>(); - for (int i = 0; i < files.length; i++) { - IFile file = files[i]; - IDiff diff = getDiff(file); - if (diff != null) { - infos.add(diff); - } - } - return createSet(title, infos.toArray(new IDiff[infos.size()])); - } - - /** - * Create a commit set with the given title and files. The created - * set is not added to the control of the commit set manager - * so no events are fired. The set can be added using the - * <code>add</code> method. - * @param title the title of the commit set - * @param diffs the files contained in the set - * @return the created set - */ - public ActiveChangeSet createSet(String title, IDiff[] diffs) { - ActiveChangeSet commitSet = doCreateSet(title); - if (diffs != null && diffs.length > 0) { - commitSet.add(diffs); - } - return commitSet; - } - - /** - * Create a change set with the given name. - * @param name the name of the change set - * @return the created change set - */ + /** + * Create a change set containing the given files if + * they have been modified locally. + * @param title the title of the commit set + * @param files the files contained in the set + * @return the created set + * @throws CoreException + */ + public ActiveChangeSet createSet(String title, IFile[] files) throws CoreException { + List<IDiff> infos = new ArrayList<>(); + for (int i = 0; i < files.length; i++) { + IFile file = files[i]; + IDiff diff = getDiff(file); + if (diff != null) { + infos.add(diff); + } + } + return createSet(title, infos.toArray(new IDiff[infos.size()])); + } + + /** + * Create a commit set with the given title and files. The created + * set is not added to the control of the commit set manager + * so no events are fired. The set can be added using the + * <code>add</code> method. + * @param title the title of the commit set + * @param diffs the files contained in the set + * @return the created set + */ + public ActiveChangeSet createSet(String title, IDiff[] diffs) { + ActiveChangeSet commitSet = doCreateSet(title); + if (diffs != null && diffs.length > 0) { + commitSet.add(diffs); + } + return commitSet; + } + + /** + * Create a change set with the given name. + * @param name the name of the change set + * @return the created change set + */ protected ActiveChangeSet doCreateSet(String name) { return new ActiveChangeSet(this, name); } @@ -208,7 +208,7 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements * be in multiple sets. */ protected boolean isSingleSetPerResource() { - return true; + return true; } private IPath[] getAllResources(IDiffChangeEvent event) { @@ -228,7 +228,7 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements IPath path = removals[i]; allResources.add(path); } - return allResources.toArray(new IPath[allResources.size()]); + return allResources.toArray(new IPath[allResources.size()]); } /** @@ -237,29 +237,29 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements * @param diffs the diffs */ protected void handleAddedResources(ChangeSet set, IDiff[] diffs) { - if (isSingleSetPerResource() && ((ActiveChangeSet)set).isUserCreated()) { - IResource[] resources = new IResource[diffs.length]; - for (int i = 0; i < resources.length; i++) { + if (isSingleSetPerResource() && ((ActiveChangeSet)set).isUserCreated()) { + IResource[] resources = new IResource[diffs.length]; + for (int i = 0; i < resources.length; i++) { resources[i] = ((DiffChangeSet)set).getDiffTree().getResource(diffs[i]); } - // Remove the added files from any other set that contains them - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet otherSet = sets[i]; + // Remove the added files from any other set that contains them + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet otherSet = sets[i]; if (otherSet != set && ((ActiveChangeSet)otherSet).isUserCreated()) { - otherSet.remove(resources); - } - } - } + otherSet.remove(resources); + } + } + } } private void handleSyncSetChange(IResourceDiffTree tree, IDiff[] addedDiffs, IPath[] allAffectedResources) { - ChangeSet changeSet = getChangeSet(tree); - if (tree.isEmpty() && changeSet != null) { - remove(changeSet); - } - fireResourcesChangedEvent(changeSet, allAffectedResources); - handleAddedResources(changeSet, addedDiffs); + ChangeSet changeSet = getChangeSet(tree); + if (tree.isEmpty() && changeSet != null) { + remove(changeSet); + } + fireResourcesChangedEvent(changeSet, allAffectedResources); + handleAddedResources(changeSet, addedDiffs); } /** @@ -271,13 +271,13 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements * <code>null</code> to unset the default set */ public void makeDefault(ActiveChangeSet set) { - // The default set must be an active set + // The default set must be an active set if (set != null && !contains(set)) { add(set); } - ActiveChangeSet oldSet = defaultSet; - defaultSet = set; - fireDefaultChangedEvent(oldSet, defaultSet); + ActiveChangeSet oldSet = defaultSet; + defaultSet = set; + fireDefaultChangedEvent(oldSet, defaultSet); } /** @@ -287,17 +287,17 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements * @return whether the set is the default set */ public boolean isDefault(ActiveChangeSet set) { - return set == defaultSet; + return set == defaultSet; } - /** - * Return the set which is currently the default or - * <code>null</code> if there is no default set. - * @return the default change set - */ - public ActiveChangeSet getDefaultSet() { - return defaultSet; - } + /** + * Return the set which is currently the default or + * <code>null</code> if there is no default set. + * @return the default change set + */ + public ActiveChangeSet getDefaultSet() { + return defaultSet; + } /** * If the given traversals contain any resources in the active change sets, ensure @@ -336,42 +336,42 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements // No need to save the sets if the manager has never been initialized if (!isInitialized()) return; - // Clear the persisted state before saving the new state - try { - String[] oldSetNames = prefs.childrenNames(); - for (int i = 0; i < oldSetNames.length; i++) { - String string = oldSetNames[i]; - prefs.node(string).removeNode(); - } - } catch (BackingStoreException e) { - TeamPlugin.log(IStatus.ERROR, NLS.bind(Messages.SubscriberChangeSetCollector_5, new String[] { getName() }), e); - } - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; + // Clear the persisted state before saving the new state + try { + String[] oldSetNames = prefs.childrenNames(); + for (int i = 0; i < oldSetNames.length; i++) { + String string = oldSetNames[i]; + prefs.node(string).removeNode(); + } + } catch (BackingStoreException e) { + TeamPlugin.log(IStatus.ERROR, NLS.bind(Messages.SubscriberChangeSetCollector_5, new String[] { getName() }), e); + } + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; if (set instanceof ActiveChangeSet && !set.isEmpty()) { - // Since the change set title is stored explicitly, the name of - // the child preference node doesn't matter as long as it - // doesn't contain / and no two change sets get the same name. - String childPrefName = escapePrefName(((ActiveChangeSet)set).getTitle()); - Preferences child = prefs.node(childPrefName); - ((ActiveChangeSet)set).save(child); + // Since the change set title is stored explicitly, the name of + // the child preference node doesn't matter as long as it + // doesn't contain / and no two change sets get the same name. + String childPrefName = escapePrefName(((ActiveChangeSet)set).getTitle()); + Preferences child = prefs.node(childPrefName); + ((ActiveChangeSet)set).save(child); } } if (getDefaultSet() != null) { - prefs.put(CTX_DEFAULT_SET, getDefaultSet().getTitle()); + prefs.put(CTX_DEFAULT_SET, getDefaultSet().getTitle()); } else { // unset default changeset prefs.remove(CTX_DEFAULT_SET); } try { - prefs.flush(); - } catch (BackingStoreException e) { - TeamPlugin.log(IStatus.ERROR, NLS.bind(Messages.SubscriberChangeSetCollector_3, new String[] { getName() }), e); - } - } + prefs.flush(); + } catch (BackingStoreException e) { + TeamPlugin.log(IStatus.ERROR, NLS.bind(Messages.SubscriberChangeSetCollector_3, new String[] { getName() }), e); + } + } - /** + /** * Escape the given string for safe use as a preference node name by * translating / to \s (so it's a single path component) and \ to \\ (to * preserve uniqueness). @@ -406,23 +406,23 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements */ protected void load(Preferences prefs) { String defaultSetTitle = prefs.get(CTX_DEFAULT_SET, null); - try { + try { String[] childNames = prefs.childrenNames(); for (int i = 0; i < childNames.length; i++) { - String string = childNames[i]; - Preferences childPrefs = prefs.node(string); - ActiveChangeSet set = createSet(childPrefs); - if (!set.isEmpty()) { - if (getDefaultSet() == null && defaultSetTitle != null && set.getTitle().equals(defaultSetTitle)) { - makeDefault(set); - } - add(set); - } + String string = childNames[i]; + Preferences childPrefs = prefs.node(string); + ActiveChangeSet set = createSet(childPrefs); + if (!set.isEmpty()) { + if (getDefaultSet() == null && defaultSetTitle != null && set.getTitle().equals(defaultSetTitle)) { + makeDefault(set); + } + add(set); + } } } catch (BackingStoreException e) { TeamPlugin.log(IStatus.ERROR, NLS.bind(Messages.SubscriberChangeSetCollector_4, new String[] { getName() }), e); } - } + } /** * Return the name of this change set manager. @@ -430,23 +430,23 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements */ protected abstract String getName(); - /** - * Create a change set from the given preferences that were - * previously saved. - * @param childPrefs the previously saved preferences - * @return the created change set - */ - protected ActiveChangeSet createSet(Preferences childPrefs) { - // Don't specify a title when creating the change set; instead, let the - // change set read its title from the preferences. - ActiveChangeSet changeSet = doCreateSet(null); - changeSet.init(childPrefs); - return changeSet; - } - - @Override + /** + * Create a change set from the given preferences that were + * previously saved. + * @param childPrefs the previously saved preferences + * @return the created change set + */ + protected ActiveChangeSet createSet(Preferences childPrefs) { + // Don't specify a title when creating the change set; instead, let the + // change set read its title from the preferences. + ActiveChangeSet changeSet = doCreateSet(null); + changeSet.init(childPrefs); + return changeSet; + } + + @Override public void ensureChangesGrouped(IProject project, IFile[] files, - String name) throws CoreException { + String name) throws CoreException { ActiveChangeSet set = getSet(name); if (set == null) { set = createSet(name, files); @@ -456,5 +456,5 @@ public abstract class ActiveChangeSetManager extends ChangeSetManager implements set.setUserCreated(false); set.add(files); } - } + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingChangeSetManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingChangeSetManager.java index ea8c4f540..f94fd8972 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingChangeSetManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingChangeSetManager.java @@ -123,16 +123,16 @@ public class BatchingChangeSetManager extends ChangeSetManager { } } - private void fireChanges(final IProgressMonitor monitor) { - if (changes.isEmpty()) { - return; - } - final CollectorChangeEvent event = changes; - changes = new CollectorChangeEvent(this); - Object[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; - if (listener instanceof IChangeSetCollectorChangeListener) { + private void fireChanges(final IProgressMonitor monitor) { + if (changes.isEmpty()) { + return; + } + final CollectorChangeEvent event = changes; + changes = new CollectorChangeEvent(this); + Object[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; + if (listener instanceof IChangeSetCollectorChangeListener) { final IChangeSetCollectorChangeListener csccl = (IChangeSetCollectorChangeListener) listener; SafeRunner.run(new ISafeRunnable() { @Override @@ -145,44 +145,44 @@ public class BatchingChangeSetManager extends ChangeSetManager { } }); } - } + } } - @Override + @Override public void add(ChangeSet set) { - try { - beginInput(); - super.add(set); - changes.setAdded(set); - } finally { - endInput(null); - } - } - - @Override + try { + beginInput(); + super.add(set); + changes.setAdded(set); + } finally { + endInput(null); + } + } + + @Override public void remove(ChangeSet set) { - try { - beginInput(); - super.remove(set); - changes.setRemoved(set); - } finally { - endInput(null); - } - } - - @Override + try { + beginInput(); + super.remove(set); + changes.setRemoved(set); + } finally { + endInput(null); + } + } + + @Override protected void fireResourcesChangedEvent(ChangeSet changeSet, IPath[] allAffectedResources) { - super.fireResourcesChangedEvent(changeSet, allAffectedResources); - try { - beginInput(); - changes.changed(changeSet, allAffectedResources); - } finally { - endInput(null); - } - } - - @Override + super.fireResourcesChangedEvent(changeSet, allAffectedResources); + try { + beginInput(); + changes.changed(changeSet, allAffectedResources); + } finally { + endInput(null); + } + } + + @Override protected void initializeSets() { - // Nothing to do - } + // Nothing to do + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingLock.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingLock.java index eea5814a4..7c551b763 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingLock.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/BatchingLock.java @@ -86,7 +86,7 @@ public class BatchingLock { } finally { if (!success) { try { - // The begin was canceled (or some other problem occurred). + // The begin was canceled (or some other problem occurred). // Free the scheduling rule // so the clients of ReentrantLock don't need to // do an endRule when the operation is canceled. @@ -195,9 +195,9 @@ public class BatchingLock { handleAbortedFlush(e); throw e; } finally { - // We have to clear the resources no matter what since the next attempt + // We have to clear the resources no matter what since the next attempt // to flush may not have an appropriate scheduling rule - changedResources.clear(); + changedResources.clear(); } } private boolean isFlushRequired() { @@ -295,21 +295,21 @@ public class BatchingLock { * Create the ThreadInfo instance used to cache the lock state for the * current thread. Subclass can override to provide a subclass of * ThreadInfo. - * @param operation the flush operation - * @return a ThreadInfo instance - */ - protected ThreadInfo createThreadInfo(IFlushOperation operation) { - return new ThreadInfo(operation); - } + * @param operation the flush operation + * @return a ThreadInfo instance + */ + protected ThreadInfo createThreadInfo(IFlushOperation operation) { + return new ThreadInfo(operation); + } - /** + /** * Release the lock held on any resources by this thread. The provided rule must * be identical to the rule returned by the corresponding acquire(). If the rule * for the release is non-null and all remaining rules held by the lock are null, * the the flush operation provided in the acquire method will be executed. - * @param rule the scheduling rule - * @param monitor a progress monitor - * @throws TeamException + * @param rule the scheduling rule + * @param monitor a progress monitor + * @throws TeamException */ public void release(ISchedulingRule rule, IProgressMonitor monitor) throws TeamException { ThreadInfo info = getThreadInfo(); diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSet.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSet.java index 45b16a1f8..03c9e2e3e 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSet.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSet.java @@ -20,101 +20,101 @@ import org.eclipse.core.resources.IResource; */ public abstract class ChangeSet { - private String name; + private String name; - /** - * Create a change set with no name. Subclasses - * that create a change set in this manner should - * provide a name before the set is used by other clients. - */ - protected ChangeSet() { - super(); - } + /** + * Create a change set with no name. Subclasses + * that create a change set in this manner should + * provide a name before the set is used by other clients. + */ + protected ChangeSet() { + super(); + } - /** - * Create a change set with the given name. - * @param name the name of the change set - */ - public ChangeSet(String name) { - this.name = name; - } + /** + * Create a change set with the given name. + * @param name the name of the change set + */ + public ChangeSet(String name) { + this.name = name; + } - /** - * Return the resources that are contained in this set. - * @return the resources that are contained in this set - */ - public abstract IResource[] getResources(); + /** + * Return the resources that are contained in this set. + * @return the resources that are contained in this set + */ + public abstract IResource[] getResources(); - /** - * Return whether the set contains any files. - * @return whether the set contains any files - */ - public abstract boolean isEmpty(); + /** + * Return whether the set contains any files. + * @return whether the set contains any files + */ + public abstract boolean isEmpty(); - /** - * Return true if the given file is included in this set. - * @param local a local file - * @return true if the given file is included in this set - */ - public abstract boolean contains(IResource local); + /** + * Return true if the given file is included in this set. + * @param local a local file + * @return true if the given file is included in this set + */ + public abstract boolean contains(IResource local); - /** - * Remove the resource from the set. - * @param resource the resource to be removed - */ - public abstract void remove(IResource resource); + /** + * Remove the resource from the set. + * @param resource the resource to be removed + */ + public abstract void remove(IResource resource); - /** - * Remove the resources from the set. - * @param resources the resources to be removed - */ - public void remove(IResource[] resources) { - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - remove(resource); - } - } + /** + * Remove the resources from the set. + * @param resources the resources to be removed + */ + public void remove(IResource[] resources) { + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + remove(resource); + } + } - /** - * Remove the resource and it's descendants to the given depth. - * @param resource the resource to be removed - * @param depth the depth of the removal (one of - * <code>IResource.DEPTH_ZERO, IResource.DEPTH_ONE, IResource.DEPTH_INFINITE)</code> - */ - public abstract void rootRemoved(IResource resource, int depth); + /** + * Remove the resource and it's descendants to the given depth. + * @param resource the resource to be removed + * @param depth the depth of the removal (one of + * <code>IResource.DEPTH_ZERO, IResource.DEPTH_ONE, IResource.DEPTH_INFINITE)</code> + */ + public abstract void rootRemoved(IResource resource, int depth); - /** - * Return a comment describing the change. - * @return a comment describing the change - */ - public abstract String getComment(); + /** + * Return a comment describing the change. + * @return a comment describing the change + */ + public abstract String getComment(); - /** - * Return the name assigned to this set. The name should be - * unique. - * @return the name assigned to this set - */ - public String getName() { - return name; - } + /** + * Return the name assigned to this set. The name should be + * unique. + * @return the name assigned to this set + */ + public String getName() { + return name; + } - /** - * Set the name of the change set. The name of a change - * set can be changed but it is up to subclass to notify - * any interested partied of the name change. - * @param name the new name for the set - */ - protected void setName(String name) { - this.name = name; - } + /** + * Set the name of the change set. The name of a change + * set can be changed but it is up to subclass to notify + * any interested partied of the name change. + * @param name the new name for the set + */ + protected void setName(String name) { + this.name = name; + } - /** - * Return whether the set contains descendants of the given resource - * to the given depth. - * @param resource the resource - * @param depth the depth - * @return whether the set contains descendants of the given resource - * to the given depth - */ + /** + * Return whether the set contains descendants of the given resource + * to the given depth. + * @param resource the resource + * @param depth the depth + * @return whether the set contains descendants of the given resource + * to the given depth + */ public abstract boolean containsChildren(IResource resource, int depth); } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSetManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSetManager.java index 61ff6d178..ca446b0a3 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSetManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/ChangeSetManager.java @@ -27,219 +27,219 @@ import org.eclipse.core.runtime.SafeRunner; */ public abstract class ChangeSetManager { - private ListenerList<IChangeSetChangeListener> listeners = new ListenerList<IChangeSetChangeListener>(ListenerList.IDENTITY); - private Set<ChangeSet> sets; + private ListenerList<IChangeSetChangeListener> listeners = new ListenerList<IChangeSetChangeListener>(ListenerList.IDENTITY); + private Set<ChangeSet> sets; private boolean initializing; - /** - * Return the list of listeners registered with this change set manager. - * @return the list of listeners registered with this change set manager - */ - protected Object[] getListeners() { - return listeners.getListeners(); - } - - /** - * Method that can be invoked by subclasses when the name of - * a managed change set changes. - * @param set the set whose title has changed - */ - protected void fireNameChangedEvent(final ChangeSet set) { - if (initializing) - return; - if (contains(set)) { - Object[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; - SafeRunner.run(new ISafeRunnable() { - @Override + /** + * Return the list of listeners registered with this change set manager. + * @return the list of listeners registered with this change set manager + */ + protected Object[] getListeners() { + return listeners.getListeners(); + } + + /** + * Method that can be invoked by subclasses when the name of + * a managed change set changes. + * @param set the set whose title has changed + */ + protected void fireNameChangedEvent(final ChangeSet set) { + if (initializing) + return; + if (contains(set)) { + Object[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; + SafeRunner.run(new ISafeRunnable() { + @Override public void handleException(Throwable exception) { - // Exceptions are logged by the platform - } - @Override + // Exceptions are logged by the platform + } + @Override public void run() throws Exception { - listener.nameChanged(set); - } - }); - } - } - } - - /** - * Method which allows subclasses to notify listeners that the default - * set has changed. - * @param oldSet the previous default - * @param defaultSet the new default - */ - protected void fireDefaultChangedEvent(final ChangeSet oldSet, final ChangeSet defaultSet) { - if (initializing) - return; - Object[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; - SafeRunner.run(new ISafeRunnable() { - @Override + listener.nameChanged(set); + } + }); + } + } + } + + /** + * Method which allows subclasses to notify listeners that the default + * set has changed. + * @param oldSet the previous default + * @param defaultSet the new default + */ + protected void fireDefaultChangedEvent(final ChangeSet oldSet, final ChangeSet defaultSet) { + if (initializing) + return; + Object[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; + SafeRunner.run(new ISafeRunnable() { + @Override public void handleException(Throwable exception) { - // Exceptions are logged by the platform - } - @Override + // Exceptions are logged by the platform + } + @Override public void run() throws Exception { - listener.defaultSetChanged(oldSet, defaultSet); - } - }); - } - } - - /** - * Add the set to the list of active sets. - * @param set the set to be added - */ - public void add(final ChangeSet set) { - if (!contains(set)) { - internalGetSets().add(set); - handleSetAdded(set); - } - } - - /** - * Handle the set addition by notifying listeners. - * @param set the added set - */ + listener.defaultSetChanged(oldSet, defaultSet); + } + }); + } + } + + /** + * Add the set to the list of active sets. + * @param set the set to be added + */ + public void add(final ChangeSet set) { + if (!contains(set)) { + internalGetSets().add(set); + handleSetAdded(set); + } + } + + /** + * Handle the set addition by notifying listeners. + * @param set the added set + */ protected void handleSetAdded(final ChangeSet set) { - if (initializing) - return; + if (initializing) + return; Object[] listeners = getListeners(); for (int i = 0; i < listeners.length; i++) { - final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; - SafeRunner.run(new ISafeRunnable() { - @Override + final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; + SafeRunner.run(new ISafeRunnable() { + @Override public void handleException(Throwable exception) { - // Exceptions are logged by the platform - } - @Override + // Exceptions are logged by the platform + } + @Override public void run() throws Exception { - listener.setAdded(set); - } - }); + listener.setAdded(set); + } + }); } } - /** - * Remove the set from the list of active sets. - * @param set the set to be removed - */ - public void remove(final ChangeSet set) { - if (contains(set)) { - internalGetSets().remove(set); - handleSetRemoved(set); - } - } - - /** - * Handle the set removal by notifying listeners. - * @param set the removed set - */ + /** + * Remove the set from the list of active sets. + * @param set the set to be removed + */ + public void remove(final ChangeSet set) { + if (contains(set)) { + internalGetSets().remove(set); + handleSetRemoved(set); + } + } + + /** + * Handle the set removal by notifying listeners. + * @param set the removed set + */ protected void handleSetRemoved(final ChangeSet set) { - if (initializing) - return; + if (initializing) + return; Object[] listeners = getListeners(); for (int i = 0; i < listeners.length; i++) { - final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; - SafeRunner.run(new ISafeRunnable() { - @Override + final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; + SafeRunner.run(new ISafeRunnable() { + @Override public void handleException(Throwable exception) { - // Exceptions are logged by the platform - } - @Override + // Exceptions are logged by the platform + } + @Override public void run() throws Exception { - listener.setRemoved(set); - } - }); + listener.setRemoved(set); + } + }); } } - /** - * Return whether the manager contains the given commit set - * @param set the commit set being tested - * @return whether the set is contained in the manager's list of active sets - */ - public boolean contains(ChangeSet set) { - return internalGetSets().contains(set); - } - - /** - * Add the listener to the set of registered listeners. - * @param listener the listener to be added - */ - public void addListener(IChangeSetChangeListener listener) { - listeners.add(listener); - } - - /** - * Remove the listener from the set of registered listeners. - * @param listener the listener to remove - */ - public void removeListener(IChangeSetChangeListener listener) { - listeners.remove(listener); - } - - /** - * Return the list of active commit sets. - * @return the list of active commit sets - */ - public ChangeSet[] getSets() { - Set<ChangeSet> sets = internalGetSets(); + /** + * Return whether the manager contains the given commit set + * @param set the commit set being tested + * @return whether the set is contained in the manager's list of active sets + */ + public boolean contains(ChangeSet set) { + return internalGetSets().contains(set); + } + + /** + * Add the listener to the set of registered listeners. + * @param listener the listener to be added + */ + public void addListener(IChangeSetChangeListener listener) { + listeners.add(listener); + } + + /** + * Remove the listener from the set of registered listeners. + * @param listener the listener to remove + */ + public void removeListener(IChangeSetChangeListener listener) { + listeners.remove(listener); + } + + /** + * Return the list of active commit sets. + * @return the list of active commit sets + */ + public ChangeSet[] getSets() { + Set<ChangeSet> sets = internalGetSets(); return sets.toArray(new ChangeSet[sets.size()]); - } - - /** - * Dispose of any resources maintained by the manager - */ - public void dispose() { - // Nothing to do - } - - /** - * Fire resource change notifications to the listeners. - * @param changeSet - * @param allAffectedResources - */ - protected void fireResourcesChangedEvent(final ChangeSet changeSet, final IPath[] allAffectedResources) { - if (initializing) - return; - Object[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; - SafeRunner.run(new ISafeRunnable() { - @Override + } + + /** + * Dispose of any resources maintained by the manager + */ + public void dispose() { + // Nothing to do + } + + /** + * Fire resource change notifications to the listeners. + * @param changeSet + * @param allAffectedResources + */ + protected void fireResourcesChangedEvent(final ChangeSet changeSet, final IPath[] allAffectedResources) { + if (initializing) + return; + Object[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IChangeSetChangeListener listener = (IChangeSetChangeListener)listeners[i]; + SafeRunner.run(new ISafeRunnable() { + @Override public void handleException(Throwable exception) { - // Exceptions are logged by the platform - } - @Override + // Exceptions are logged by the platform + } + @Override public void run() throws Exception { - listener.resourcesChanged(changeSet, allAffectedResources); - } - }); - } - } - - private Set<ChangeSet> internalGetSets() { - if (sets == null) { - sets = Collections.synchronizedSet(new HashSet<>()); - try { - initializing = true; - initializeSets(); - } finally { - initializing = false; - } - } - return sets; - } - - /** - * Initialize the sets contained in this manager. - * This method is called the first time the sets are accessed. - */ + listener.resourcesChanged(changeSet, allAffectedResources); + } + }); + } + } + + private Set<ChangeSet> internalGetSets() { + if (sets == null) { + sets = Collections.synchronizedSet(new HashSet<>()); + try { + initializing = true; + initializeSets(); + } finally { + initializing = false; + } + } + return sets; + } + + /** + * Initialize the sets contained in this manager. + * This method is called the first time the sets are accessed. + */ protected abstract void initializeSets(); public boolean isInitialized() { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/CheckedInChangeSet.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/CheckedInChangeSet.java index 9cada75b6..92a65d4a2 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/CheckedInChangeSet.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/CheckedInChangeSet.java @@ -35,128 +35,128 @@ public abstract class CheckedInChangeSet extends ChangeSet { private final SyncInfoTree set = new SyncInfoTree(); - public abstract String getAuthor(); - - public abstract Date getDate(); - - /** - * Return the SyncInfoSet that contains the resources that belong to this change set. - * @return the SyncInfoSet that contains the resources that belong to this change set - */ - public SyncInfoTree getSyncInfoSet() { - return set; - } - - /** - * Return the resources that are contained in this set. - * @return the resources that are contained in this set - */ - @Override + public abstract String getAuthor(); + + public abstract Date getDate(); + + /** + * Return the SyncInfoSet that contains the resources that belong to this change set. + * @return the SyncInfoSet that contains the resources that belong to this change set + */ + public SyncInfoTree getSyncInfoSet() { + return set; + } + + /** + * Return the resources that are contained in this set. + * @return the resources that are contained in this set + */ + @Override public IResource[] getResources() { - return set.getResources(); - } - - /** - * Return whether the set contains any files. - * @return whether the set contains any files - */ - @Override + return set.getResources(); + } + + /** + * Return whether the set contains any files. + * @return whether the set contains any files + */ + @Override public boolean isEmpty() { - return set.isEmpty(); - } - - /** - * Return true if the given file is included in this set. - * @param local a local file - * @return true if the given file is included in this set - */ - @Override + return set.isEmpty(); + } + + /** + * Return true if the given file is included in this set. + * @param local a local file + * @return true if the given file is included in this set + */ + @Override public boolean contains(IResource local) { - return set.getSyncInfo(local) != null; - } - - /** - * Add the resource to this set if it is modified - * w.r.t. the subscriber. - * @param info - */ - public void add(SyncInfo info) { - if (isValidChange(info)) { - set.add(info); - } - } - - /** - * Return whether the given sync info is a valid change - * and can be included in this set. This method is used - * by the <code>add</code> method to filter set additions. - * @param info a sync info - * @return whether the sync info is a valid member of this set - */ - protected boolean isValidChange(SyncInfo info) { - return (info != null); - } - - /** - * Add the resources to this set if they are modified - * w.r.t. the subscriber. - * @param infos the resources to be added. - */ - public void add(SyncInfo[] infos) { - try { - set.beginInput(); - for (int i = 0; i < infos.length; i++) { - SyncInfo info = infos[i]; - add(info); - } - } finally { - set.endInput(null); - } - } - - /** - * Remove the resource from the set. - * @param resource the resource to be removed - */ - @Override + return set.getSyncInfo(local) != null; + } + + /** + * Add the resource to this set if it is modified + * w.r.t. the subscriber. + * @param info + */ + public void add(SyncInfo info) { + if (isValidChange(info)) { + set.add(info); + } + } + + /** + * Return whether the given sync info is a valid change + * and can be included in this set. This method is used + * by the <code>add</code> method to filter set additions. + * @param info a sync info + * @return whether the sync info is a valid member of this set + */ + protected boolean isValidChange(SyncInfo info) { + return (info != null); + } + + /** + * Add the resources to this set if they are modified + * w.r.t. the subscriber. + * @param infos the resources to be added. + */ + public void add(SyncInfo[] infos) { + try { + set.beginInput(); + for (int i = 0; i < infos.length; i++) { + SyncInfo info = infos[i]; + add(info); + } + } finally { + set.endInput(null); + } + } + + /** + * Remove the resource from the set. + * @param resource the resource to be removed + */ + @Override public void remove(IResource resource) { - if (contains(resource)) { - set.remove(resource); - } - } - - /** - * Remove the resources from the set. - * @param resources the resources to be removed - */ - @Override + if (contains(resource)) { + set.remove(resource); + } + } + + /** + * Remove the resources from the set. + * @param resources the resources to be removed + */ + @Override public void remove(IResource[] resources) { - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - remove(resource); - } - } - - /** - * Remove the resource and it's descendants to the given depth. - * @param resource the resource to be removed - * @param depth the depth of the removal (one of - * <code>IResource.DEPTH_ZERO, IResource.DEPTH_ONE, IResource.DEPTH_INFINITE)</code> - */ - @Override + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + remove(resource); + } + } + + /** + * Remove the resource and it's descendants to the given depth. + * @param resource the resource to be removed + * @param depth the depth of the removal (one of + * <code>IResource.DEPTH_ZERO, IResource.DEPTH_ONE, IResource.DEPTH_INFINITE)</code> + */ + @Override public void rootRemoved(IResource resource, int depth) { - SyncInfo[] infos = set.getSyncInfos(resource, depth); - if (infos.length > 0) { - IResource[] resources = new IResource[infos.length]; - for (int i = 0; i < resources.length; i++) { - resources[i] = infos[i].getLocal(); - } - set.removeAll(resources); - } - } - - @Override + SyncInfo[] infos = set.getSyncInfos(resource, depth); + if (infos.length > 0) { + IResource[] resources = new IResource[infos.length]; + for (int i = 0; i < resources.length; i++) { + resources[i] = infos[i].getLocal(); + } + set.removeAll(resources); + } + } + + @Override public boolean containsChildren(IResource resource, int depth) { - return set.getSyncInfos(resource, depth).length > 0; - } + return set.getSyncInfos(resource, depth).length > 0; + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/DiffChangeSet.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/DiffChangeSet.java index 0a0798d78..cfb3a92e1 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/DiffChangeSet.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/DiffChangeSet.java @@ -23,127 +23,127 @@ public class DiffChangeSet extends ChangeSet { private final ResourceDiffTree tree = new ResourceDiffTree(); - public DiffChangeSet() { + public DiffChangeSet() { super(); } - public DiffChangeSet(String name) { - super(name); - } + public DiffChangeSet(String name) { + super(name); + } - /** - * Return the diff tree that contains the resources that belong to this change set. - * @return the diff tree that contains the resources that belong to this change set - */ - public IResourceDiffTree getDiffTree() { - return tree; - } + /** + * Return the diff tree that contains the resources that belong to this change set. + * @return the diff tree that contains the resources that belong to this change set + */ + public IResourceDiffTree getDiffTree() { + return tree; + } - protected ResourceDiffTree internalGetDiffTree() { - return tree; - } + protected ResourceDiffTree internalGetDiffTree() { + return tree; + } - /** - * Return the resources that are contained in this set. - * @return the resources that are contained in this set - */ - @Override + /** + * Return the resources that are contained in this set. + * @return the resources that are contained in this set + */ + @Override public IResource[] getResources() { - return tree.getAffectedResources(); - } - - /** - * Return whether the set contains any files. - * @return whether the set contains any files - */ - @Override + return tree.getAffectedResources(); + } + + /** + * Return whether the set contains any files. + * @return whether the set contains any files + */ + @Override public boolean isEmpty() { - return tree.isEmpty(); - } - - /** - * Return true if the given file is included in this set. - * @param local a local file - * @return true if the given file is included in this set - */ - @Override + return tree.isEmpty(); + } + + /** + * Return true if the given file is included in this set. + * @param local a local file + * @return true if the given file is included in this set + */ + @Override public boolean contains(IResource local) { - return tree.getDiff(local) != null; - } - - /** - * Add the resource to this set if it is modified - * w.r.t. the subscriber. - * @param diff the diff to be added - */ - public void add(IDiff diff) { - if (isValidChange(diff)) { - tree.add(diff); - } - } - - /** - * Return whether the given sync info is a valid change - * and can be included in this set. This method is used - * by the <code>add</code> method to filter set additions. - * @param diff a diff - * @return whether the sync info is a valid member of this set - */ - protected boolean isValidChange(IDiff diff) { - return (diff != null); - } - - /** - * Add the resources to this set if they are modified - * w.r.t. the subscriber. - * @param diffs the resources to be added. - */ - public void add(IDiff[] diffs) { - try { - tree.beginInput(); - for (int i = 0; i < diffs.length; i++) { - IDiff diff = diffs[i]; - add(diff); - } - } finally { - tree.endInput(null); - } - } - - /** - * Remove the resource from the set. - * @param resource the resource to be removed - */ - @Override + return tree.getDiff(local) != null; + } + + /** + * Add the resource to this set if it is modified + * w.r.t. the subscriber. + * @param diff the diff to be added + */ + public void add(IDiff diff) { + if (isValidChange(diff)) { + tree.add(diff); + } + } + + /** + * Return whether the given sync info is a valid change + * and can be included in this set. This method is used + * by the <code>add</code> method to filter set additions. + * @param diff a diff + * @return whether the sync info is a valid member of this set + */ + protected boolean isValidChange(IDiff diff) { + return (diff != null); + } + + /** + * Add the resources to this set if they are modified + * w.r.t. the subscriber. + * @param diffs the resources to be added. + */ + public void add(IDiff[] diffs) { + try { + tree.beginInput(); + for (int i = 0; i < diffs.length; i++) { + IDiff diff = diffs[i]; + add(diff); + } + } finally { + tree.endInput(null); + } + } + + /** + * Remove the resource from the set. + * @param resource the resource to be removed + */ + @Override public void remove(IResource resource) { - if (contains(resource)) { - tree.remove(resource); - } - } - - /** - * Remove the resource and it's descendants to the given depth. - * @param resource the resource to be removed - * @param depth the depth of the removal (one of - * <code>IResource.DEPTH_ZERO, IResource.DEPTH_ONE, IResource.DEPTH_INFINITE)</code> - */ - @Override + if (contains(resource)) { + tree.remove(resource); + } + } + + /** + * Remove the resource and it's descendants to the given depth. + * @param resource the resource to be removed + * @param depth the depth of the removal (one of + * <code>IResource.DEPTH_ZERO, IResource.DEPTH_ONE, IResource.DEPTH_INFINITE)</code> + */ + @Override public void rootRemoved(IResource resource, int depth) { - IDiff[] diffs = tree.getDiffs(resource, depth); - if (diffs.length > 0) { - try { - tree.beginInput(); - for (int i = 0; i < diffs.length; i++) { + IDiff[] diffs = tree.getDiffs(resource, depth); + if (diffs.length > 0) { + try { + tree.beginInput(); + for (int i = 0; i < diffs.length; i++) { IDiff diff = diffs[i]; IResource r = tree.getResource(diff); if (r != null) tree.remove(r); } - } finally { - tree.endInput(null); - } - } - } + } finally { + tree.endInput(null); + } + } + } public boolean contains(IPath path) { return getDiffTree().getDiff(path) != null; diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/IChangeSetChangeListener.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/IChangeSetChangeListener.java index ec42f7711..78f125f8a 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/IChangeSetChangeListener.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/IChangeSetChangeListener.java @@ -22,41 +22,41 @@ import org.eclipse.core.runtime.IPath; */ public interface IChangeSetChangeListener { - /** - * The given set has been added to the set manager. - * @param set the added set - */ - void setAdded(ChangeSet set); - - /** - * The default change set has change to be the given set. - * All new modifications will be placed in the default - * set. - * @param previousDefault - * @param set the default set - */ - void defaultSetChanged(ChangeSet previousDefault, ChangeSet set); - - /** - * The given set has been removed from the set manager. - * @param set the removed set - */ - void setRemoved(ChangeSet set); - - /** - * The title of the given set has changed. - * @param set the set whose title changed - */ - void nameChanged(ChangeSet set); - - /** - * The state of the given resources have change with respect to the - * given set. This means that the resource have either been added - * or removed from the set. Callers can use the resources contained - * in the set to determine if each resource is an addition or removal. - * @param set the set that has changed - * @param paths the paths of the resources whose containment state has changed w.r.t the set - */ - void resourcesChanged(ChangeSet set, IPath[] paths); + /** + * The given set has been added to the set manager. + * @param set the added set + */ + void setAdded(ChangeSet set); + + /** + * The default change set has change to be the given set. + * All new modifications will be placed in the default + * set. + * @param previousDefault + * @param set the default set + */ + void defaultSetChanged(ChangeSet previousDefault, ChangeSet set); + + /** + * The given set has been removed from the set manager. + * @param set the removed set + */ + void setRemoved(ChangeSet set); + + /** + * The title of the given set has changed. + * @param set the set whose title changed + */ + void nameChanged(ChangeSet set); + + /** + * The state of the given resources have change with respect to the + * given set. This means that the resource have either been added + * or removed from the set. Callers can use the resources contained + * in the set to determine if each resource is an addition or removal. + * @param set the set that has changed + * @param paths the paths of the resources whose containment state has changed w.r.t the set + */ + void resourcesChanged(ChangeSet set, IPath[] paths); } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberChangeSetManager.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberChangeSetManager.java index 462860ca5..c34010237 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberChangeSetManager.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberChangeSetManager.java @@ -42,288 +42,288 @@ import org.osgi.service.prefs.Preferences; */ public class SubscriberChangeSetManager extends ActiveChangeSetManager { - private static final String PREF_CHANGE_SETS = "changeSets"; //$NON-NLS-1$ + private static final String PREF_CHANGE_SETS = "changeSets"; //$NON-NLS-1$ - private static final int RESOURCE_REMOVAL = 1; - private static final int RESOURCE_CHANGE = 2; + private static final int RESOURCE_REMOVAL = 1; + private static final int RESOURCE_CHANGE = 2; - private EventHandler handler; - private ResourceCollector collector; + private EventHandler handler; + private ResourceCollector collector; - /* - * Background event handler for serializing and batching change set changes - */ - private class EventHandler extends BackgroundEventHandler { + /* + * Background event handler for serializing and batching change set changes + */ + private class EventHandler extends BackgroundEventHandler { - private List<Event> dispatchEvents = new ArrayList<>(); + private List<Event> dispatchEvents = new ArrayList<>(); - protected EventHandler(String jobName, String errorTitle) { - super(jobName, errorTitle); - } + protected EventHandler(String jobName, String errorTitle) { + super(jobName, errorTitle); + } - @Override + @Override protected void processEvent(Event event, IProgressMonitor monitor) throws CoreException { - // Handle everything in the dispatch - if (isShutdown()) - throw new OperationCanceledException(); - dispatchEvents.add(event); - } + // Handle everything in the dispatch + if (isShutdown()) + throw new OperationCanceledException(); + dispatchEvents.add(event); + } - @Override + @Override protected boolean doDispatchEvents(IProgressMonitor monitor) throws TeamException { - if (dispatchEvents.isEmpty()) { - return false; - } - if (isShutdown()) - throw new OperationCanceledException(); - ResourceDiffTree[] locked = null; - try { - locked = beginDispath(); - for (Iterator iter = dispatchEvents.iterator(); iter.hasNext();) { - Event event = (Event) iter.next(); - switch (event.getType()) { - case RESOURCE_REMOVAL: - handleRemove(event.getResource()); - break; - case RESOURCE_CHANGE: - handleChange(event.getResource(), ((ResourceEvent)event).getDepth()); - break; - default: - break; - } - if (isShutdown()) - throw new OperationCanceledException(); - } - } catch (CoreException e) { + if (dispatchEvents.isEmpty()) { + return false; + } + if (isShutdown()) + throw new OperationCanceledException(); + ResourceDiffTree[] locked = null; + try { + locked = beginDispath(); + for (Iterator iter = dispatchEvents.iterator(); iter.hasNext();) { + Event event = (Event) iter.next(); + switch (event.getType()) { + case RESOURCE_REMOVAL: + handleRemove(event.getResource()); + break; + case RESOURCE_CHANGE: + handleChange(event.getResource(), ((ResourceEvent)event).getDepth()); + break; + default: + break; + } + if (isShutdown()) + throw new OperationCanceledException(); + } + } catch (CoreException e) { throw TeamException.asTeamException(e); } finally { - try { - endDispatch(locked, monitor); - } finally { - dispatchEvents.clear(); - } - } - return true; - } - - /* - * Begin input on all the sets and return the sync sets that were - * locked. If this method throws an exception then the client - * can assume that no sets were locked - */ - private ResourceDiffTree[] beginDispath() { - ChangeSet[] sets = getSets(); - List<ResourceDiffTree> lockedSets = new ArrayList<>(); - try { - for (int i = 0; i < sets.length; i++) { - ActiveChangeSet set = (ActiveChangeSet)sets[i]; - ResourceDiffTree tree = set.internalGetDiffTree(); - lockedSets.add(tree); - tree.beginInput(); - } - return lockedSets.toArray(new ResourceDiffTree[lockedSets.size()]); - } catch (RuntimeException e) { - try { - for (Iterator iter = lockedSets.iterator(); iter.hasNext();) { - ResourceDiffTree tree = (ResourceDiffTree) iter.next(); - try { - tree.endInput(null); - } catch (Throwable e1) { - // Ignore so that original exception is not masked - } - } - } catch (Throwable e1) { - // Ignore so that original exception is not masked - } - throw e; - } - } - - private void endDispatch(ResourceDiffTree[] locked, IProgressMonitor monitor) { - if (locked == null) { - // The begin failed so there's nothing to unlock - return; - } - monitor.beginTask(null, 100 * locked.length); - for (int i = 0; i < locked.length; i++) { - ResourceDiffTree tree = locked[i]; - try { - tree.endInput(Policy.subMonitorFor(monitor, 100)); - } catch (RuntimeException e) { - // Don't worry about ending every set if an error occurs. - // Instead, log the error and suggest a restart. - TeamPlugin.log(IStatus.ERROR, Messages.SubscriberChangeSetCollector_0, e); - throw e; - } - } - monitor.done(); - } - - @Override + try { + endDispatch(locked, monitor); + } finally { + dispatchEvents.clear(); + } + } + return true; + } + + /* + * Begin input on all the sets and return the sync sets that were + * locked. If this method throws an exception then the client + * can assume that no sets were locked + */ + private ResourceDiffTree[] beginDispath() { + ChangeSet[] sets = getSets(); + List<ResourceDiffTree> lockedSets = new ArrayList<>(); + try { + for (int i = 0; i < sets.length; i++) { + ActiveChangeSet set = (ActiveChangeSet)sets[i]; + ResourceDiffTree tree = set.internalGetDiffTree(); + lockedSets.add(tree); + tree.beginInput(); + } + return lockedSets.toArray(new ResourceDiffTree[lockedSets.size()]); + } catch (RuntimeException e) { + try { + for (Iterator iter = lockedSets.iterator(); iter.hasNext();) { + ResourceDiffTree tree = (ResourceDiffTree) iter.next(); + try { + tree.endInput(null); + } catch (Throwable e1) { + // Ignore so that original exception is not masked + } + } + } catch (Throwable e1) { + // Ignore so that original exception is not masked + } + throw e; + } + } + + private void endDispatch(ResourceDiffTree[] locked, IProgressMonitor monitor) { + if (locked == null) { + // The begin failed so there's nothing to unlock + return; + } + monitor.beginTask(null, 100 * locked.length); + for (int i = 0; i < locked.length; i++) { + ResourceDiffTree tree = locked[i]; + try { + tree.endInput(Policy.subMonitorFor(monitor, 100)); + } catch (RuntimeException e) { + // Don't worry about ending every set if an error occurs. + // Instead, log the error and suggest a restart. + TeamPlugin.log(IStatus.ERROR, Messages.SubscriberChangeSetCollector_0, e); + throw e; + } + } + monitor.done(); + } + + @Override protected synchronized void queueEvent(Event event, boolean front) { - // Override to allow access from enclosing class - super.queueEvent(event, front); - } - - /* - * Handle the removal - */ - private void handleRemove(IResource resource) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - // This will remove any descendants from the set and callback to - // resourcesChanged which will batch changes - if (!set.isEmpty()) { - set.rootRemoved(resource, IResource.DEPTH_INFINITE); - if (set.isEmpty()) { - remove(set); - } - } - } - } - - /* - * Handle the change - */ - private void handleChange(IResource resource, int depth) throws CoreException { - IDiff diff = getDiff(resource); - if (isModified(diff)) { - ActiveChangeSet[] containingSets = getContainingSets(resource); - if (containingSets.length == 0) { - // Consider for inclusion in the default set - // if the resource is not already a member of another set - if (getDefaultSet() != null) { - getDefaultSet().add(diff); - } - } else { - for (int i = 0; i < containingSets.length; i++) { - ActiveChangeSet set = containingSets[i]; - // Update the sync info in the set - set.add(diff); - } - } - } else { - removeFromAllSets(resource); - } - if (depth != IResource.DEPTH_ZERO) { - IResource[] members = getSubscriber().members(resource); - for (int i = 0; i < members.length; i++) { - IResource member = members[i]; - handleChange(member, depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : IResource.DEPTH_INFINITE); - } - } - } - - private void removeFromAllSets(IResource resource) { - List<ChangeSet> toRemove = new ArrayList<>(); - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (set.contains(resource)) { - set.remove(resource); - if (set.isEmpty()) { - toRemove.add(set); - } - } - } - for (Object element : toRemove) { - ActiveChangeSet set = (ActiveChangeSet) element; - remove(set); - } - } - - private ActiveChangeSet[] getContainingSets(IResource resource) { - Set<ActiveChangeSet> result = new HashSet<>(); - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (set.contains(resource)) { - result.add((ActiveChangeSet) set); - } - } - return result.toArray(new ActiveChangeSet[result.size()]); - } - } - - private class ResourceCollector extends SubscriberResourceCollector { - - public ResourceCollector(Subscriber subscriber) { - super(subscriber); - } - - @Override + // Override to allow access from enclosing class + super.queueEvent(event, front); + } + + /* + * Handle the removal + */ + private void handleRemove(IResource resource) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + // This will remove any descendants from the set and callback to + // resourcesChanged which will batch changes + if (!set.isEmpty()) { + set.rootRemoved(resource, IResource.DEPTH_INFINITE); + if (set.isEmpty()) { + remove(set); + } + } + } + } + + /* + * Handle the change + */ + private void handleChange(IResource resource, int depth) throws CoreException { + IDiff diff = getDiff(resource); + if (isModified(diff)) { + ActiveChangeSet[] containingSets = getContainingSets(resource); + if (containingSets.length == 0) { + // Consider for inclusion in the default set + // if the resource is not already a member of another set + if (getDefaultSet() != null) { + getDefaultSet().add(diff); + } + } else { + for (int i = 0; i < containingSets.length; i++) { + ActiveChangeSet set = containingSets[i]; + // Update the sync info in the set + set.add(diff); + } + } + } else { + removeFromAllSets(resource); + } + if (depth != IResource.DEPTH_ZERO) { + IResource[] members = getSubscriber().members(resource); + for (int i = 0; i < members.length; i++) { + IResource member = members[i]; + handleChange(member, depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : IResource.DEPTH_INFINITE); + } + } + } + + private void removeFromAllSets(IResource resource) { + List<ChangeSet> toRemove = new ArrayList<>(); + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (set.contains(resource)) { + set.remove(resource); + if (set.isEmpty()) { + toRemove.add(set); + } + } + } + for (Object element : toRemove) { + ActiveChangeSet set = (ActiveChangeSet) element; + remove(set); + } + } + + private ActiveChangeSet[] getContainingSets(IResource resource) { + Set<ActiveChangeSet> result = new HashSet<>(); + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (set.contains(resource)) { + result.add((ActiveChangeSet) set); + } + } + return result.toArray(new ActiveChangeSet[result.size()]); + } + } + + private class ResourceCollector extends SubscriberResourceCollector { + + public ResourceCollector(Subscriber subscriber) { + super(subscriber); + } + + @Override protected void remove(IResource resource) { - if (handler != null) - handler.queueEvent(new BackgroundEventHandler.ResourceEvent(resource, RESOURCE_REMOVAL, IResource.DEPTH_INFINITE), false); - } + if (handler != null) + handler.queueEvent(new BackgroundEventHandler.ResourceEvent(resource, RESOURCE_REMOVAL, IResource.DEPTH_INFINITE), false); + } - @Override + @Override protected void change(IResource resource, int depth) { - if (handler != null) - handler.queueEvent(new BackgroundEventHandler.ResourceEvent(resource, RESOURCE_CHANGE, depth), false); - } + if (handler != null) + handler.queueEvent(new BackgroundEventHandler.ResourceEvent(resource, RESOURCE_CHANGE, depth), false); + } - @Override + @Override protected boolean hasMembers(IResource resource) { - return SubscriberChangeSetManager.this.hasMembers(resource); - } - } + return SubscriberChangeSetManager.this.hasMembers(resource); + } + } - public SubscriberChangeSetManager(Subscriber subscriber) { - collector = new ResourceCollector(subscriber); - handler = new EventHandler(NLS.bind(Messages.SubscriberChangeSetCollector_1, new String[] { subscriber.getName() }), NLS.bind(Messages.SubscriberChangeSetCollector_2, new String[] { subscriber.getName() })); // - } + public SubscriberChangeSetManager(Subscriber subscriber) { + collector = new ResourceCollector(subscriber); + handler = new EventHandler(NLS.bind(Messages.SubscriberChangeSetCollector_1, new String[] { subscriber.getName() }), NLS.bind(Messages.SubscriberChangeSetCollector_2, new String[] { subscriber.getName() })); // + } - @Override + @Override protected void initializeSets() { - load(getPreferences()); - } - - public boolean hasMembers(IResource resource) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ActiveChangeSet set = (ActiveChangeSet)sets[i]; - if (set.getDiffTree().getChildren(resource.getFullPath()).length > 0) - return true; - } - if (getDefaultSet() != null) - return (getDefaultSet().getDiffTree().getChildren(resource.getFullPath()).length > 0); - return false; - } - - /** - * Return the sync info for the given resource obtained - * from the subscriber. - * @param resource the resource - * @return the sync info for the resource - * @throws CoreException - */ - @Override + load(getPreferences()); + } + + public boolean hasMembers(IResource resource) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ActiveChangeSet set = (ActiveChangeSet)sets[i]; + if (set.getDiffTree().getChildren(resource.getFullPath()).length > 0) + return true; + } + if (getDefaultSet() != null) + return (getDefaultSet().getDiffTree().getChildren(resource.getFullPath()).length > 0); + return false; + } + + /** + * Return the sync info for the given resource obtained + * from the subscriber. + * @param resource the resource + * @return the sync info for the resource + * @throws CoreException + */ + @Override public IDiff getDiff(IResource resource) throws CoreException { - Subscriber subscriber = getSubscriber(); - return subscriber.getDiff(resource); - } - - /** - * Return the subscriber associated with this collector. - * @return the subscriber associated with this collector - */ - public Subscriber getSubscriber() { - return collector.getSubscriber(); - } - - @Override + Subscriber subscriber = getSubscriber(); + return subscriber.getDiff(resource); + } + + /** + * Return the subscriber associated with this collector. + * @return the subscriber associated with this collector + */ + public Subscriber getSubscriber() { + return collector.getSubscriber(); + } + + @Override public void dispose() { - handler.shutdown(); - collector.dispose(); - super.dispose(); - save(getPreferences()); - } + handler.shutdown(); + collector.dispose(); + super.dispose(); + save(getPreferences()); + } - private Preferences getPreferences() { - return getParentPreferences().node(getSubscriberIdentifier()); - } + private Preferences getPreferences() { + return getParentPreferences().node(getSubscriberIdentifier()); + } private static Preferences getParentPreferences() { return getTeamPreferences().node(PREF_CHANGE_SETS); @@ -333,21 +333,21 @@ public class SubscriberChangeSetManager extends ActiveChangeSetManager { return InstanceScope.INSTANCE.getNode(TeamPlugin.getPlugin().getBundle().getSymbolicName()); } - /** - * Return the id that will uniquely identify the subscriber across - * restarts. - * @return the id that will uniquely identify the subscriber across - */ - protected String getSubscriberIdentifier() { - return getSubscriber().getName(); - } - - /** - * Wait until the collector is done processing any events. - * This method is for testing purposes only. - * @param monitor - */ - public void waitUntilDone(IProgressMonitor monitor) { + /** + * Return the id that will uniquely identify the subscriber across + * restarts. + * @return the id that will uniquely identify the subscriber across + */ + protected String getSubscriberIdentifier() { + return getSubscriber().getName(); + } + + /** + * Wait until the collector is done processing any events. + * This method is for testing purposes only. + * @param monitor + */ + public void waitUntilDone(IProgressMonitor monitor) { monitor.worked(1); // wait for the event handler to process changes. while(handler.getEventHandlerJob().getState() != Job.NONE) { @@ -359,7 +359,7 @@ public class SubscriberChangeSetManager extends ActiveChangeSetManager { Policy.checkCanceled(monitor); } monitor.worked(1); - } + } @Override protected String getName() { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberDiffTreeEventHandler.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberDiffTreeEventHandler.java index c6454da7c..4fbe86525 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberDiffTreeEventHandler.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberDiffTreeEventHandler.java @@ -205,7 +205,7 @@ public class SubscriberDiffTreeEventHandler extends SubscriberEventHandler { protected void dispatchEvents(SubscriberEvent[] events, IProgressMonitor monitor) { try { - tree.beginInput(); + tree.beginInput(); for (int i = 0; i < events.length; i++) { SubscriberEvent event = events[i]; switch (event.getType()) { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberEventHandler.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberEventHandler.java index 79355152b..94e2495a4 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberEventHandler.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberEventHandler.java @@ -310,15 +310,15 @@ public abstract class SubscriberEventHandler extends BackgroundEventHandler { break; case SubscriberEvent.CHANGE : collect( - event.getResource(), - ((ResourceEvent)event).getDepth(), + event.getResource(), + ((ResourceEvent)event).getDepth(), monitor); break; case SubscriberEvent.INITIALIZE : monitor.subTask(NLS.bind(Messages.SubscriberEventHandler_2, new String[] { event.getResource().getFullPath().toString() })); collectAll( - event.getResource(), - ((ResourceEvent)event).getDepth(), + event.getResource(), + ((ResourceEvent)event).getDepth(), Policy.subMonitorFor(monitor, 64)); break; } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberResourceCollector.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberResourceCollector.java index f202ca6e3..04b85e69f 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberResourceCollector.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberResourceCollector.java @@ -32,19 +32,19 @@ import org.eclipse.team.core.subscribers.Subscriber; */ public abstract class SubscriberResourceCollector implements IResourceChangeListener, ISubscriberChangeListener { - Subscriber subscriber; - - /** - * Create the collector and register it as a listener with the workspace - * and the subscriber. - * @param subscriber the subscriber to be associated with this collector - */ - public SubscriberResourceCollector(Subscriber subscriber) { - Assert.isNotNull(subscriber); - this.subscriber = subscriber; + Subscriber subscriber; + + /** + * Create the collector and register it as a listener with the workspace + * and the subscriber. + * @param subscriber the subscriber to be associated with this collector + */ + public SubscriberResourceCollector(Subscriber subscriber) { + Assert.isNotNull(subscriber); + this.subscriber = subscriber; ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); subscriber.addListener(this); - } + } /** * Returns the <code>Subscriber</code> associated with this collector. @@ -55,9 +55,9 @@ public abstract class SubscriberResourceCollector implements IResourceChangeList return subscriber; } - /** - * De-register the listeners for this collector. - */ + /** + * De-register the listeners for this collector. + */ public void dispose() { getSubscriber().removeListener(this); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); @@ -65,14 +65,14 @@ public abstract class SubscriberResourceCollector implements IResourceChangeList @Override public void subscriberResourceChanged(ISubscriberChangeEvent[] deltas) { - try { - beginInput(); + try { + beginInput(); IResource[] roots = getRoots(); for (int i = 0; i < deltas.length; i++) { switch (deltas[i].getFlags()) { case ISubscriberChangeEvent.SYNC_CHANGED : if (isAllRootsIncluded() || isDescendantOfRoot(deltas[i].getResource(), roots)) { - change(deltas[i].getResource(), IResource.DEPTH_ZERO); + change(deltas[i].getResource(), IResource.DEPTH_ZERO); } break; case ISubscriberChangeEvent.ROOT_REMOVED : @@ -85,42 +85,42 @@ public abstract class SubscriberResourceCollector implements IResourceChangeList break; } } - } finally { - endInput(); - } + } finally { + endInput(); + } } - /** - * This method is invoked at the beginning of a subscriber change event - * or resource delta event. The endInput method will be invoked at some point - * following this. There may be several invocations of remove or change - * in between. - */ - protected void beginInput() { - // Do nothing by default - } - - /** - * The processing of the resource or subscriber delta has finished. - * Subclasses can accumulate removals and changes and handle them - * at this point to allow batched change events. - */ - protected void endInput() { - // Do nothing by default - } + /** + * This method is invoked at the beginning of a subscriber change event + * or resource delta event. The endInput method will be invoked at some point + * following this. There may be several invocations of remove or change + * in between. + */ + protected void beginInput() { + // Do nothing by default + } + + /** + * The processing of the resource or subscriber delta has finished. + * Subclasses can accumulate removals and changes and handle them + * at this point to allow batched change events. + */ + protected void endInput() { + // Do nothing by default + } @Override public void resourceChanged(IResourceChangeEvent event) { - try { - beginInput(); + try { + beginInput(); processDelta(event.getDelta(), getRoots()); - } finally { - endInput(); - } + } finally { + endInput(); + } } - /** + /** * Process the resource delta and posts all necessary events to the background * event handler. * @@ -133,8 +133,8 @@ public abstract class SubscriberResourceCollector implements IResourceChangeList if (resource.getType() == IResource.PROJECT) { // Handle projects that should be removed from the collector if (((kind & IResourceDelta.REMOVED) != 0) /* deleted project */ - || (delta.getFlags() & IResourceDelta.OPEN) != 0 && !((IProject) resource).isOpen() /* closed project */ - || !isAncestorOfRoot(resource, roots)) /* not within subscriber roots */ { + || (delta.getFlags() & IResourceDelta.OPEN) != 0 && !((IProject) resource).isOpen() /* closed project */ + || !isAncestorOfRoot(resource, roots)) /* not within subscriber roots */ { // If the project has any entries in the sync set, remove them if (hasMembers(resource)) { remove(resource); @@ -178,8 +178,8 @@ public abstract class SubscriberResourceCollector implements IResourceChangeList * Return the root resources that are to be considered by this handler. * These may be either the subscriber roots or a set of resources that are * contained by the subscriber's roots. - * @return the root resources that are to be considered by this handler - */ + * @return the root resources that are to be considered by this handler + */ protected IResource[] getRoots() { return getSubscriber().roots(); } @@ -188,38 +188,38 @@ public abstract class SubscriberResourceCollector implements IResourceChangeList * Return whether the given resource, which is not * within the roots of this handler, has children * that are. - * @param resource the resource - * @return whether the resource has children that are being considered - * by this handler. - */ - protected abstract boolean hasMembers(IResource resource); - - /** - * The resource is no longer of concern to the subscriber. - * Remove the resource and any of it's descendants - * from the set of resources being collected. - * @param resource the resource to be removed along with its - * descendants. - */ - protected abstract void remove(IResource resource); - - /** - * The resource sync state has changed to the depth specified. - * @param resource the resource - * @param depth the depth - */ - protected abstract void change(IResource resource, int depth); + * @param resource the resource + * @return whether the resource has children that are being considered + * by this handler. + */ + protected abstract boolean hasMembers(IResource resource); + + /** + * The resource is no longer of concern to the subscriber. + * Remove the resource and any of it's descendants + * from the set of resources being collected. + * @param resource the resource to be removed along with its + * descendants. + */ + protected abstract void remove(IResource resource); + + /** + * The resource sync state has changed to the depth specified. + * @param resource the resource + * @param depth the depth + */ + protected abstract void change(IResource resource, int depth); /** * Return whether all roots of a subscriber are included or * if the collector is only consider a subset of the resources. - * @return whether all roots of a subscriber are included - */ + * @return whether all roots of a subscriber are included + */ protected boolean isAllRootsIncluded() { return true; } - private boolean isAncestorOfRoot(IResource parent, IResource[] roots) { + private boolean isAncestorOfRoot(IResource parent, IResource[] roots) { // Always traverse into projects in case a root was removed if (parent.getType() == IResource.ROOT) return true; for (int i = 0; i < roots.length; i++) { diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoCollector.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoCollector.java index 9ac9c4554..e14f38c7d 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoCollector.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoCollector.java @@ -51,7 +51,7 @@ public final class SubscriberSyncInfoCollector extends SubscriberResourceCollect * @param roots the roots of the out-of-sync resources to be collected */ public SubscriberSyncInfoCollector(Subscriber subscriber, IResource[] roots) { - super(subscriber); + super(subscriber); this.roots = roots; this.eventHandler = new SubscriberSyncInfoEventHandler(subscriber, roots); this.subscriberInput = eventHandler.getSyncSetInput(); @@ -196,18 +196,18 @@ public final class SubscriberSyncInfoCollector extends SubscriberResourceCollect reset(); } - @Override + @Override protected boolean hasMembers(IResource resource) { - return getSubscriberSyncInfoSet().hasMembers(resource); - } + return getSubscriberSyncInfoSet().hasMembers(resource); + } - @Override + @Override protected void remove(IResource resource) { - eventHandler.remove(resource); - } + eventHandler.remove(resource); + } - @Override + @Override protected void change(IResource resource, int depth) { - eventHandler.change(resource, depth); - } + eventHandler.change(resource, depth); + } } diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoEventHandler.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoEventHandler.java index a6128cd21..72379bb7c 100644 --- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoEventHandler.java +++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/subscribers/SubscriberSyncInfoEventHandler.java @@ -179,7 +179,7 @@ public class SubscriberSyncInfoEventHandler extends SubscriberEventHandler { protected void dispatchEvents(SubscriberEvent[] events, IProgressMonitor monitor) { // this will batch the following set changes until endInput is called. SubscriberSyncInfoSet syncSet = syncSetInput.getSyncSet(); - try { + try { syncSet.beginInput(); for (int i = 0; i < events.length; i++) { SubscriberEvent event = events[i]; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSAnnotateBlock.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSAnnotateBlock.java index 8a757d5bf..f9384de9f 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSAnnotateBlock.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSAnnotateBlock.java @@ -117,11 +117,11 @@ public class CVSAnnotateBlock { line = CVSMessages.CVSAnnotateBlock_5; } return NLS.bind(CVSMessages.CVSAnnotateBlock_6, (new Object[] { - user, - revision, - String.valueOf(delta), - line - })); + user, + revision, + String.valueOf(delta), + line + })); } /** diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCompareSubscriber.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCompareSubscriber.java index c5b76c497..2df39fdfa 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCompareSubscriber.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCompareSubscriber.java @@ -163,7 +163,7 @@ public class CVSCompareSubscriber extends CVSSyncTreeSubscriber implements ISubs newRoots.addAll(Arrays.asList(resources)); newRoots.removeAll(removals); resources = (IResource[]) newRoots.toArray(new IResource[newRoots.size()]); - + // Create the deltas for the removals SubscriberChangeEvent[] deltas = new SubscriberChangeEvent[removals.size()]; for (int i = 0; i < deltas.length; i++) { @@ -245,24 +245,24 @@ public class CVSCompareSubscriber extends CVSSyncTreeSubscriber implements ISubs } } - /** - * Return the tag associated with the given root resource - * or <code>null</code> if there is only a single tag - * for the subscriber. - * @param root the root resource - * @return the tag associated with the given root resource - */ - public CVSTag getTag(IResource root) { - return tree.getTag(root); - } - - /** - * Return <code>true</code> if the tag against which each - * root is compared may differ. - * @return whether the tag on each root may differ. - */ - public boolean isMultipleTagComparison() { - return getTag() == null; - } + /** + * Return the tag associated with the given root resource + * or <code>null</code> if there is only a single tag + * for the subscriber. + * @param root the root resource + * @return the tag associated with the given root resource + */ + public CVSTag getTag(IResource root) { + return tree.getTag(root); + } + + /** + * Return <code>true</code> if the tag against which each + * root is compared may differ. + * @return whether the tag on each root may differ. + */ + public boolean isMultipleTagComparison() { + return getTag() == null; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCoreFileModificationValidator.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCoreFileModificationValidator.java index 49333af1d..cc2be829e 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCoreFileModificationValidator.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSCoreFileModificationValidator.java @@ -28,63 +28,63 @@ import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; * Core validator that will load the UI validator only if a prompt is needed */ public class CVSCoreFileModificationValidator extends FileModificationValidator implements ICVSFileModificationValidator { - - FileModificationValidator uiValidator; - - @Override - public IStatus validateEdit(IFile[] files, FileModificationValidationContext context) { - IFile[] unmanagedReadOnlyFiles = getUnmanagedReadOnlyFiles(files); - if (unmanagedReadOnlyFiles.length > 0) { - IStatus status = setWritable(unmanagedReadOnlyFiles); - if (!status.isOK()) { - return status; - } - } + + FileModificationValidator uiValidator; + + @Override + public IStatus validateEdit(IFile[] files, FileModificationValidationContext context) { + IFile[] unmanagedReadOnlyFiles = getUnmanagedReadOnlyFiles(files); + if (unmanagedReadOnlyFiles.length > 0) { + IStatus status = setWritable(unmanagedReadOnlyFiles); + if (!status.isOK()) { + return status; + } + } IFile[] readOnlyFiles = getManagedReadOnlyFiles(files); if (readOnlyFiles.length == 0) return Status.OK_STATUS; return edit(readOnlyFiles, context); - } + } - @Override - public IStatus validateSave(IFile file) { + @Override + public IStatus validateSave(IFile file) { if (!needsCheckout(file)) { - if (file.isReadOnly()) { - setWritable(new IFile[] { file } ); - } - return Status.OK_STATUS; + if (file.isReadOnly()) { + setWritable(new IFile[] { file } ); + } + return Status.OK_STATUS; } return edit(new IFile[] {file}, (FileModificationValidationContext)null); - } - - /** - * Method for editing a set of files. Is overriden by the - * UI to prompt the user. Default behavior is to try and load the - * UI validator and, failing that, to edit without - * prompting. - * @param readOnlyFiles - * @param context - * @return - */ - protected IStatus edit(IFile[] readOnlyFiles, FileModificationValidationContext context) { - FileModificationValidator override = getUIValidator(); - if (override != null) { - return override.validateEdit(readOnlyFiles, context); - } else { - performEdit(readOnlyFiles); - return Status.OK_STATUS; - } - } - - private FileModificationValidator getUIValidator() { - synchronized(this) { - if (uiValidator == null) { - uiValidator = getPluggedInValidator(); - } - } - return uiValidator; - } - - @Override + } + + /** + * Method for editing a set of files. Is overriden by the + * UI to prompt the user. Default behavior is to try and load the + * UI validator and, failing that, to edit without + * prompting. + * @param readOnlyFiles + * @param context + * @return + */ + protected IStatus edit(IFile[] readOnlyFiles, FileModificationValidationContext context) { + FileModificationValidator override = getUIValidator(); + if (override != null) { + return override.validateEdit(readOnlyFiles, context); + } else { + performEdit(readOnlyFiles); + return Status.OK_STATUS; + } + } + + private FileModificationValidator getUIValidator() { + synchronized(this) { + if (uiValidator == null) { + uiValidator = getPluggedInValidator(); + } + } + return uiValidator; + } + + @Override public IStatus validateMoveDelete(IFile[] files, IProgressMonitor monitor) { IFile[] readOnlyFiles = getManagedReadOnlyFiles(files); if (readOnlyFiles.length == 0) return Status.OK_STATUS; @@ -93,30 +93,30 @@ public class CVSCoreFileModificationValidator extends FileModificationValidator return Status.OK_STATUS; } - /* - * Perform the headless edit check in the background. - * The user will be notified of any errors that occurred. - */ + /* + * Perform the headless edit check in the background. + * The user will be notified of any errors that occurred. + */ protected void performEdit(final IFile[] readOnlyFiles) { - setWritable(readOnlyFiles); - Job job = new Job(CVSMessages.CVSCoreFileModificationValidator_editJob) { - protected IStatus run(IProgressMonitor monitor) { - try { - performEdit(readOnlyFiles, monitor); - } catch (CVSException e) { - return e.getStatus(); - } - return Status.OK_STATUS; - } - }; - scheduleEditJob(job); - } - - protected void scheduleEditJob(Job job) { - job.schedule(); - } - - protected CVSTeamProvider getProvider(IFile[] files) { + setWritable(readOnlyFiles); + Job job = new Job(CVSMessages.CVSCoreFileModificationValidator_editJob) { + protected IStatus run(IProgressMonitor monitor) { + try { + performEdit(readOnlyFiles, monitor); + } catch (CVSException e) { + return e.getStatus(); + } + return Status.OK_STATUS; + } + }; + scheduleEditJob(job); + } + + protected void scheduleEditJob(Job job) { + job.schedule(); + } + + protected CVSTeamProvider getProvider(IFile[] files) { CVSTeamProvider provider = (CVSTeamProvider)RepositoryProvider.getProvider(files[0].getProject(), CVSProviderPlugin.getTypeId()); return provider; } @@ -130,7 +130,7 @@ public class CVSCoreFileModificationValidator extends FileModificationValidator if (file.isReadOnly()) { ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file); boolean managed = cvsFile.isManaged(); - return managed; + return managed; } } catch (CVSException e) { // Log the exception and assume we don't need a checkout @@ -140,21 +140,21 @@ public class CVSCoreFileModificationValidator extends FileModificationValidator } protected IStatus setWritable(final IFile[] files) { - for (int i = 0; i < files.length; i++) { - IFile file = files[i]; - ResourceAttributes attributes = file.getResourceAttributes(); - if (attributes != null) { - attributes.setReadOnly(false); - } - try { - file.setResourceAttributes(attributes); - } catch (CoreException e) { - return CVSException.wrapException(e).getStatus(); - } - } - return Status.OK_STATUS; - } - + for (int i = 0; i < files.length; i++) { + IFile file = files[i]; + ResourceAttributes attributes = file.getResourceAttributes(); + if (attributes != null) { + attributes.setReadOnly(false); + } + try { + file.setResourceAttributes(attributes); + } catch (CoreException e) { + return CVSException.wrapException(e).getStatus(); + } + } + return Status.OK_STATUS; + } + private IFile[] getManagedReadOnlyFiles(IFile[] files) { List readOnlys = new ArrayList(); for (int i = 0; i < files.length; i++) { @@ -166,7 +166,7 @@ public class CVSCoreFileModificationValidator extends FileModificationValidator return (IFile[]) readOnlys.toArray(new IFile[readOnlys.size()]); } - protected IFile[] getUnmanagedReadOnlyFiles(IFile[] files) { + protected IFile[] getUnmanagedReadOnlyFiles(IFile[] files) { List readOnlys = new ArrayList(); for (int i = 0; i < files.length; i++) { IFile iFile = files[i]; @@ -175,8 +175,8 @@ public class CVSCoreFileModificationValidator extends FileModificationValidator } } return (IFile[]) readOnlys.toArray(new IFile[readOnlys.size()]); - } - + } + private static FileModificationValidator getPluggedInValidator() { IExtension[] extensions = Platform.getExtensionRegistry().getExtensionPoint(CVSProviderPlugin.ID, CVSProviderPlugin.PT_FILE_MODIFICATION_VALIDATOR).getExtensions(); if (extensions.length == 0) @@ -195,45 +195,45 @@ public class CVSCoreFileModificationValidator extends FileModificationValidator return null; } } - - public ISchedulingRule validateEditRule(CVSResourceRuleFactory factory, IResource[] resources) { - FileModificationValidator override = getUIValidator(); - if (override instanceof CVSCoreFileModificationValidator && override != this) { - CVSCoreFileModificationValidator ui = (CVSCoreFileModificationValidator) override; - return ui.validateEditRule(factory, resources); - } - return internalValidateEditRule(factory, resources); - } - - protected final ISchedulingRule internalValidateEditRule(CVSResourceRuleFactory factory, IResource[] resources) { - if (resources.length == 0) - return null; - //optimize rule for single file - if (resources.length == 1) - return isReadOnly(resources[0]) ? factory.getParent(resources[0]) : null; - //need a lock on the parents of all read-only files - HashSet rules = new HashSet(); - for (int i = 0; i < resources.length; i++) - if (isReadOnly(resources[i])) - rules.add(factory.getParent(resources[i])); - return createSchedulingRule(rules); - } - - protected ISchedulingRule createSchedulingRule(Set rules) { - if (rules.isEmpty()) - return null; - if (rules.size() == 1) - return (ISchedulingRule) rules.iterator().next(); - ISchedulingRule[] ruleArray = (ISchedulingRule[]) rules - .toArray(new ISchedulingRule[rules.size()]); - return new MultiRule(ruleArray); - } - - protected final boolean isReadOnly(IResource resource) { - ResourceAttributes a = resource.getResourceAttributes(); - if (a != null) { - return a.isReadOnly(); - } - return false; - } + + public ISchedulingRule validateEditRule(CVSResourceRuleFactory factory, IResource[] resources) { + FileModificationValidator override = getUIValidator(); + if (override instanceof CVSCoreFileModificationValidator && override != this) { + CVSCoreFileModificationValidator ui = (CVSCoreFileModificationValidator) override; + return ui.validateEditRule(factory, resources); + } + return internalValidateEditRule(factory, resources); + } + + protected final ISchedulingRule internalValidateEditRule(CVSResourceRuleFactory factory, IResource[] resources) { + if (resources.length == 0) + return null; + //optimize rule for single file + if (resources.length == 1) + return isReadOnly(resources[0]) ? factory.getParent(resources[0]) : null; + //need a lock on the parents of all read-only files + HashSet rules = new HashSet(); + for (int i = 0; i < resources.length; i++) + if (isReadOnly(resources[i])) + rules.add(factory.getParent(resources[i])); + return createSchedulingRule(rules); + } + + protected ISchedulingRule createSchedulingRule(Set rules) { + if (rules.isEmpty()) + return null; + if (rules.size() == 1) + return (ISchedulingRule) rules.iterator().next(); + ISchedulingRule[] ruleArray = (ISchedulingRule[]) rules + .toArray(new ISchedulingRule[rules.size()]); + return new MultiRule(ruleArray); + } + + protected final boolean isReadOnly(IResource resource) { + ResourceAttributes a = resource.getResourceAttributes(); + if (a != null) { + return a.isReadOnly(); + } + return false; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSException.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSException.java index bc87a45a5..926712c09 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSException.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSException.java @@ -34,14 +34,14 @@ public class CVSException extends TeamException { private static final long serialVersionUID = 1L; - public CVSException(CoreException e) { - super(e); + public CVSException(CoreException e) { + super(e); } public CVSException(String message) { this(new CVSStatus(IStatus.ERROR, message)); } - + public CVSException(IStatus status) { super(status); } @@ -76,7 +76,7 @@ public class CVSException extends TeamException { //TODO: fix the caller to setup the error code return new CVSException(new CVSStatus(IStatus.ERROR, UNABLE, t.getMessage() != null ? t.getMessage() : "", t, (IResource)null)); //$NON-NLS-1$ } - + public static CVSException wrapException(CoreException e) { if (e instanceof CVSException) { return (CVSException)e; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMergeSubscriber.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMergeSubscriber.java index e39b8ac0b..5f38acc26 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMergeSubscriber.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMergeSubscriber.java @@ -347,6 +347,6 @@ public class CVSMergeSubscriber extends CVSSyncTreeSubscriber implements IResour if(! (other instanceof CVSMergeSubscriber)) return false; CVSMergeSubscriber s = (CVSMergeSubscriber)other; return getEndTag().equals(s.getEndTag()) && - getStartTag().equals(s.getStartTag()) && rootsEqual(s); + getStartTag().equals(s.getStartTag()) && rootsEqual(s); } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMessages.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMessages.java index d1deabbd7..879cf9e45 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMessages.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSMessages.java @@ -85,7 +85,7 @@ public class CVSMessages extends NLS { public static String CVSTeamProvider_errorGettingWatchEdit; public static String CVSTeamProvider_errorSettingWatchEdit; public static String CVSTeamProvider_updatingFolder; - public static String CVSCoreFileModificationValidator_editJob; + public static String CVSCoreFileModificationValidator_editJob; public static String ResourceDeltaVisitor_visitError; @@ -110,7 +110,7 @@ public class CVSMessages extends NLS { public static String Session_transferNoSize; public static String Session_calculatingCompressedSize; public static String Session_0; - public static String Session_sending; + public static String Session_sending; public static String Command_receivingResponses; public static String Command_warnings; @@ -122,8 +122,8 @@ public class CVSMessages extends NLS { public static String Command_noOpenSession; public static String Command_seriousServerError; - public static String Add_invalidParent; - + public static String Add_invalidParent; + public static String Commit_syncInfoMissing; public static String Commit_timestampReset; @@ -166,9 +166,9 @@ public class CVSMessages extends NLS { public static String CVSRepositoryLocation_invalidFormat; public static String CVSRepositoryLocation_openingConnection; public static String CVSRepositoryLocation_usernameRequired; - public static String CVSRepositoryLocation_hostRequired; - public static String CVSRepositoryLocation_rootRequired; - public static String CVSRepositoryLocation_noAuthenticator; + public static String CVSRepositoryLocation_hostRequired; + public static String CVSRepositoryLocation_rootRequired; + public static String CVSRepositoryLocation_noAuthenticator; public static String Util_timeout; public static String Util_processTimeout; @@ -197,7 +197,7 @@ public class CVSMessages extends NLS { public static String EclipseFile_Problem_writing_resource; public static String EclipseFolder_problem_creating; public static String EclipseFolder_isModifiedProgress; - public static String EclipseFolder_0; + public static String EclipseFolder_0; public static String EclipseSynchronizer_UpdatingSyncEndOperation; public static String EclipseSynchronizer_UpdatingSyncEndOperationCancelled; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProjectSetCapability.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProjectSetCapability.java index 8579ccfaf..6399830a4 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProjectSetCapability.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProjectSetCapability.java @@ -144,16 +144,16 @@ public class CVSProjectSetCapability extends ProjectSetCapability { // Confirm the projects to be loaded Map infoMap = new HashMap(referenceStrings.length); - IProject[] projects = asProjects(referenceStrings, infoMap); + IProject[] projects = asProjects(referenceStrings, infoMap); - projects = confirmOverwrite(context, projects); + projects = confirmOverwrite(context, projects); if (projects == null || projects.length == 0 /* No projects to import */) return new IProject[0]; Map suggestedRepositoryLocations = CVSRepositoryLocationMatcher .prepareSuggestedRepositoryLocations(projects, infoMap); - applySinglePerfectMatchesToInfoMap(suggestedRepositoryLocations, infoMap); - if (CVSRepositoryLocationMatcher.isPromptRequired(suggestedRepositoryLocations)) { + applySinglePerfectMatchesToInfoMap(suggestedRepositoryLocations, infoMap); + if (CVSRepositoryLocationMatcher.isPromptRequired(suggestedRepositoryLocations)) { // Display the dialog Map userSelectedRepositoryLocations = promptForAdditionRepositoryInformation(suggestedRepositoryLocations); // Replace repository location from a project load info with one from the prompter @@ -165,8 +165,8 @@ public class CVSProjectSetCapability extends ProjectSetCapability { } } - // Load the projects - return checkout(projects, infoMap, monitor); + // Load the projects + return checkout(projects, infoMap, monitor); } private void applySinglePerfectMatchesToInfoMap( diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProviderPlugin.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProviderPlugin.java index b84a4082e..85d9aff4b 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProviderPlugin.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSProviderPlugin.java @@ -115,38 +115,38 @@ public class CVSProviderPlugin extends Plugin { private static final String CRASH_INDICATION_FILE = ".running"; //$NON-NLS-1$ private boolean crash; - private boolean autoShareOnImport; - private boolean useProxy; - - public static final String PROXY_TYPE_HTTP = "HTTP"; //$NON-NLS-1$ - public static final String PROXY_TYPE_SOCKS5 = "SOCKS5"; //$NON-NLS-1$ - public static final String HTTP_DEFAULT_PORT = "80"; //$NON-NLS-1$ - public static final String SOCKS5_DEFAULT_PORT = "1080"; //$NON-NLS-1$ - - private String proxyType; - private String proxyHost; - private String proxyPort; - private boolean useProxyAuth; - - private CVSActiveChangeSetCollector changeSetManager; + private boolean autoShareOnImport; + private boolean useProxy; + + public static final String PROXY_TYPE_HTTP = "HTTP"; //$NON-NLS-1$ + public static final String PROXY_TYPE_SOCKS5 = "SOCKS5"; //$NON-NLS-1$ + public static final String HTTP_DEFAULT_PORT = "80"; //$NON-NLS-1$ + public static final String SOCKS5_DEFAULT_PORT = "1080"; //$NON-NLS-1$ + + private String proxyType; + private String proxyHost; + private String proxyPort; + private boolean useProxyAuth; + + private CVSActiveChangeSetCollector changeSetManager; private ServiceRegistration debugRegistration; private ServiceTracker tracker; - private static final String INFO_PROXY_USER = "org.eclipse.team.cvs.core.proxy.user"; //$NON-NLS-1$ - private static final String INFO_PROXY_PASS = "org.eclipse.team.cvs.core.proxy.pass"; //$NON-NLS-1$ - - private static final URL FAKE_URL; - static { - URL temp = null; - try { - temp = new URL("http://org.eclipse.team.cvs.proxy.auth");//$NON-NLS-1$ - } catch (MalformedURLException e) { - // Should never fail - } - FAKE_URL = temp; - } - - + private static final String INFO_PROXY_USER = "org.eclipse.team.cvs.core.proxy.user"; //$NON-NLS-1$ + private static final String INFO_PROXY_PASS = "org.eclipse.team.cvs.core.proxy.pass"; //$NON-NLS-1$ + + private static final URL FAKE_URL; + static { + URL temp = null; + try { + temp = new URL("http://org.eclipse.team.cvs.proxy.auth");//$NON-NLS-1$ + } catch (MalformedURLException e) { + // Should never fail + } + FAKE_URL = temp; + } + + public synchronized CVSWorkspaceSubscriber getCVSWorkspaceSubscriber() { if (cvsWorkspaceSubscriber == null) { cvsWorkspaceSubscriber = new CVSWorkspaceSubscriber( @@ -282,7 +282,7 @@ public class CVSProviderPlugin extends Plugin { * @param consoleListener the listener */ public void setConsoleListener(IConsoleListener consoleListener) { - ConsoleListeners.getInstance().addListener(consoleListener); + ConsoleListeners.getInstance().addListener(consoleListener); } @Override @@ -312,8 +312,8 @@ public class CVSProviderPlugin extends Plugin { // Must load the change set manager on startup since it listens to deltas getChangeSetManager(); - tracker = new ServiceTracker(getBundle().getBundleContext(), IJSchService.class.getName(), null); - tracker.open(); + tracker = new ServiceTracker(getBundle().getBundleContext(), IJSchService.class.getName(), null); + tracker.open(); } @Override @@ -638,13 +638,13 @@ public class CVSProviderPlugin extends Plugin { this.usePlatformLineend = usePlatformLineend; } - public void setAutoshareOnImport(boolean autoShareOnImport) { - this.autoShareOnImport = autoShareOnImport; - } + public void setAutoshareOnImport(boolean autoShareOnImport) { + this.autoShareOnImport = autoShareOnImport; + } - public boolean isAutoshareOnImport() { - return autoShareOnImport; - } + public boolean isAutoshareOnImport() { + return autoShareOnImport; + } /** * @return Returns the watchOnEdit. @@ -652,93 +652,93 @@ public class CVSProviderPlugin extends Plugin { public boolean isWatchOnEdit() { return getPluginPreferences().getBoolean(CVSProviderPlugin.ENABLE_WATCH_ON_EDIT); } - - // proxy configuration - - public void setUseProxy(boolean useProxy) { - this.useProxy = useProxy; - } - - public boolean isUseProxy() { - return this.useProxy; - } - - public void setProxyType(String proxyType) { - this.proxyType = proxyType; - } - - public String getProxyType() { - return this.proxyType; - } - - public void setProxyHost(String proxyHost) { - this.proxyHost = proxyHost; - } - - public String getProxyHost() { - return this.proxyHost; - } - - public void setProxyPort(String proxyPort) { - this.proxyPort = proxyPort; - } - - public String getProxyPort() { - return this.proxyPort; - } - - public void setUseProxyAuth(boolean useProxyAuth) { - this.useProxyAuth = useProxyAuth; - } - - public boolean isUseProxyAuth() { - return this.useProxyAuth; - } - - public String getProxyUser() { - Object user = getAuthInfo().get(INFO_PROXY_USER); - return user==null ? "" : (String) user; //$NON-NLS-1$ - } - - public String getProxyPassword() { - Object pass = getAuthInfo().get(INFO_PROXY_PASS); - return pass==null ? "" : (String) pass; //$NON-NLS-1$ - } - - private Map getAuthInfo() { - // Retrieve username and password from keyring. - Map authInfo = Platform.getAuthorizationInfo(FAKE_URL, "proxy", ""); //$NON-NLS-1$ //$NON-NLS-2$ - return authInfo!=null ? authInfo : Collections.EMPTY_MAP; - } - - public void setProxyAuth(String proxyUser, String proxyPass) { - Map authInfo = getAuthInfo(); - if (authInfo.size()==0) { - authInfo = new java.util.HashMap(4); - } - if (proxyUser != null) { - authInfo.put(INFO_PROXY_USER, proxyUser); - } - if (proxyPass != null) { - authInfo.put(INFO_PROXY_PASS, proxyPass); - } - try { - Platform.addAuthorizationInfo(FAKE_URL, "proxy", "", authInfo); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (CoreException e) { - // We should probably wrap the CoreException here! - CVSProviderPlugin.log(e); - } - } - - public synchronized ActiveChangeSetManager getChangeSetManager() { - if (changeSetManager == null) { - changeSetManager = new CVSActiveChangeSetCollector(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); - } - return changeSetManager; - } - - public IJSchService getJSchService() { - return (IJSchService)tracker.getService(); - } - + + // proxy configuration + + public void setUseProxy(boolean useProxy) { + this.useProxy = useProxy; + } + + public boolean isUseProxy() { + return this.useProxy; + } + + public void setProxyType(String proxyType) { + this.proxyType = proxyType; + } + + public String getProxyType() { + return this.proxyType; + } + + public void setProxyHost(String proxyHost) { + this.proxyHost = proxyHost; + } + + public String getProxyHost() { + return this.proxyHost; + } + + public void setProxyPort(String proxyPort) { + this.proxyPort = proxyPort; + } + + public String getProxyPort() { + return this.proxyPort; + } + + public void setUseProxyAuth(boolean useProxyAuth) { + this.useProxyAuth = useProxyAuth; + } + + public boolean isUseProxyAuth() { + return this.useProxyAuth; + } + + public String getProxyUser() { + Object user = getAuthInfo().get(INFO_PROXY_USER); + return user==null ? "" : (String) user; //$NON-NLS-1$ + } + + public String getProxyPassword() { + Object pass = getAuthInfo().get(INFO_PROXY_PASS); + return pass==null ? "" : (String) pass; //$NON-NLS-1$ + } + + private Map getAuthInfo() { + // Retrieve username and password from keyring. + Map authInfo = Platform.getAuthorizationInfo(FAKE_URL, "proxy", ""); //$NON-NLS-1$ //$NON-NLS-2$ + return authInfo!=null ? authInfo : Collections.EMPTY_MAP; + } + + public void setProxyAuth(String proxyUser, String proxyPass) { + Map authInfo = getAuthInfo(); + if (authInfo.size()==0) { + authInfo = new java.util.HashMap(4); + } + if (proxyUser != null) { + authInfo.put(INFO_PROXY_USER, proxyUser); + } + if (proxyPass != null) { + authInfo.put(INFO_PROXY_PASS, proxyPass); + } + try { + Platform.addAuthorizationInfo(FAKE_URL, "proxy", "", authInfo); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (CoreException e) { + // We should probably wrap the CoreException here! + CVSProviderPlugin.log(e); + } + } + + public synchronized ActiveChangeSetManager getChangeSetManager() { + if (changeSetManager == null) { + changeSetManager = new CVSActiveChangeSetCollector(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); + } + return changeSetManager; + } + + public IJSchService getJSchService() { + return (IJSchService)tracker.getService(); + } + } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSResourceRuleFactory.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSResourceRuleFactory.java index b92be5df6..db3d55b0a 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSResourceRuleFactory.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSResourceRuleFactory.java @@ -18,12 +18,12 @@ import org.eclipse.core.resources.team.ResourceRuleFactory; import org.eclipse.core.runtime.jobs.ISchedulingRule; public class CVSResourceRuleFactory extends ResourceRuleFactory { - public ISchedulingRule validateEditRule(IResource[] resources) { - return CVSTeamProvider.internalGetFileModificationValidator().validateEditRule(this, resources); - } - - public ISchedulingRule getParent(IResource resource) { - return parent(resource); - } - + public ISchedulingRule validateEditRule(IResource[] resources) { + return CVSTeamProvider.internalGetFileModificationValidator().validateEditRule(this, resources); + } + + public ISchedulingRule getParent(IResource resource) { + return parent(resource); + } + }
\ No newline at end of file diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSRevisionNumberCompareCriteria.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSRevisionNumberCompareCriteria.java index 3f3164600..3fda18b5e 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSRevisionNumberCompareCriteria.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSRevisionNumberCompareCriteria.java @@ -24,7 +24,7 @@ import org.eclipse.team.internal.ccvs.core.syncinfo.ResourceSyncInfo; * CVSRevisionNumberCompareCriteria */ public class CVSRevisionNumberCompareCriteria implements IResourceVariantComparator { - + private boolean isThreeWay; public CVSRevisionNumberCompareCriteria(boolean isThreeWay) { diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSStatus.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSStatus.java index 1e8306d93..ac05beb4f 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSStatus.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSStatus.java @@ -98,46 +98,46 @@ public class CVSStatus extends TeamStatus { return message; } - /** - * Return whether this status is wrapping an internal error. - * An internal error is any error for which the wrapped exception - * is not a CVS exception. Check deeply to make sure there isn't - * an internal error buried deep down. - * @return whether this status is wrapping an internal error - */ - public boolean isInternalError() { - Throwable ex = getException(); - if (ex instanceof CVSException) { - CVSException cvsEx = (CVSException) ex; - IStatus status = cvsEx.getStatus(); - return isInternalError(status); - } - return ex != null; - } + /** + * Return whether this status is wrapping an internal error. + * An internal error is any error for which the wrapped exception + * is not a CVS exception. Check deeply to make sure there isn't + * an internal error buried deep down. + * @return whether this status is wrapping an internal error + */ + public boolean isInternalError() { + Throwable ex = getException(); + if (ex instanceof CVSException) { + CVSException cvsEx = (CVSException) ex; + IStatus status = cvsEx.getStatus(); + return isInternalError(status); + } + return ex != null; + } - /** - * Return whether this status is wrapping an internal error. - * An internal error is any error for which the wrapped exception - * is not a CVS exception. Check deeply to make sure there isn't - * an internal error buried deep down. - * @return whether this status is wrapping an internal error - */ - public static boolean isInternalError(IStatus status) { - if (status instanceof CVSStatus) { - return ((CVSStatus)status).isInternalError(); - } - if (status.isMultiStatus()) { - IStatus[] children = status.getChildren(); - for (int i = 0; i < children.length; i++) { - IStatus child = children[i]; - if (isInternalError(child)) { - return true; - } - } - return false; - } - return true; - } + /** + * Return whether this status is wrapping an internal error. + * An internal error is any error for which the wrapped exception + * is not a CVS exception. Check deeply to make sure there isn't + * an internal error buried deep down. + * @return whether this status is wrapping an internal error + */ + public static boolean isInternalError(IStatus status) { + if (status instanceof CVSStatus) { + return ((CVSStatus)status).isInternalError(); + } + if (status.isMultiStatus()) { + IStatus[] children = status.getChildren(); + for (int i = 0; i < children.length; i++) { + IStatus child = children[i]; + if (isInternalError(child)) { + return true; + } + } + return false; + } + return true; + } public ICVSRepositoryLocation getCvsLocation() { if (cvsLocation==null){ diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java index 7c14f4080..a5984d346 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java @@ -267,13 +267,13 @@ public class CVSSyncInfo extends SyncInfo { * </ul> * </ul> */ - public IStatus makeInSync() throws CVSException { - - // Only works on folders + public IStatus makeInSync() throws CVSException { + + // Only works on folders if (getLocal().getType() == IResource.FILE) { return new CVSStatus(IStatus.WARNING, INVALID_RESOURCE_TYPE, NLS.bind(CVSMessages.CVSSyncInfo_7, new String[] { getLocal().getFullPath().toString()}), getLocal()); } - + // Only works on outgoing and conflicting changes boolean outgoing = (getKind() & DIRECTION_MASK) == OUTGOING; if (outgoing) { @@ -318,9 +318,9 @@ public class CVSSyncInfo extends SyncInfo { // It is also impossible for an incomming folder to be static. FolderSyncInfo remoteInfo = remote.getFolderSyncInfo(); FolderSyncInfo localInfo = local.getParent().getFolderSyncInfo(); - MutableFolderSyncInfo newInfo = remoteInfo.cloneMutable(); - newInfo.setTag(localInfo.getTag()); - newInfo.setStatic(false); + MutableFolderSyncInfo newInfo = remoteInfo.cloneMutable(); + newInfo.setTag(localInfo.getTag()); + newInfo.setStatic(false); local.setFolderSyncInfo(newInfo); return Status.OK_STATUS; } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java index 0b0a8bf36..754c44908 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProvider.java @@ -100,26 +100,26 @@ public class CVSTeamProvider extends RepositoryProvider { * @param project the project */ public static void markAsTempShare(IProject project) { - if (RepositoryProvider.isShared(project)) - return; - try { - project.setSessionProperty(CVSTeamProvider.TEMP_SHARED, Boolean.TRUE); + if (RepositoryProvider.isShared(project)) + return; + try { + project.setSessionProperty(CVSTeamProvider.TEMP_SHARED, Boolean.TRUE); } catch (CoreException e) { CVSProviderPlugin.log(e); } } - /** - * Return the file modification validator used for all CVS repository providers. - * @return the file modification validator used for all CVS repository providers - */ - protected static CVSCoreFileModificationValidator internalGetFileModificationValidator() { - if (CVSTeamProvider.fileModificationValidator == null) { - CVSTeamProvider.fileModificationValidator = new CVSCoreFileModificationValidator(); - } - return CVSTeamProvider.fileModificationValidator; - } - + /** + * Return the file modification validator used for all CVS repository providers. + * @return the file modification validator used for all CVS repository providers + */ + protected static CVSCoreFileModificationValidator internalGetFileModificationValidator() { + if (CVSTeamProvider.fileModificationValidator == null) { + CVSTeamProvider.fileModificationValidator = new CVSCoreFileModificationValidator(); + } + return CVSTeamProvider.fileModificationValidator; + } + /** * No-arg Constructor for IProjectNature conformance */ @@ -184,13 +184,13 @@ public class CVSTeamProvider extends RepositoryProvider { /* * Generate an exception if the resource is not a child of the project */ - private void checkIsChild(IResource resource) throws CVSException { - if (!isChildResource(resource)) - throw new CVSException(new Status(IStatus.ERROR, CVSProviderPlugin.ID, TeamException.UNABLE, - NLS.bind(CVSMessages.CVSTeamProvider_invalidResource, (new Object[] {resource.getFullPath().toString(), project.getName()})), - null)); - } - + private void checkIsChild(IResource resource) throws CVSException { + if (!isChildResource(resource)) + throw new CVSException(new Status(IStatus.ERROR, CVSProviderPlugin.ID, TeamException.UNABLE, + NLS.bind(CVSMessages.CVSTeamProvider_invalidResource, (new Object[] {resource.getFullPath().toString(), project.getName()})), + null)); + } + /* * Get the arguments to be passed to a commit or update */ @@ -242,8 +242,8 @@ public class CVSTeamProvider extends RepositoryProvider { FolderSyncInfo info = folder.getFolderSyncInfo(); if (info != null) { monitor1.subTask(NLS.bind(CVSMessages.CVSTeamProvider_updatingFolder, new String[] { info.getRepository() })); - MutableFolderSyncInfo newInfo = info.cloneMutable(); - newInfo.setRoot(root); + MutableFolderSyncInfo newInfo = info.cloneMutable(); + newInfo.setRoot(root); folder.setFolderSyncInfo(newInfo); folder.acceptChildren(this); } @@ -833,9 +833,9 @@ public class CVSTeamProvider extends RepositoryProvider { @Override public IFileHistoryProvider getFileHistoryProvider() { - if (CVSTeamProvider.fileHistoryProvider == null) { - CVSTeamProvider.fileHistoryProvider = new CVSFileHistoryProvider(); - } - return CVSTeamProvider.fileHistoryProvider; + if (CVSTeamProvider.fileHistoryProvider == null) { + CVSTeamProvider.fileHistoryProvider = new CVSFileHistoryProvider(); + } + return CVSTeamProvider.fileHistoryProvider; } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProviderType.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProviderType.java index c448cf678..7e3573456 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProviderType.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSTeamProviderType.java @@ -171,8 +171,8 @@ public class CVSTeamProviderType extends RepositoryProviderType implements IAdap TeamPlugin.log(IStatus.ERROR, "Could not flag meta-files as team-private for " + cvsDir.getFullPath(), e); //$NON-NLS-1$ } } - if (CVSProviderPlugin.getPlugin().isAutoshareOnImport()) - getAutoShareJob().share(project); + if (CVSProviderPlugin.getPlugin().isAutoshareOnImport()) + getAutoShareJob().share(project); } @Override diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSFolder.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSFolder.java index fb60f80f5..6092771d8 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSFolder.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSFolder.java @@ -57,7 +57,7 @@ public interface ICVSFolder extends ICVSResource { * Answers and array of <code>ICVSResource</code> elements that are immediate * children of this remote resource, in no particular order. The server may be contacted. * - * @param monitor a progress monitor to indicate the duration of the operation, or + * @param monitor a progress monitor to indicate the duration of the operation, or * <code>null</code> if progress reporting is not required. * * @return array of immediate children of this remote resource. diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFile.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFile.java index be47baf77..b91adb72c 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFile.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFile.java @@ -20,14 +20,14 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.team.core.TeamException; /** - * This interface represents a file in a repository. - * Instances of this interface can be used to fetch the contents - * of the remote file. - * - * In the future, additional information should be available (tags, revisions, etc.) - * - * Clients are not expected to implement this interface. - */ + * This interface represents a file in a repository. + * Instances of this interface can be used to fetch the contents + * of the remote file. + * + * In the future, additional information should be available (tags, revisions, etc.) + * + * Clients are not expected to implement this interface. + */ public interface ICVSRemoteFile extends ICVSRemoteResource, ICVSFile { /** diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFolder.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFolder.java index 9de9d9883..ea276b78e 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFolder.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/ICVSRemoteFolder.java @@ -17,11 +17,11 @@ package org.eclipse.team.internal.ccvs.core; import org.eclipse.team.internal.ccvs.core.client.Command.LocalOption; /** - * This interface represents a remote folder in a repository. It provides - * access to the members (remote files and folders) of a remote folder - * - * Clients are not expected to implement this interface. - */ + * This interface represents a remote folder in a repository. It provides + * access to the members (remote files and folders) of a remote folder + * + * Clients are not expected to implement this interface. + */ public interface ICVSRemoteFolder extends ICVSRemoteResource, ICVSFolder { // This constant is the name of the folder at the root of a repository diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/IUserAuthenticator.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/IUserAuthenticator.java index f35628eb9..10313ce9a 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/IUserAuthenticator.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/IUserAuthenticator.java @@ -129,14 +129,14 @@ public interface IUserAuthenticator { */ public int prompt(ICVSRepositoryLocation location, int promptType, String title, String message, int[] promptResponses, int defaultResponseIndex); - /** - * The host key for the given location has changed. - * @param location - * @return true if new host key should be accepted - */ - public boolean promptForHostKeyChange(ICVSRepositoryLocation location); - - /** + /** + * The host key for the given location has changed. + * @param location + * @return true if new host key should be accepted + */ + public boolean promptForHostKeyChange(ICVSRepositoryLocation location); + + /** * If the project set contains only partial repository information (some of * location are unknown) we will display a dialog to associate each project * set repository with a known repository location or create a new one or at diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/Policy.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/Policy.java index b0371deb7..7aabf568d 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/Policy.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/Policy.java @@ -74,39 +74,39 @@ public class Policy { } public static boolean isDebugProtocol() { - return DEBUG_CVS_PROTOCOL || recorder != null; + return DEBUG_CVS_PROTOCOL || recorder != null; } public static void printProtocolLine(String line) { - printProtocol(line, true); + printProtocol(line, true); } - public static void printProtocol(String string, boolean newLine) { - if (DEBUG_CVS_PROTOCOL) { - System.out.print(string); - if (newLine) { - System.out.println(); - } - } - if (recorder != null) { - recorder.print(string); - if (newLine) { - recorder.println(); - } - } - } - - public static String getMessage(String key) { - try { - Field f = CVSMessages.class.getDeclaredField(key); - Object o = f.get(null); - if (o instanceof String) - return (String)o; - } catch (SecurityException e) { - } catch (NoSuchFieldException e) { - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } - return null; - } + public static void printProtocol(String string, boolean newLine) { + if (DEBUG_CVS_PROTOCOL) { + System.out.print(string); + if (newLine) { + System.out.println(); + } + } + if (recorder != null) { + recorder.print(string); + if (newLine) { + recorder.println(); + } + } + } + + public static String getMessage(String key) { + try { + Field f = CVSMessages.class.getDeclaredField(key); + Object o = f.get(null); + if (o instanceof String) + return (String)o; + } catch (SecurityException e) { + } catch (NoSuchFieldException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalAccessException e) { + } + return null; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/AbstractStructureVisitor.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/AbstractStructureVisitor.java index 6de8222b1..ee7934bc5 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/AbstractStructureVisitor.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/AbstractStructureVisitor.java @@ -44,8 +44,8 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { protected boolean sendQuestionable; protected boolean sendModifiedContents; private boolean sendBinary; - - private boolean recurse = true; + + private boolean recurse = true; public AbstractStructureVisitor(Session session, LocalOption[] localOptions, boolean sendQuestionable, boolean sendModifiedContents) { this(session, localOptions, sendQuestionable, sendModifiedContents, true); @@ -56,8 +56,8 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { this.sendQuestionable = sendQuestionable; this.sendModifiedContents = sendModifiedContents; this.sendBinary = sendBinary; - if (Command.DO_NOT_RECURSE.isElementOf(localOptions)) - recurse = false; + if (Command.DO_NOT_RECURSE.isElementOf(localOptions)) + recurse = false; } /** @@ -107,7 +107,7 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { if (isLastSent(mFolder)) return; // Do not send virtual directories - if (isCVSFolder && info.isVirtualDirectory()) { + if (isCVSFolder && info.isVirtualDirectory()) { return; } @@ -171,7 +171,7 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { boolean isManaged = syncBytes != null; if (isManaged) { - sendPendingNotification(mFile); + sendPendingNotification(mFile); } else { // If the file is not managed, send a questionable to the server if the file exists locally // A unmanaged, locally non-existant file results from the explicit use of the file name as a command argument @@ -190,15 +190,15 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { boolean sendContents = mFile.exists() && mFile.isModified(monitor) && !mFile.getSyncInfo().isNeedsMerge(mFile.getTimeStamp()); if (ResourceSyncInfo.isDeletion(syncBytes)) { - sendEntryLineToServer(mFile, syncBytes); + sendEntryLineToServer(mFile, syncBytes); } else if (sendContents) { - // Perform the send of modified contents in a sheduling rule to ensure that - // the contents are not modified while we are sending them - final IResource resource = mFile.getIResource(); - try { - if (resource != null) - Job.getJobManager().beginRule(resource, monitor); - + // Perform the send of modified contents in a sheduling rule to ensure that + // the contents are not modified while we are sending them + final IResource resource = mFile.getIResource(); + try { + if (resource != null) + Job.getJobManager().beginRule(resource, monitor); + sendEntryLineToServer(mFile, syncBytes); if (mFile.exists() && mFile.isModified(null)) { boolean binary = ResourceSyncInfo.isBinary(syncBytes); @@ -210,26 +210,26 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { } else { session.sendUnchanged(mFile); } - } finally { - if (resource != null) - Job.getJobManager().endRule(resource); - } + } finally { + if (resource != null) + Job.getJobManager().endRule(resource); + } } else { - sendEntryLineToServer(mFile, syncBytes); + sendEntryLineToServer(mFile, syncBytes); session.sendUnchanged(mFile); } monitor.worked(1); } - private void sendEntryLineToServer(ICVSFile mFile, byte[] syncBytes) throws CVSException { - if (syncBytes != null) { - String syncBytesToServer = ResourceSyncInfo.getTimestampToServer(syncBytes, mFile.getTimeStamp()); - session.sendEntry(syncBytes, syncBytesToServer); - } - } + private void sendEntryLineToServer(ICVSFile mFile, byte[] syncBytes) throws CVSException { + if (syncBytes != null) { + String syncBytesToServer = ResourceSyncInfo.getTimestampToServer(syncBytes, mFile.getTimeStamp()); + session.sendEntry(syncBytes, syncBytesToServer); + } + } - protected void sendPendingNotification(ICVSFile mFile) throws CVSException { + protected void sendPendingNotification(ICVSFile mFile) throws CVSException { NotifyInfo notify = mFile.getPendingNotification(); if (notify != null) { sendFolder(mFile.getParent()); @@ -284,16 +284,16 @@ abstract class AbstractStructureVisitor implements ICVSResourceVisitor { } } - /** - * Return a send file message that contains one argument slot - * for the file name. - * @return a send file message that contains one argument slot - * for the file name - */ + /** + * Return a send file message that contains one argument slot + * for the file name. + * @return a send file message that contains one argument slot + * for the file name + */ protected String getSendFileMessage() { return CVSMessages.AbstractStructureVisitor_sendingFile; } - public boolean isRecurse() { - return recurse; - } + public boolean isRecurse() { + return recurse; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Add.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Add.java index 91648de5b..d2917d4f0 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Add.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Add.java @@ -67,8 +67,8 @@ public class Add extends Command { status = mergeStatus(status, new CVSStatus(IStatus.ERROR, NLS.bind(CVSMessages.Add_invalidParent, new String[] { mFolder.getRelativePath(session.getLocalRoot()) }))); } else { String repository = info.getRepository() + "/" + mFolder.getName(); //$NON-NLS-1$ - MutableFolderSyncInfo newInfo = info.cloneMutable(); - newInfo.setRepository(repository); + MutableFolderSyncInfo newInfo = info.cloneMutable(); + newInfo.setRepository(repository); mFolder.setFolderSyncInfo(newInfo); } } @@ -77,22 +77,22 @@ public class Add extends Command { } @Override - protected ICommandOutputListener getDefaultCommandOutputListener() { - return new CommandOutputListener() { - public IStatus errorLine(String line, - ICVSRepositoryLocation location, ICVSFolder commandRoot, - IProgressMonitor monitor) { - - String serverMessage = getServerMessage(line, location); - if (serverMessage != null) { - if (serverMessage.indexOf("cvs commit") != -1 && serverMessage.indexOf("add") != -1 && serverMessage.indexOf("permanently") != -1) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - return OK; - if (serverMessage.startsWith("scheduling file") && serverMessage.indexOf("for addition") != -1) //$NON-NLS-1$ //$NON-NLS-2$ - return OK; - } - return super.errorLine(line, location, commandRoot, monitor); - } - }; - } + protected ICommandOutputListener getDefaultCommandOutputListener() { + return new CommandOutputListener() { + public IStatus errorLine(String line, + ICVSRepositoryLocation location, ICVSFolder commandRoot, + IProgressMonitor monitor) { + + String serverMessage = getServerMessage(line, location); + if (serverMessage != null) { + if (serverMessage.indexOf("cvs commit") != -1 && serverMessage.indexOf("add") != -1 && serverMessage.indexOf("permanently") != -1) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + return OK; + if (serverMessage.startsWith("scheduling file") && serverMessage.indexOf("for addition") != -1) //$NON-NLS-1$ //$NON-NLS-2$ + return OK; + } + return super.errorLine(line, location, commandRoot, monitor); + } + }; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Annotate.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Annotate.java index 043837727..d163ef33f 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Annotate.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Annotate.java @@ -20,7 +20,7 @@ package org.eclipse.team.internal.ccvs.core.client; */ public class Annotate extends AbstractMessageCommand { - public static final Object FORCE_BINARY_ANNOTATE = new LocalOption("-F"); //$NON-NLS-1$ + public static final Object FORCE_BINARY_ANNOTATE = new LocalOption("-F"); //$NON-NLS-1$ protected Annotate() { } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Checkout.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Checkout.java index eecda7900..4b0193f9c 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Checkout.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Checkout.java @@ -179,8 +179,8 @@ public class Checkout extends Command { return RemoteModule.createRemoteModules(moduleDefinitionListener.getModuleExpansions(), session.getCVSRepositoryLocation(), tag); } - - protected String getDisplayText() { - return "checkout"; //$NON-NLS-1$ - } + + protected String getDisplayText() { + return "checkout"; //$NON-NLS-1$ + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Command.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Command.java index e9a6ebee8..aa8018827 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Command.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Command.java @@ -79,7 +79,7 @@ public abstract class Command extends Request { // Empty local option array public static final LocalOption[] NO_LOCAL_OPTIONS = new LocalOption[0]; // valid for: annotate checkout commit diff export log rdiff remove rtag status tag update - public static final LocalOption RECURSE = new LocalOption("-R"); //$NON-NLS-1$ + public static final LocalOption RECURSE = new LocalOption("-R"); //$NON-NLS-1$ public static final LocalOption DO_NOT_RECURSE = new LocalOption("-l"); //$NON-NLS-1$ // valid for: checkout export update public static final LocalOption PRUNE_EMPTY_DIRECTORIES = new LocalOption("-P"); //$NON-NLS-1$ @@ -324,7 +324,7 @@ public abstract class Command extends Request { // run the command try { - session.setCurrentCommand(Command.this); + session.setCurrentCommand(Command.this); status[0] = doExecute(session, gOptions, lOptions, arguments, listener, monitor); notifyConsoleOnCompletion(session, status[0], null); } catch (CVSException e1) { @@ -560,28 +560,28 @@ public abstract class Command extends Request { session.sendArgument(option); if (argument != null) session.sendArgument(argument); } - public LocalOption[] addTo(LocalOption[] options) { - if (this.isElementOf(options)) { - return options; - } - LocalOption[] newOptions = new LocalOption[options.length + 1]; - System.arraycopy(options, 0, newOptions, 0, options.length); - newOptions[options.length] = this; - return newOptions; - } - public LocalOption[] removeFrom(LocalOption[] options) { - if (!this.isElementOf(options)) { - return options; - } - List result = new ArrayList(); - for (int i = 0; i < options.length; i++) { - Command.LocalOption option = options[i]; - if (!option.equals(this)) { - result.add(option); - } - } - return (LocalOption[]) result.toArray(new LocalOption[result.size()]); - } + public LocalOption[] addTo(LocalOption[] options) { + if (this.isElementOf(options)) { + return options; + } + LocalOption[] newOptions = new LocalOption[options.length + 1]; + System.arraycopy(options, 0, newOptions, 0, options.length); + newOptions[options.length] = this; + return newOptions; + } + public LocalOption[] removeFrom(LocalOption[] options) { + if (!this.isElementOf(options)) { + return options; + } + List result = new ArrayList(); + for (int i = 0; i < options.length; i++) { + Command.LocalOption option = options[i]; + if (!option.equals(this)) { + result.add(option); + } + } + return (LocalOption[]) result.toArray(new LocalOption[result.size()]); + } } /** * Options subtype for keyword substitution options. @@ -654,40 +654,40 @@ public abstract class Command extends Request { */ public String getShortDisplayText() { if (isUnknownMode) - return NLS.bind(CVSMessages.KSubstOption_unknown_short, new String[] { option }); - if (option.equals("-kb")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kb_short; - if (option.equals("-kkv")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kkv_short; - if (option.equals("-ko")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__ko_short; - if (option.equals("-kk")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kk_short; - if (option.equals("-kv")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kv_short; - if (option.equals("-kkvl")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kkvl_short; - return NLS.bind(CVSMessages.KSubstOption_unknown_short, new String[] { option }); + return NLS.bind(CVSMessages.KSubstOption_unknown_short, new String[] { option }); + if (option.equals("-kb")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kb_short; + if (option.equals("-kkv")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kkv_short; + if (option.equals("-ko")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__ko_short; + if (option.equals("-kk")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kk_short; + if (option.equals("-kv")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kv_short; + if (option.equals("-kkvl")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kkvl_short; + return NLS.bind(CVSMessages.KSubstOption_unknown_short, new String[] { option }); } /** * Returns a long localized text string describing this mode. */ public String getLongDisplayText() { if (isUnknownMode) - return NLS.bind(CVSMessages.KSubstOption_unknown_long, new String[] { option }); - if (option.equals("-kb")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kb_long; - if (option.equals("-kkv")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kkv_long; - if (option.equals("-ko")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__ko_long; - if (option.equals("-kk")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kk_long; - if (option.equals("-kv")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kv_long; - if (option.equals("-kkvl")) //$NON-NLS-1$ - return CVSMessages.KSubstOption__kkvl_long; - return NLS.bind(CVSMessages.KSubstOption_unknown_long, new String[] { option }); + return NLS.bind(CVSMessages.KSubstOption_unknown_long, new String[] { option }); + if (option.equals("-kb")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kb_long; + if (option.equals("-kkv")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kkv_long; + if (option.equals("-ko")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__ko_long; + if (option.equals("-kk")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kk_long; + if (option.equals("-kv")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kv_long; + if (option.equals("-kkvl")) //$NON-NLS-1$ + return CVSMessages.KSubstOption__kkvl_long; + return NLS.bind(CVSMessages.KSubstOption_unknown_long, new String[] { option }); } /** * Return the text mode that will be used by default diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/CommandOutputListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/CommandOutputListener.java index 567c7c07f..9a4e30d83 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/CommandOutputListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/CommandOutputListener.java @@ -20,14 +20,14 @@ import org.eclipse.team.internal.ccvs.core.client.listeners.ICommandOutputListen import org.eclipse.team.internal.ccvs.core.connection.CVSRepositoryLocation; public class CommandOutputListener implements ICommandOutputListener { - - /* - * Failure string that is returned from the server when pserver is used and the root directory - * is not readable. The problem can be fixed by making the directory readable or by using -f in - * the pserver configuration file. We will ignore the error since it does not affect the command. - */ - public static final String ROOT_CVSIGNORE_READ_FAILURE = "cvs server: cannot open /root/.cvsignore: Permission denied"; //$NON-NLS-1$ - + + /* + * Failure string that is returned from the server when pserver is used and the root directory + * is not readable. The problem can be fixed by making the directory readable or by using -f in + * the pserver configuration file. We will ignore the error since it does not affect the command. + */ + public static final String ROOT_CVSIGNORE_READ_FAILURE = "cvs server: cannot open /root/.cvsignore: Permission denied"; //$NON-NLS-1$ + public IStatus messageLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { return OK; } @@ -37,8 +37,8 @@ public class CommandOutputListener implements ICommandOutputListener { return new CVSStatus(IStatus.ERROR, CVSStatus.PROTOCOL_ERROR, protocolError, commandRoot); } if (line.equals(ROOT_CVSIGNORE_READ_FAILURE) || getServerMessage(ROOT_CVSIGNORE_READ_FAILURE, location).equals(getServerMessage(line, location))) { - // Don't report this as an error since it does not affect the command - return new CVSStatus(IStatus.WARNING, CVSStatus.ERROR_LINE, line, commandRoot); + // Don't report this as an error since it does not affect the command + return new CVSStatus(IStatus.WARNING, CVSStatus.ERROR_LINE, line, commandRoot); } return new CVSStatus(IStatus.ERROR, CVSStatus.ERROR_LINE, line, commandRoot); } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Commit.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Commit.java index 90efdc551..2980cd5f9 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Commit.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Commit.java @@ -132,8 +132,8 @@ public class Commit extends Command { session.setTextTransferOverride(null); } } - - protected String getDisplayText() { - return "commit"; //$NON-NLS-1$ - } + + protected String getDisplayText() { + return "commit"; //$NON-NLS-1$ + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ConsoleListeners.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ConsoleListeners.java index 7f552dfe4..7ab88ad15 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ConsoleListeners.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ConsoleListeners.java @@ -27,100 +27,100 @@ import org.eclipse.team.internal.ccvs.core.client.listeners.IConsoleListener; */ public class ConsoleListeners implements IConsoleListener { - private static ConsoleListeners instance = new ConsoleListeners(); - private Set listeners = new HashSet(); - - /** - * Return the console listeners - * @return the console listeners - */ - public static ConsoleListeners getInstance() { - return instance; - } - - public void addListener(IConsoleListener listener) { - synchronized(listeners) { - listeners.add(listener); - } - } - - public void removeListener(IConsoleListener listener) { - synchronized(listeners) { - listeners.remove(listener); - } - } + private static ConsoleListeners instance = new ConsoleListeners(); + private Set listeners = new HashSet(); + + /** + * Return the console listeners + * @return the console listeners + */ + public static ConsoleListeners getInstance() { + return instance; + } + + public void addListener(IConsoleListener listener) { + synchronized(listeners) { + listeners.add(listener); + } + } + + public void removeListener(IConsoleListener listener) { + synchronized(listeners) { + listeners.remove(listener); + } + } - private IConsoleListener[] getListeners() { - synchronized(listeners) { - return (IConsoleListener[]) listeners.toArray(new IConsoleListener[listeners.size()]); - } - } - - @Override - public void commandInvoked(final Session session, final String line) { - if (listeners.isEmpty()) return; - IConsoleListener[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IConsoleListener listener = listeners[i]; - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - // Exception logged by Platform - } - public void run() throws Exception { - listener.commandInvoked(session, line); - } - }); - } - } + private IConsoleListener[] getListeners() { + synchronized(listeners) { + return (IConsoleListener[]) listeners.toArray(new IConsoleListener[listeners.size()]); + } + } + + @Override + public void commandInvoked(final Session session, final String line) { + if (listeners.isEmpty()) return; + IConsoleListener[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IConsoleListener listener = listeners[i]; + Platform.run(new ISafeRunnable() { + public void handleException(Throwable exception) { + // Exception logged by Platform + } + public void run() throws Exception { + listener.commandInvoked(session, line); + } + }); + } + } - @Override - public void messageLineReceived(final Session session, final String line, final IStatus status) { - if (listeners.isEmpty()) return; - IConsoleListener[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IConsoleListener listener = listeners[i]; - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - // Exception logged by Platform - } - public void run() throws Exception { - listener.messageLineReceived(session, line, status); - } - }); - } - } + @Override + public void messageLineReceived(final Session session, final String line, final IStatus status) { + if (listeners.isEmpty()) return; + IConsoleListener[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IConsoleListener listener = listeners[i]; + Platform.run(new ISafeRunnable() { + public void handleException(Throwable exception) { + // Exception logged by Platform + } + public void run() throws Exception { + listener.messageLineReceived(session, line, status); + } + }); + } + } - @Override - public void errorLineReceived(final Session session, final String line, final IStatus status) { - if (listeners.isEmpty()) return; - IConsoleListener[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IConsoleListener listener = listeners[i]; - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - // Exception logged by Platform - } - public void run() throws Exception { - listener.errorLineReceived(session, line, status); - } - }); - } - } + @Override + public void errorLineReceived(final Session session, final String line, final IStatus status) { + if (listeners.isEmpty()) return; + IConsoleListener[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IConsoleListener listener = listeners[i]; + Platform.run(new ISafeRunnable() { + public void handleException(Throwable exception) { + // Exception logged by Platform + } + public void run() throws Exception { + listener.errorLineReceived(session, line, status); + } + }); + } + } - @Override - public void commandCompleted(final Session session, final IStatus status, final Exception exception) { - if (listeners.isEmpty()) return; - IConsoleListener[] listeners = getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IConsoleListener listener = listeners[i]; - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - // Exception logged by Platform - } - public void run() throws Exception { - listener.commandCompleted(session, status, exception); - } - }); - } - } + @Override + public void commandCompleted(final Session session, final IStatus status, final Exception exception) { + if (listeners.isEmpty()) return; + IConsoleListener[] listeners = getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IConsoleListener listener = listeners[i]; + Platform.run(new ISafeRunnable() { + public void handleException(Throwable exception) { + // Exception logged by Platform + } + public void run() throws Exception { + listener.commandCompleted(session, status, exception); + } + }); + } + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Diff.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Diff.java index 9955fb0e6..33babbc23 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Diff.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Diff.java @@ -42,21 +42,21 @@ public class Diff extends Command { * so when there is a difference between the checked files. */ protected IStatus doExecute(Session session, GlobalOption[] globalOptions, LocalOption[] localOptions, - String[] arguments, ICommandOutputListener listener, IProgressMonitor monitor) throws CVSException { + String[] arguments, ICommandOutputListener listener, IProgressMonitor monitor) throws CVSException { try { IStatus status = super.doExecute(session, globalOptions, localOptions, arguments, listener, monitor); - if (status.getCode() == CVSStatus.SERVER_ERROR) { - if (status.isMultiStatus()) { - IStatus[] children = status.getChildren(); - for (int i = 0; i < children.length; i++) { - IStatus child = children[i]; - if (child.getMessage().indexOf("[diff aborted]") != -1) { //$NON-NLS-1$ - throw new CVSServerException(status); - } - } - } - } - return status; + if (status.getCode() == CVSStatus.SERVER_ERROR) { + if (status.isMultiStatus()) { + IStatus[] children = status.getChildren(); + for (int i = 0; i < children.length; i++) { + IStatus child = children[i]; + if (child.getMessage().indexOf("[diff aborted]") != -1) { //$NON-NLS-1$ + throw new CVSServerException(status); + } + } + } + } + return status; } catch (CVSServerException e) { if (e.containsErrors()) throw e; return e.getStatus(); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/FileStructureVisitor.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/FileStructureVisitor.java index 4091eed84..f4bf92070 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/FileStructureVisitor.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/FileStructureVisitor.java @@ -73,9 +73,9 @@ class FileStructureVisitor extends AbstractStructureVisitor { ICVSResource[] children = mFolder.members(ICVSFolder.ALL_UNIGNORED_MEMBERS); sendFiles(children); sendQuestionableFolders(children); - if (isRecurse()) { - sendManagedFolders(children); - } + if (isRecurse()) { + sendManagedFolders(children); + } } /** diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Import.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Import.java index 70f526ace..1310f7767 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Import.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Import.java @@ -39,13 +39,13 @@ public class Import extends Command { IProgressMonitor monitor) throws CVSException { // If the branch option is not provided, a default value of 1.1.1 is used. - // This is done to maintain reference client compatibility - if (findOption(localOptions, "-b") == null) { //$NON-NLS-1$ - LocalOption[] newLocalOptions = new LocalOption[localOptions.length + 1]; + // This is done to maintain reference client compatibility + if (findOption(localOptions, "-b") == null) { //$NON-NLS-1$ + LocalOption[] newLocalOptions = new LocalOption[localOptions.length + 1]; newLocalOptions[0] = new LocalOption("-b", "1.1.1"); //$NON-NLS-1$ //$NON-NLS-2$ System.arraycopy(localOptions, 0, newLocalOptions, 1, localOptions.length); localOptions = newLocalOptions; - } + } return super.doExecute(session, globalOptions, localOptions, arguments, listener, monitor); } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RLog.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RLog.java index 2338d2eb1..b0857c4a0 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RLog.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RLog.java @@ -34,7 +34,7 @@ public class RLog extends RemoteCommand { * ==== ==== ================================= * date date date<date (all revisions between date and later) * tag tag tag:tag (all revisions between tag and tag, must be on same branch) - * branch date >date (all revisions of date or later) + * branch date >date (all revisions of date or later) * branch tag tag: (all revisions from tag to the end of branchs tip) * * Valid for: rlog diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemoteCommand.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemoteCommand.java index eff261de8..58d8f5a46 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemoteCommand.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemoteCommand.java @@ -54,21 +54,21 @@ public abstract class RemoteCommand extends Command { // Convert arguments List stringArguments = new ArrayList(arguments.length); for (int i = 0; i < arguments.length; i++) { - ICVSResource resource = arguments[i]; - String remotePath; - if (isDefinedModule(resource)) { - remotePath = resource.getName(); - } else { - remotePath = resource.getRepositoryRelativePath(); - - } - stringArguments.add(remotePath); + ICVSResource resource = arguments[i]; + String remotePath; + if (isDefinedModule(resource)) { + remotePath = resource.getName(); + } else { + remotePath = resource.getRepositoryRelativePath(); + + } + stringArguments.add(remotePath); } return (String[]) stringArguments.toArray(new String[stringArguments.size()]); } - private boolean isDefinedModule(ICVSResource resource) { - return resource instanceof ICVSRemoteFolder && ((ICVSRemoteFolder)resource).isDefinedModule(); - } + private boolean isDefinedModule(ICVSResource resource) { + return resource instanceof ICVSRemoteFolder && ((ICVSRemoteFolder)resource).isDefinedModule(); + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemovedHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemovedHandler.java index d452bf304..f08075f7d 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemovedHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/RemovedHandler.java @@ -59,25 +59,25 @@ class RemovedHandler extends ResponseHandler { // delete then unmanage the file try { - if (mFile.isReadOnly()) mFile.setReadOnly(false); - mFile.delete(); - mFile.unmanage(null); - } catch (CVSException e) { - IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.RESPONSE_HANDLING_FAILURE, NLS.bind(CVSMessages.RemovedHandler_0, new String[] { getPath(mFile) }), e, session.getLocalRoot()); - session.handleResponseError(status); - } + if (mFile.isReadOnly()) mFile.setReadOnly(false); + mFile.delete(); + mFile.unmanage(null); + } catch (CVSException e) { + IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.RESPONSE_HANDLING_FAILURE, NLS.bind(CVSMessages.RemovedHandler_0, new String[] { getPath(mFile) }), e, session.getLocalRoot()); + session.handleResponseError(status); + } } - private String getPath(ICVSFile file) { - IResource resource = file.getIResource(); - if (resource != null) { - return resource.getFullPath().toString(); - } - try { - return file.getRepositoryRelativePath(); - } catch (CVSException e1) { - return file.getName(); - } - } + private String getPath(ICVSFile file) { + IResource resource = file.getIResource(); + if (resource != null) { + return resource.getFullPath().toString(); + } + try { + return file.getRepositoryRelativePath(); + } catch (CVSException e1) { + return file.getName(); + } + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java index fe1a6bec5..341ed488d 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Request.java @@ -114,7 +114,7 @@ public abstract class Request { // move some rather than remaining still and then jumping to 100). final int TOTAL_WORK = 300; monitor.beginTask(CVSMessages.Command_receivingResponses, TOTAL_WORK); - monitor.subTask(CVSMessages.Command_receivingResponses); + monitor.subTask(CVSMessages.Command_receivingResponses); int halfWay = TOTAL_WORK / 2; int currentIncrement = 4; int nextProgress = currentIncrement; @@ -168,18 +168,18 @@ public abstract class Request { } if (!session.hasErrors()) { - session.addError(new CVSStatus(IStatus.ERROR, CVSStatus.SERVER_ERROR, CVSMessages.Command_noMoreInfoAvailable,session.getLocalRoot())); + session.addError(new CVSStatus(IStatus.ERROR, CVSStatus.SERVER_ERROR, CVSMessages.Command_noMoreInfoAvailable,session.getLocalRoot())); } IStatus status = new MultiStatus(CVSProviderPlugin.ID, CVSStatus.SERVER_ERROR, - session.getErrors(), + session.getErrors(), argument, null); if (serious) { throw new CVSServerException(status); } else { // look for particularly bad errors in the accumulated statuses - IStatus[] errors = session.getErrors(); - for (int i = 0; i < errors.length; i++) { - IStatus s = errors[i]; + IStatus[] errors = session.getErrors(); + for (int i = 0; i < errors.length; i++) { + IStatus s = errors[i]; if (s.getCode() == CVSStatus.PROTOCOL_ERROR) { throw new CVSServerException(status); } @@ -242,7 +242,7 @@ public abstract class Request { protected String getServerErrorMessage() { return NLS.bind(CVSMessages.Command_serverError, new String[] { getDisplayText() }); } - protected String getDisplayText() { - return getRequestId(); - } + protected String getDisplayText() { + return getRequestId(); + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ResponseHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ResponseHandler.java index 5cdef4c50..6a1827aba 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ResponseHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/ResponseHandler.java @@ -83,39 +83,39 @@ public abstract class ResponseHandler { } if (! folder.isCVSFolder()) { String repositoryRoot = session.getRepositoryRoot(); - String relativePath; - if (repositoryDir.startsWith(repositoryRoot)) { - // The repositoryDir is an absolute path - relativePath = Util.getRelativePath(repositoryRoot, repositoryDir); - } else { - // The repositoryDir is already a relative path - relativePath = repositoryDir; - } - IResource resource = folder.getIResource(); - if (resource != null) { - IProject project = resource.getProject(); + String relativePath; + if (repositoryDir.startsWith(repositoryRoot)) { + // The repositoryDir is an absolute path + relativePath = Util.getRelativePath(repositoryRoot, repositoryDir); + } else { + // The repositoryDir is already a relative path + relativePath = repositoryDir; + } + IResource resource = folder.getIResource(); + if (resource != null) { + IProject project = resource.getProject(); if (project != null && project.isAccessible() && !CVSTeamProvider.isSharedWithCVS(project)) { - // The project isn't shared but we are about to perform an operation on it. - // we need to flag the project as shared so that the sync info management works - CVSTeamProvider.markAsTempShare(project); - } - } - try{ - folder.setFolderSyncInfo(new FolderSyncInfo( + // The project isn't shared but we are about to perform an operation on it. + // we need to flag the project as shared so that the sync info management works + CVSTeamProvider.markAsTempShare(project); + } + } + try{ + folder.setFolderSyncInfo(new FolderSyncInfo( relativePath, session.getCVSRepositoryLocation().getLocation(false), null, false)); - } catch (CVSException ex){ - IStatus status = ex.getStatus(); - if (status != null){ - if (status.getCode() == IResourceStatus.INVALID_VALUE){ - //if it's an invalid value, just ignore the exception (see Bug# 152053), - //else throw it again - } else { - throw ex; - } - } - } + } catch (CVSException ex){ + IStatus status = ex.getStatus(); + if (status != null){ + if (status.getCode() == IResourceStatus.INVALID_VALUE){ + //if it's an invalid value, just ignore the exception (see Bug# 152053), + //else throw it again + } else { + throw ex; + } + } + } } return folder; } @@ -127,13 +127,13 @@ public abstract class ResponseHandler { IContainer container = (IContainer)mParent.getIResource(); if (container != null) { try { - // Create all the parents as need - recreatePhantomFolders(mParent); - } catch (CVSException e) { - if (!handleInvalidResourceName(session, mParent, e)) { - throw e; - } - } + // Create all the parents as need + recreatePhantomFolders(mParent); + } catch (CVSException e) { + if (!handleInvalidResourceName(session, mParent, e)) { + throw e; + } + } } } return mParent; @@ -159,32 +159,32 @@ public abstract class ResponseHandler { return this; } - protected boolean handleInvalidResourceName(Session session, ICVSResource resource, CVSException e) { - int code = e.getStatus().getCode(); - if (code == IResourceStatus.INVALID_VALUE - || code == IResourceStatus.INVALID_RESOURCE_NAME - || code == IResourceStatus.RESOURCE_NOT_FOUND - || code == IResourceStatus.RESOURCE_EXISTS - || code == IResourceStatus.RESOURCE_WRONG_TYPE - || code == IResourceStatus.CASE_VARIANT_EXISTS - || code == IResourceStatus.PATH_OCCUPIED) { - - try { - IResource local = resource.getIResource(); - String path; - if (local == null) { - path = resource.getRepositoryRelativePath(); - } else { - path = local.getFullPath().toString(); - } - IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.INVALID_LOCAL_RESOURCE_PATH, NLS.bind(CVSMessages.ResponseHandler_0, new String[] { path, e.getMessage() }), e, session.getLocalRoot()); - session.handleResponseError(status); - } catch (CVSException e1) { - CVSProviderPlugin.log(e1); - } - return true; - } - return false; - } + protected boolean handleInvalidResourceName(Session session, ICVSResource resource, CVSException e) { + int code = e.getStatus().getCode(); + if (code == IResourceStatus.INVALID_VALUE + || code == IResourceStatus.INVALID_RESOURCE_NAME + || code == IResourceStatus.RESOURCE_NOT_FOUND + || code == IResourceStatus.RESOURCE_EXISTS + || code == IResourceStatus.RESOURCE_WRONG_TYPE + || code == IResourceStatus.CASE_VARIANT_EXISTS + || code == IResourceStatus.PATH_OCCUPIED) { + + try { + IResource local = resource.getIResource(); + String path; + if (local == null) { + path = resource.getRepositoryRelativePath(); + } else { + path = local.getFullPath().toString(); + } + IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.INVALID_LOCAL_RESOURCE_PATH, NLS.bind(CVSMessages.ResponseHandler_0, new String[] { path, e.getMessage() }), e, session.getLocalRoot()); + session.handleResponseError(status); + } catch (CVSException e1) { + CVSProviderPlugin.log(e1); + } + return true; + } + return false; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Session.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Session.java index 4775d2979..f63b5fbe3 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Session.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Session.java @@ -94,9 +94,9 @@ public class Session { private Map responseHandlers; // List of errors accumulated while the command is executing - private List errors = new ArrayList(); - - private Command currentCommand; + private List errors = new ArrayList(); + + private Command currentCommand; /** * Creates a new CVS session, initially in the CLOSED state. @@ -760,14 +760,14 @@ public class Session { } size = Long.parseLong(sizeLine, 10); } catch (NumberFormatException e) { - // In some cases, the server will give us an error line here - if (sizeLine != null && sizeLine.startsWith("E")) { //$NON-NLS-1$ - handleErrorLine(sizeLine.substring(1).trim(), org.eclipse.core.runtime.Status.OK_STATUS); - return; - } else { - IStatus status = new CVSStatus(IStatus.ERROR,CVSStatus.ERROR,CVSMessages.Session_badInt, e, localRoot); - throw new CVSException(status); - } + // In some cases, the server will give us an error line here + if (sizeLine != null && sizeLine.startsWith("E")) { //$NON-NLS-1$ + handleErrorLine(sizeLine.substring(1).trim(), org.eclipse.core.runtime.Status.OK_STATUS); + return; + } else { + IStatus status = new CVSStatus(IStatus.ERROR,CVSStatus.ERROR,CVSMessages.Session_badInt, e, localRoot); + throw new CVSException(status); + } } // create an input stream that spans the next 'size' bytes from the connection InputStream in = new SizeConstrainedInputStream(connection.getInputStream(), size, true /*discardOnClose*/); @@ -808,7 +808,7 @@ public class Session { file.setContents(in, responseType, true, new NullProgressMonitor()); } - /** + /** * Stores the value of the last Mod-time response encountered. * Valid only for the duration of a single CVS command. */ @@ -993,53 +993,53 @@ public class Session { return (ResponseHandler)getReponseHandlers().get(responseID); } - /** - * Accumulate the added errors so they can be included in the status returned - * when the command execution is finished. OK status are ignored. - * @param status the status to be accumulated - */ - public void addError(IStatus status) { - if (!status.isOK()) - errors.add(status); - } - - public boolean hasErrors() { - return !errors.isEmpty(); - } - - public IStatus[] getErrors() { - return (IStatus[]) errors.toArray(new IStatus[errors.size()]); - } + /** + * Accumulate the added errors so they can be included in the status returned + * when the command execution is finished. OK status are ignored. + * @param status the status to be accumulated + */ + public void addError(IStatus status) { + if (!status.isOK()) + errors.add(status); + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } + + public IStatus[] getErrors() { + return (IStatus[]) errors.toArray(new IStatus[errors.size()]); + } - public void clearErrors() { - errors.clear(); - } + public void clearErrors() { + errors.clear(); + } - public void setCurrentCommand(Command c) { - currentCommand = c; - } - - public Command getCurrentCommand() { - return currentCommand; - } + public void setCurrentCommand(Command c) { + currentCommand = c; + } + + public Command getCurrentCommand() { + return currentCommand; + } /** * Report the given error line to any listeners - * @param line the error line - * @param status the status that indicates any problems encountered parsing the line - */ - public void handleErrorLine(String line, IStatus status) { - ConsoleListeners.getInstance().errorLineReceived(this, line, status); - } - - /** - * An error has occurred while processing responses from the - * server. Place this error is the status that will be returned - * from the command and show the error in the console - * @param status the status that descibes the error - */ - public void handleResponseError(IStatus status) { - addError(status); - handleErrorLine(NLS.bind(CVSMessages.Session_0, new String[] { status.getMessage() }), status); - } + * @param line the error line + * @param status the status that indicates any problems encountered parsing the line + */ + public void handleErrorLine(String line, IStatus status) { + ConsoleListeners.getInstance().errorLineReceived(this, line, status); + } + + /** + * An error has occurred while processing responses from the + * server. Place this error is the status that will be returned + * from the command and show the error in the console + * @param status the status that descibes the error + */ + public void handleResponseError(IStatus status) { + addError(status); + handleErrorLine(NLS.bind(CVSMessages.Session_0, new String[] { status.getMessage() }), status); + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StaticHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StaticHandler.java index c8335c6b0..59c21d149 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StaticHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StaticHandler.java @@ -61,20 +61,20 @@ class StaticHandler extends ResponseHandler { Assert.isTrue(repositoryDir.endsWith("/")); //$NON-NLS-1$ repositoryDir = repositoryDir.substring(0, repositoryDir.length() - 1); try { - ICVSFolder folder = createFolder(session, localDir, repositoryDir); - FolderSyncInfo syncInfo = folder.getFolderSyncInfo(); - // Added to ignore sync info for workspace root - if (syncInfo == null) return; - MutableFolderSyncInfo newInfo = syncInfo.cloneMutable(); - newInfo.setStatic(setStaticDirectory); - // only set the sync info if it has changed - if (!syncInfo.equals(newInfo)) - folder.setFolderSyncInfo(newInfo); - } catch (CVSException e) { - if (!handleInvalidResourceName(session, session.getLocalRoot().getFolder(localDir), e)) { - throw e; - } - } + ICVSFolder folder = createFolder(session, localDir, repositoryDir); + FolderSyncInfo syncInfo = folder.getFolderSyncInfo(); + // Added to ignore sync info for workspace root + if (syncInfo == null) return; + MutableFolderSyncInfo newInfo = syncInfo.cloneMutable(); + newInfo.setStatic(setStaticDirectory); + // only set the sync info if it has changed + if (!syncInfo.equals(newInfo)) + folder.setFolderSyncInfo(newInfo); + } catch (CVSException e) { + if (!handleInvalidResourceName(session, session.getLocalRoot().getFolder(localDir), e)) { + throw e; + } + } } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StickyHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StickyHandler.java index b94325e76..48fe582ff 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StickyHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/StickyHandler.java @@ -66,24 +66,24 @@ class StickyHandler extends ResponseHandler { Assert.isTrue(repositoryDir.endsWith("/")); //$NON-NLS-1$ repositoryDir = repositoryDir.substring(0, repositoryDir.length() - 1); try { - ICVSFolder folder = createFolder(session, localDir, repositoryDir); - FolderSyncInfo syncInfo = folder.getFolderSyncInfo(); - // Added to ignore sync info for workspace root - if (syncInfo == null) return; - MutableFolderSyncInfo newInfo = syncInfo.cloneMutable(); - newInfo.setTag(tag != null ? new CVSEntryLineTag(tag) : null); - /* if we are reverting to BASE we do not change anything here - * see bug 106876 */ - if(tag != null && tag.equals("TBASE")) //$NON-NLS-1$ - newInfo.setTag(syncInfo.getTag()); - // only set the sync info if it has changed - if (!syncInfo.equals(newInfo)) - folder.setFolderSyncInfo(newInfo); - } catch (CVSException e) { - if (!handleInvalidResourceName(session, session.getLocalRoot().getFolder(localDir), e)) { - throw e; - } - } + ICVSFolder folder = createFolder(session, localDir, repositoryDir); + FolderSyncInfo syncInfo = folder.getFolderSyncInfo(); + // Added to ignore sync info for workspace root + if (syncInfo == null) return; + MutableFolderSyncInfo newInfo = syncInfo.cloneMutable(); + newInfo.setTag(tag != null ? new CVSEntryLineTag(tag) : null); + /* if we are reverting to BASE we do not change anything here + * see bug 106876 */ + if(tag != null && tag.equals("TBASE")) //$NON-NLS-1$ + newInfo.setTag(syncInfo.getTag()); + // only set the sync info if it has changed + if (!syncInfo.equals(newInfo)) + folder.setFolderSyncInfo(newInfo); + } catch (CVSException e) { + if (!handleInvalidResourceName(session, session.getLocalRoot().getFolder(localDir), e)) { + throw e; + } + } } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/SyncUpdate.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/SyncUpdate.java index 7bc529dc1..385559125 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/SyncUpdate.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/SyncUpdate.java @@ -22,26 +22,26 @@ public class SyncUpdate extends Update { public SyncUpdate() { }; @Override - protected void sendFileStructure(Session session, ICVSResource[] resources, - LocalOption[] localOptions, boolean emptyFolders, IProgressMonitor monitor) throws CVSException { + protected void sendFileStructure(Session session, ICVSResource[] resources, + LocalOption[] localOptions, boolean emptyFolders, IProgressMonitor monitor) throws CVSException { checkResourcesManaged(session, resources); new FileStructureVisitor(session, localOptions, emptyFolders, true, false).visit(session, resources, monitor); } - @Override - protected boolean isWorkspaceModification() { - // The sync-update will not modify the workspace - return false; - } - - @Override - protected GlobalOption[] filterGlobalOptions(Session session, GlobalOption[] globalOptions) { - // Ensure that the DO_NOT_CHANGE (-n) global option is present + @Override + protected boolean isWorkspaceModification() { + // The sync-update will not modify the workspace + return false; + } + + @Override + protected GlobalOption[] filterGlobalOptions(Session session, GlobalOption[] globalOptions) { + // Ensure that the DO_NOT_CHANGE (-n) global option is present if (! Command.DO_NOT_CHANGE.isElementOf(globalOptions)) { globalOptions = Command.DO_NOT_CHANGE.addToEnd(globalOptions); } - return super.filterGlobalOptions(session, globalOptions); - } + return super.filterGlobalOptions(session, globalOptions); + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java index 9c99a9a0f..dd7783fac 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java @@ -40,18 +40,18 @@ public class TemplateHandler extends ResponseHandler { @Override public void handle(Session session, String localDir, IProgressMonitor monitor) throws CVSException { session.readLine(); /* read the remote dir which is not needed */ - // Only read the template file if the container exists. - // This is OK as we only use the template from the project folder which must exist - ICVSFolder localFolder = session.getLocalRoot().getFolder(localDir); + // Only read the template file if the container exists. + // This is OK as we only use the template from the project folder which must exist + ICVSFolder localFolder = session.getLocalRoot().getFolder(localDir); IContainer container = (IContainer)localFolder.getIResource(); ICVSStorage templateFile = null; if (container != null && container.exists()) { - try { - templateFile = CVSWorkspaceRoot.getCVSFileFor(SyncFileWriter.getTemplateFile(container)); - } catch (CVSException e) { - // Log the inability to create the template file - CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, CVSStatus.ERROR, "Could not write template file in " + container.getFullPath() + ": " + e.getMessage(), e, session.getLocalRoot())); //$NON-NLS-1$ //$NON-NLS-2$ - } + try { + templateFile = CVSWorkspaceRoot.getCVSFileFor(SyncFileWriter.getTemplateFile(container)); + } catch (CVSException e) { + // Log the inability to create the template file + CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, CVSStatus.ERROR, "Could not write template file in " + container.getFullPath() + ": " + e.getMessage(), e, session.getLocalRoot())); //$NON-NLS-1$ //$NON-NLS-2$ + } } if (container == null || templateFile == null) { // Create a dummy storage handle to recieve the contents from the server @@ -98,12 +98,12 @@ public class TemplateHandler extends ResponseHandler { }; } try { - session.receiveFile(templateFile, false, UpdatedHandler.HANDLE_UPDATED, monitor); - } catch (CVSException e) { - if (!(templateFile instanceof ICVSFile && handleInvalidResourceName(session, (ICVSFile)templateFile, e))) { - throw e; - } - } + session.receiveFile(templateFile, false, UpdatedHandler.HANDLE_UPDATED, monitor); + } catch (CVSException e) { + if (!(templateFile instanceof ICVSFile && handleInvalidResourceName(session, (ICVSFile)templateFile, e))) { + throw e; + } + } } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Update.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Update.java index a03b0604e..cb0e5daa5 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Update.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Update.java @@ -171,9 +171,9 @@ public class Update extends Command { folder = resources[i].getParent(); } if (folder==null || (!folder.isCVSFolder() && folder.exists())) { - if (folder == null) - folder = (ICVSFolder)resources[i]; - IStatus status = new CVSStatus(IStatus.ERROR,CVSStatus.ERROR,NLS.bind(CVSMessages.Command_argumentNotManaged, new String[] { folder.getName() }),session.getLocalRoot()); + if (folder == null) + folder = (ICVSFolder)resources[i]; + IStatus status = new CVSStatus(IStatus.ERROR,CVSStatus.ERROR,NLS.bind(CVSMessages.Command_argumentNotManaged, new String[] { folder.getName() }),session.getLocalRoot()); throw new CVSException(status); } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/UpdatedHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/UpdatedHandler.java index efd121cbf..0b96cd76e 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/UpdatedHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/UpdatedHandler.java @@ -92,27 +92,27 @@ public class UpdatedHandler extends ResponseHandler { boolean executable = permissionsLine.indexOf(EXECUTE_FLAG) != -1; try { - // The file may have been set as read-only by a previous checkout/update - if (mFile.isReadOnly()) mFile.setReadOnly(false); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + // The file may have been set as read-only by a previous checkout/update + if (mFile.isReadOnly()) mFile.setReadOnly(false); + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } try { - receiveTargetFile(session, mFile, entryLine, modTime, binary, readOnly, executable, monitor); - } catch (CVSException e) { - // An error occurred while recieving the file. - // If it is due to an invalid file name, - // accumulate the error and continue. - // Otherwise, exit - if (!handleInvalidResourceName(session, mFile, e)) { - throw e; - } - } + receiveTargetFile(session, mFile, entryLine, modTime, binary, readOnly, executable, monitor); + } catch (CVSException e) { + // An error occurred while recieving the file. + // If it is due to an invalid file name, + // accumulate the error and continue. + // Otherwise, exit + if (!handleInvalidResourceName(session, mFile, e)) { + throw e; + } + } } - protected ICVSFile getTargetFile(ICVSFolder mParent, String fileName, byte[] entryBytes) throws CVSException { + protected ICVSFile getTargetFile(ICVSFolder mParent, String fileName, byte[] entryBytes) throws CVSException { return mParent.getFile(fileName); } @@ -148,12 +148,12 @@ public class UpdatedHandler extends ResponseHandler { } mFile.setSyncInfo(newInfoWithTimestamp, modificationState); try { - if (readOnly) mFile.setReadOnly(true); + if (readOnly) mFile.setReadOnly(true); if (executable) mFile.setExecutable(true); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } } public int getHandlerType() { diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Version.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Version.java index 388182224..282c736ad 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Version.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/Version.java @@ -70,13 +70,13 @@ public class Version extends RemoteCommand { if (knownPrefix != null) { String versionNumber = line.substring(knownPrefix.length(), line.indexOf(' ', knownPrefix.length() + 1)); if (versionNumber.startsWith("1.10") || versionNumber.equals("1.11") || versionNumber.equals("1.11.1")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - serverType = CVSRepositoryLocation.UNSUPPORTED_SERVER; + serverType = CVSRepositoryLocation.UNSUPPORTED_SERVER; status = new CVSStatus(IStatus.WARNING, CVSStatus.UNSUPPORTED_SERVER_VERSION, NLS.bind(CVSMessages.Version_unsupportedVersion, new String[] { location.getHost(), versionNumber }),location); } else if (isCVSNT) { - serverType = CVSRepositoryLocation.CVSNT_SERVER; + serverType = CVSRepositoryLocation.CVSNT_SERVER; } } else { - serverType = CVSRepositoryLocation.UNKNOWN_SERVER; + serverType = CVSRepositoryLocation.UNKNOWN_SERVER; status = new CVSStatus(IStatus.INFO, CVSStatus.SERVER_IS_UNKNOWN, NLS.bind(CVSMessages.Version_unknownVersionFormat, new String[] { location.getHost(), line }), location); } ((CVSRepositoryLocation)location).setServerPlaform(serverType); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AdminKSubstListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AdminKSubstListener.java index 286d30487..b7d70eff6 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AdminKSubstListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AdminKSubstListener.java @@ -80,7 +80,7 @@ public class AdminKSubstListener extends CommandOutputListener { IPath relativeFilePath = rcsFilePath.removeFirstSegments(remoteRootPath.segmentCount()); ICVSFile file = commandRoot.getFile(relativeFilePath.toString()); if (file.isManaged() && isMatchingPath(file, rcsFilePath)) { - return file; + return file; } } @@ -90,7 +90,7 @@ public class AdminKSubstListener extends CommandOutputListener { if (parent != null) { ICVSFile file = parent.getFile(rcsFilePath.lastSegment()); if (file.isManaged()) { - return file; + return file; } } @@ -99,30 +99,30 @@ public class AdminKSubstListener extends CommandOutputListener { NLS.bind(CVSMessages.AdminKSubstListener_expectedChildOfCommandRoot, new String[] { rcsFilePath.toString(), remoteRootPath.toString() }))); } - private ICVSFolder findFolder(ICVSFolder commandRoot, IPath path) throws CVSException { - final String remotePath = path.toString(); - final ICVSFolder[] result = new ICVSFolder[] { null }; - commandRoot.accept(new ICVSResourceVisitor() { - public void visitFile(ICVSFile file) throws CVSException { - // Nothing to do for files - } - public void visitFolder(ICVSFolder folder) throws CVSException { - FolderSyncInfo info = folder.getFolderSyncInfo(); - if (info != null && info.getRemoteLocation().equals(remotePath)) { - // We found the folder we're looking for - result[0] = folder; - } - if (result[0] == null) { - folder.acceptChildren(this); - } - } - }); - return result[0]; - } + private ICVSFolder findFolder(ICVSFolder commandRoot, IPath path) throws CVSException { + final String remotePath = path.toString(); + final ICVSFolder[] result = new ICVSFolder[] { null }; + commandRoot.accept(new ICVSResourceVisitor() { + public void visitFile(ICVSFile file) throws CVSException { + // Nothing to do for files + } + public void visitFolder(ICVSFolder folder) throws CVSException { + FolderSyncInfo info = folder.getFolderSyncInfo(); + if (info != null && info.getRemoteLocation().equals(remotePath)) { + // We found the folder we're looking for + result[0] = folder; + } + if (result[0] == null) { + folder.acceptChildren(this); + } + } + }); + return result[0]; + } - private boolean isMatchingPath(ICVSFile file, IPath rcsFilePath) throws CVSException { - FolderSyncInfo info = file.getParent().getFolderSyncInfo(); - return info != null - && info.getRemoteLocation().equals(rcsFilePath.removeLastSegments(1).toString()); - } + private boolean isMatchingPath(ICVSFile file, IPath rcsFilePath) throws CVSException { + FolderSyncInfo info = file.getParent().getFolderSyncInfo(); + return info != null + && info.getRemoteLocation().equals(rcsFilePath.removeLastSegments(1).toString()); + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AnnotateListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AnnotateListener.java index dc277e4e7..b9408f4b7 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AnnotateListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/AnnotateListener.java @@ -32,7 +32,7 @@ public class AnnotateListener extends CommandOutputListener { int lineNumber; public IStatus messageLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { - String error = null; + String error = null; CVSAnnotateBlock aBlock = new CVSAnnotateBlock(line, lineNumber++); if (!aBlock.isValid()) { error = line; @@ -49,8 +49,8 @@ public class AnnotateListener extends CommandOutputListener { } catch (IOException e) { } add(aBlock); - if (error != null) - return new CVSStatus(IStatus.ERROR, CVSStatus.ERROR_LINE_PARSE_FAILURE, error, commandRoot); + if (error != null) + return new CVSStatus(IStatus.ERROR, CVSStatus.ERROR_LINE_PARSE_FAILURE, error, commandRoot); return OK; } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/DiffListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/DiffListener.java index 55e09f61c..0660b6dc2 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/DiffListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/DiffListener.java @@ -51,8 +51,8 @@ public class DiffListener extends CommandOutputListener { // Special handling to avoid getting duplicate CRs when generating a patch on windows. // If the remote file has CR/LF in it, then the line will have a CR at the end. - // We need to remove it so we don't end up with two CRs (since the printStream will also add one). - // On *nix, we want to include the CR since it will not be added by the printStream (see bug 92162). + // We need to remove it so we don't end up with two CRs (since the printStream will also add one). + // On *nix, we want to include the CR since it will not be added by the printStream (see bug 92162). if (Session.IS_CRLF_PLATFORM && line.length() > 0 && line.charAt(line.length() - 1) == '\r') { line = line.substring(0, line.length() - 1); } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/ILogEntryListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/ILogEntryListener.java index b0ccb4b18..577709c47 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/ILogEntryListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/ILogEntryListener.java @@ -20,10 +20,10 @@ import org.eclipse.team.internal.ccvs.core.ILogEntry; */ public interface ILogEntryListener { - /** - * A log entry was received for the current file - * @param entry the received log entry. - */ - void handleLogEntryReceived(ILogEntry entry); - + /** + * A log entry was received for the current file + * @param entry the received log entry. + */ + void handleLogEntryReceived(ILogEntry entry); + } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogEntry.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogEntry.java index 6c88f1fcf..09f28da16 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogEntry.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogEntry.java @@ -30,8 +30,8 @@ public class LogEntry extends PlatformObject implements ILogEntry { private String state; private CVSTag[] tags; private CVSTag[] branches; - private String[] revisions; - + private String[] revisions; + /* * Flatten the text in the multi-line comment */ diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogListener.java index 6c3d2806b..6d199da8c 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/LogListener.java @@ -33,233 +33,233 @@ import org.eclipse.team.internal.ccvs.core.util.Util; * server but delegates the handling of the entries to a subclass. */ public class LogListener extends CommandOutputListener { - - /* - * A new format for log dates was introduced in 1.12.9 - */ - private static final String LOG_TIMESTAMP_FORMAT_OLD= "yyyy/MM/dd HH:mm:ss zzz";//$NON-NLS-1$ - private static final String LOG_TIMESTAMP_FORMAT= "yyyy-MM-dd HH:mm:ss zzz";//$NON-NLS-1$ - private static final Locale LOG_TIMESTAMP_LOCALE= Locale.US; - private final DateFormat LOG_DATE_FORMATTER_OLD = new SimpleDateFormat(LOG_TIMESTAMP_FORMAT_OLD, LOG_TIMESTAMP_LOCALE); - private final DateFormat LOG_DATE_FORMATTER = new SimpleDateFormat(LOG_TIMESTAMP_FORMAT, LOG_TIMESTAMP_LOCALE); - - // Server message prefix used for error detection - private static final String NOTHING_KNOWN_ABOUT = "nothing known about "; //$NON-NLS-1$ + + /* + * A new format for log dates was introduced in 1.12.9 + */ + private static final String LOG_TIMESTAMP_FORMAT_OLD= "yyyy/MM/dd HH:mm:ss zzz";//$NON-NLS-1$ + private static final String LOG_TIMESTAMP_FORMAT= "yyyy-MM-dd HH:mm:ss zzz";//$NON-NLS-1$ + private static final Locale LOG_TIMESTAMP_LOCALE= Locale.US; + private final DateFormat LOG_DATE_FORMATTER_OLD = new SimpleDateFormat(LOG_TIMESTAMP_FORMAT_OLD, LOG_TIMESTAMP_LOCALE); + private final DateFormat LOG_DATE_FORMATTER = new SimpleDateFormat(LOG_TIMESTAMP_FORMAT, LOG_TIMESTAMP_LOCALE); + + // Server message prefix used for error detection + private static final String NOTHING_KNOWN_ABOUT = "nothing known about "; //$NON-NLS-1$ - // States of log accumulation. - private final int DONE = 4; - private final int COMMENT = 3; - private final int REVISION = 2; - private final int SYMBOLIC_NAMES = 1; - private final int BEGIN = 0; - - //Tag used for accumulating all of a branch's revision info - public final static String BRANCH_REVISION = "branchRevision"; //$NON-NLS-1$ - - private static final CVSTag[] NO_TAGS = new CVSTag[0]; - private static final String[] NO_VERSIONS = new String[0]; - - // Instance variables for accumulating Log information - private RemoteFile currentFile; - private int state = BEGIN; - private StringBuffer comment; - private String fileState; - private String revision; - private String author; - private Date creationDate; - private List versions = new ArrayList(); - private Map internedStrings = new HashMap(); - private final ILogEntryListener listener; - - /** - * Create a log listener for receiving entries for one or more files. - */ - public LogListener(ILogEntryListener listener) { - this.listener = listener; - } + // States of log accumulation. + private final int DONE = 4; + private final int COMMENT = 3; + private final int REVISION = 2; + private final int SYMBOLIC_NAMES = 1; + private final int BEGIN = 0; + + //Tag used for accumulating all of a branch's revision info + public final static String BRANCH_REVISION = "branchRevision"; //$NON-NLS-1$ + + private static final CVSTag[] NO_TAGS = new CVSTag[0]; + private static final String[] NO_VERSIONS = new String[0]; + + // Instance variables for accumulating Log information + private RemoteFile currentFile; + private int state = BEGIN; + private StringBuffer comment; + private String fileState; + private String revision; + private String author; + private Date creationDate; + private List versions = new ArrayList(); + private Map internedStrings = new HashMap(); + private final ILogEntryListener listener; + + /** + * Create a log listener for receiving entries for one or more files. + */ + public LogListener(ILogEntryListener listener) { + this.listener = listener; + } - public LogListener(RemoteFile file, ILogEntryListener listener) { - this(listener); - this.currentFile = file; - } + public LogListener(RemoteFile file, ILogEntryListener listener) { + this(listener); + this.currentFile = file; + } - private String getRelativeFilePath(ICVSRepositoryLocation location, String fileName) { - if (fileName.endsWith(",v")) { //$NON-NLS-1$ - fileName = fileName.substring(0, fileName.length() - 2); - } - fileName = Util.removeAtticSegment(fileName); - String rootDirectory = location.getRootDirectory(); - if (fileName.startsWith(rootDirectory)) { - try { - fileName = Util.getRelativePath(rootDirectory, fileName); - } catch (CVSException e) { - CVSProviderPlugin.log(e); - return null; - } - } - return fileName; - } + private String getRelativeFilePath(ICVSRepositoryLocation location, String fileName) { + if (fileName.endsWith(",v")) { //$NON-NLS-1$ + fileName = fileName.substring(0, fileName.length() - 2); + } + fileName = Util.removeAtticSegment(fileName); + String rootDirectory = location.getRootDirectory(); + if (fileName.startsWith(rootDirectory)) { + try { + fileName = Util.getRelativePath(rootDirectory, fileName); + } catch (CVSException e) { + CVSProviderPlugin.log(e); + return null; + } + } + return fileName; + } - public IStatus errorLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { - String serverMessage = getServerMessage(line, location); - if (serverMessage != null) { - // look for the following condition - // E cvs server: nothing known about fileName - if (serverMessage.startsWith(NOTHING_KNOWN_ABOUT)) { - return new CVSStatus(IStatus.ERROR, CVSStatus.DOES_NOT_EXIST, line, commandRoot); - } - } - return OK; - } + public IStatus errorLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { + String serverMessage = getServerMessage(line, location); + if (serverMessage != null) { + // look for the following condition + // E cvs server: nothing known about fileName + if (serverMessage.startsWith(NOTHING_KNOWN_ABOUT)) { + return new CVSStatus(IStatus.ERROR, CVSStatus.DOES_NOT_EXIST, line, commandRoot); + } + } + return OK; + } - public IStatus messageLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { - // Fields we will find in the log for a file - // keys = String (tag name), values = String (tag revision number) */ - switch (state) { - case BEGIN: - if (line.startsWith("RCS file: ")) { //$NON-NLS-1$ - // We are starting to recieve the log for a file - String fileName = getRelativeFilePath(location, line.substring(10).trim()); - if (fileName == null) { - currentFile = null; - handleInvalidFileName(location, fileName); - } else { - if (currentFile == null || !currentFile.getRepositoryRelativePath().equals(fileName)) { - // We are starting another file - beginFile(location, fileName); - } - } - } else if (line.startsWith("symbolic names:")) { //$NON-NLS-1$ - state = SYMBOLIC_NAMES; - } else if (line.startsWith("revision ")) { //$NON-NLS-1$ - // if the revision has been locked, remove the "locked by" suffix - revision = line.substring(9).replaceFirst(ResourceSyncInfo.LOCKEDBY_REGEX, ""); //$NON-NLS-1$ - revision = internAndCopyString(revision); - state = REVISION; - } else if (line.startsWith("total revisions:")){ //$NON-NLS-1$ - //if there are no current revision selected and this is a branch then we are in the - //case where there have been no changes made on the branch since the initial branching - //and we need to get the revision that the branch was made from - int indexOfSelectedRevisions = line.lastIndexOf("selected revisions: "); //$NON-NLS-1$ - //20 for length of "selected revisions: " - String selectedRevisions = line.substring(indexOfSelectedRevisions + 20).trim(); - if (selectedRevisions.equals("0")){ //$NON-NLS-1$ - //ok put into comment state to await ======= and add info to log - state = COMMENT; - revision = BRANCH_REVISION; - comment = new StringBuffer(); - } - } - break; - case SYMBOLIC_NAMES: - if (line.startsWith("keyword substitution:")) { //$NON-NLS-1$ - state = BEGIN; - } else { - int firstColon = line.indexOf(':'); - String tagName = internAndCopyString(line.substring(1, firstColon)); - String tagRevision = internAndCopyString(line.substring(firstColon + 2)); - versions.add(new VersionInfo(tagRevision, tagName)); - } - break; - case REVISION: - // date: 2000/06/19 04:56:21; author: somebody; state: Exp; lines: +114 -45 - // get the creation date - int endOfDateIndex = line.indexOf(';', 6); - creationDate = convertFromLogTime(line.substring(6, endOfDateIndex) + " GMT"); //$NON-NLS-1$ - - // get the author name - int endOfAuthorIndex = line.indexOf(';', endOfDateIndex + 1); - author = internAndCopyString(line.substring(endOfDateIndex + 11, endOfAuthorIndex)); + public IStatus messageLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { + // Fields we will find in the log for a file + // keys = String (tag name), values = String (tag revision number) */ + switch (state) { + case BEGIN: + if (line.startsWith("RCS file: ")) { //$NON-NLS-1$ + // We are starting to recieve the log for a file + String fileName = getRelativeFilePath(location, line.substring(10).trim()); + if (fileName == null) { + currentFile = null; + handleInvalidFileName(location, fileName); + } else { + if (currentFile == null || !currentFile.getRepositoryRelativePath().equals(fileName)) { + // We are starting another file + beginFile(location, fileName); + } + } + } else if (line.startsWith("symbolic names:")) { //$NON-NLS-1$ + state = SYMBOLIC_NAMES; + } else if (line.startsWith("revision ")) { //$NON-NLS-1$ + // if the revision has been locked, remove the "locked by" suffix + revision = line.substring(9).replaceFirst(ResourceSyncInfo.LOCKEDBY_REGEX, ""); //$NON-NLS-1$ + revision = internAndCopyString(revision); + state = REVISION; + } else if (line.startsWith("total revisions:")){ //$NON-NLS-1$ + //if there are no current revision selected and this is a branch then we are in the + //case where there have been no changes made on the branch since the initial branching + //and we need to get the revision that the branch was made from + int indexOfSelectedRevisions = line.lastIndexOf("selected revisions: "); //$NON-NLS-1$ + //20 for length of "selected revisions: " + String selectedRevisions = line.substring(indexOfSelectedRevisions + 20).trim(); + if (selectedRevisions.equals("0")){ //$NON-NLS-1$ + //ok put into comment state to await ======= and add info to log + state = COMMENT; + revision = BRANCH_REVISION; + comment = new StringBuffer(); + } + } + break; + case SYMBOLIC_NAMES: + if (line.startsWith("keyword substitution:")) { //$NON-NLS-1$ + state = BEGIN; + } else { + int firstColon = line.indexOf(':'); + String tagName = internAndCopyString(line.substring(1, firstColon)); + String tagRevision = internAndCopyString(line.substring(firstColon + 2)); + versions.add(new VersionInfo(tagRevision, tagName)); + } + break; + case REVISION: + // date: 2000/06/19 04:56:21; author: somebody; state: Exp; lines: +114 -45 + // get the creation date + int endOfDateIndex = line.indexOf(';', 6); + creationDate = convertFromLogTime(line.substring(6, endOfDateIndex) + " GMT"); //$NON-NLS-1$ + + // get the author name + int endOfAuthorIndex = line.indexOf(';', endOfDateIndex + 1); + author = internAndCopyString(line.substring(endOfDateIndex + 11, endOfAuthorIndex)); - // get the file state (because this revision might be "dead") - int endOfStateIndex = line.indexOf(';', endOfAuthorIndex + 1) < 0 ? line.length() : line.indexOf(';', endOfAuthorIndex + 1); - fileState = internAndCopyString(line.substring(endOfAuthorIndex + 10, endOfStateIndex)); - comment = new StringBuffer(); - state = COMMENT; - break; - case COMMENT: - // skip next line (info about branches) if it exists, if not then it is a comment line. - if (line.startsWith("branches:")) break; //$NON-NLS-1$ - if (line.equals("=============================================================================") //$NON-NLS-1$ - || line.equals("----------------------------")) { //$NON-NLS-1$ - state = DONE; - break; - } - //check for null if we are in the waiting to finish case (brought on by branches) - if (comment == null) - break; - - if (comment.length() != 0) comment.append('\n'); - comment.append(line); - break; - } - if (state == DONE) { - // we are only interested in tag names for this revision, remove all others. - List thisRevisionTags = versions.isEmpty() ? Collections.EMPTY_LIST : new ArrayList(3); - List thisRevisionBranches = new ArrayList(1); - //a parallel lists for revision tags (used only for branches with no commits on them) - List revisionVersions = versions.isEmpty() ? Collections.EMPTY_LIST : new ArrayList(3); - String branchRevision = this.getBranchRevision(revision); - for (Iterator i = versions.iterator(); i.hasNext();) { - VersionInfo version = (VersionInfo) i.next(); - String tagName = version.getTagName(); - String tagRevision = version.getTagRevision(); - String tagBranchRevision = version.getBranchRevision(); + // get the file state (because this revision might be "dead") + int endOfStateIndex = line.indexOf(';', endOfAuthorIndex + 1) < 0 ? line.length() : line.indexOf(';', endOfAuthorIndex + 1); + fileState = internAndCopyString(line.substring(endOfAuthorIndex + 10, endOfStateIndex)); + comment = new StringBuffer(); + state = COMMENT; + break; + case COMMENT: + // skip next line (info about branches) if it exists, if not then it is a comment line. + if (line.startsWith("branches:")) break; //$NON-NLS-1$ + if (line.equals("=============================================================================") //$NON-NLS-1$ + || line.equals("----------------------------")) { //$NON-NLS-1$ + state = DONE; + break; + } + //check for null if we are in the waiting to finish case (brought on by branches) + if (comment == null) + break; + + if (comment.length() != 0) comment.append('\n'); + comment.append(line); + break; + } + if (state == DONE) { + // we are only interested in tag names for this revision, remove all others. + List thisRevisionTags = versions.isEmpty() ? Collections.EMPTY_LIST : new ArrayList(3); + List thisRevisionBranches = new ArrayList(1); + //a parallel lists for revision tags (used only for branches with no commits on them) + List revisionVersions = versions.isEmpty() ? Collections.EMPTY_LIST : new ArrayList(3); + String branchRevision = this.getBranchRevision(revision); + for (Iterator i = versions.iterator(); i.hasNext();) { + VersionInfo version = (VersionInfo) i.next(); + String tagName = version.getTagName(); + String tagRevision = version.getTagRevision(); + String tagBranchRevision = version.getBranchRevision(); int type = version.isBranch() ? CVSTag.BRANCH : CVSTag.VERSION; if ( branchRevision.equals(tagBranchRevision) || (version.isBranch() && revision.equals(tagRevision))) { - CVSTag cvsTag = new CVSTag(tagName, tagBranchRevision, type); - thisRevisionBranches.add(cvsTag); - } - + CVSTag cvsTag = new CVSTag(tagName, tagBranchRevision, type); + thisRevisionBranches.add(cvsTag); + } + if (tagRevision.equals(revision) || - revision.equals(BRANCH_REVISION)) { - CVSTag cvsTag = new CVSTag(tagName, tagBranchRevision, type); - thisRevisionTags.add(cvsTag); - if (revision.equals(BRANCH_REVISION)){ - //also record the tag revision - revisionVersions.add(tagRevision); - } - } - } - - if (branchRevision.equals(CVSTag.HEAD_REVISION)) { - CVSTag tag = new CVSTag(CVSTag.HEAD_BRANCH, CVSTag.HEAD_REVISION, CVSTag.HEAD); + revision.equals(BRANCH_REVISION)) { + CVSTag cvsTag = new CVSTag(tagName, tagBranchRevision, type); + thisRevisionTags.add(cvsTag); + if (revision.equals(BRANCH_REVISION)){ + //also record the tag revision + revisionVersions.add(tagRevision); + } + } + } + + if (branchRevision.equals(CVSTag.HEAD_REVISION)) { + CVSTag tag = new CVSTag(CVSTag.HEAD_BRANCH, CVSTag.HEAD_REVISION, CVSTag.HEAD); thisRevisionBranches.add(tag); - } else { - if ( thisRevisionBranches.size() == 0) { - CVSTag cvsTag = new CVSTag(CVSTag.UNKNOWN_BRANCH, branchRevision, CVSTag.BRANCH); - thisRevisionBranches.add(cvsTag); - } - } - if (currentFile != null) { - LogEntry entry = new LogEntry(currentFile, revision, author, creationDate, - internString(comment.toString()), fileState, - !thisRevisionTags.isEmpty() ? (CVSTag[]) thisRevisionTags.toArray(new CVSTag[thisRevisionTags.size()]) :NO_TAGS, - !thisRevisionBranches.isEmpty() ? (CVSTag[]) thisRevisionBranches.toArray(new CVSTag[thisRevisionBranches.size()]) :NO_TAGS, - !revisionVersions.isEmpty() ? (String[]) revisionVersions.toArray(new String[revisionVersions.size()]) : NO_VERSIONS); - addEntry(entry); - } - state = BEGIN; - } - return OK; - } + } else { + if ( thisRevisionBranches.size() == 0) { + CVSTag cvsTag = new CVSTag(CVSTag.UNKNOWN_BRANCH, branchRevision, CVSTag.BRANCH); + thisRevisionBranches.add(cvsTag); + } + } + if (currentFile != null) { + LogEntry entry = new LogEntry(currentFile, revision, author, creationDate, + internString(comment.toString()), fileState, + !thisRevisionTags.isEmpty() ? (CVSTag[]) thisRevisionTags.toArray(new CVSTag[thisRevisionTags.size()]) :NO_TAGS, + !thisRevisionBranches.isEmpty() ? (CVSTag[]) thisRevisionBranches.toArray(new CVSTag[thisRevisionBranches.size()]) :NO_TAGS, + !revisionVersions.isEmpty() ? (String[]) revisionVersions.toArray(new String[revisionVersions.size()]) : NO_VERSIONS); + addEntry(entry); + } + state = BEGIN; + } + return OK; + } - /** - * Convert revision number to branch number. - * - * <table border="1"> - * <tr><th>revision</th><th>branch</th><th>comment</th></tr> - * <tr><td>1.1.2.1</td><td>1.1.0.2</td><td>regular branch</td></tr> - * <tr><td>1.1.4.1</td><td>1.1.0.4</td><td>regular branch</td></tr> - * <tr><td>1.1.1.2</td><td>1.1.1</td><td>vendor branch</td></tr> - * <tr><td>1.1.2.1.2.3</td><td>1.1.2.1.0.2</td><td>branch created from another branch</td></tr> - * </table> - * - * @param revision revision number - * @return branch number - * - */ + /** + * Convert revision number to branch number. + * + * <table border="1"> + * <tr><th>revision</th><th>branch</th><th>comment</th></tr> + * <tr><td>1.1.2.1</td><td>1.1.0.2</td><td>regular branch</td></tr> + * <tr><td>1.1.4.1</td><td>1.1.0.4</td><td>regular branch</td></tr> + * <tr><td>1.1.1.2</td><td>1.1.1</td><td>vendor branch</td></tr> + * <tr><td>1.1.2.1.2.3</td><td>1.1.2.1.0.2</td><td>branch created from another branch</td></tr> + * </table> + * + * @param revision revision number + * @return branch number + * + */ private String getBranchRevision(String revision) { if (revision.length() == 0 || revision.lastIndexOf(".") == -1) //$NON-NLS-1$ throw new IllegalArgumentException( @@ -274,63 +274,63 @@ public class LogListener extends CommandOutputListener { branchPrefix += branchNumber.substring(branchNumber.lastIndexOf(".")); //$NON-NLS-1$ return branchPrefix; } - - protected void beginFile(ICVSRepositoryLocation location, String fileName) { - currentFile = RemoteFile.create(fileName, location); - versions.clear(); - } + + protected void beginFile(ICVSRepositoryLocation location, String fileName) { + currentFile = RemoteFile.create(fileName, location); + versions.clear(); + } - protected void addEntry(LogEntry entry) { - listener.handleLogEntryReceived(entry); - } + protected void addEntry(LogEntry entry) { + listener.handleLogEntryReceived(entry); + } - protected void handleInvalidFileName(ICVSRepositoryLocation location, String badFilePath) { - CVSProviderPlugin.log(IStatus.WARNING, "Invalid file path '" + badFilePath + "' received from " + location.toString(), null); //$NON-NLS-1$ //$NON-NLS-2$ - } + protected void handleInvalidFileName(ICVSRepositoryLocation location, String badFilePath) { + CVSProviderPlugin.log(IStatus.WARNING, "Invalid file path '" + badFilePath + "' received from " + location.toString(), null); //$NON-NLS-1$ //$NON-NLS-2$ + } - /** - * Converts a time stamp as sent from a cvs server for a "log" command into a - * <code>Date</code>. - */ - private Date convertFromLogTime(String modTime) { - DateFormat format = LOG_DATE_FORMATTER; - // Compatibility for older cvs version (pre 1.12.9) - if (modTime.length() > 4 && modTime.charAt(4) == '/') - format = LOG_DATE_FORMATTER_OLD; - - try { - return format.parse(modTime); - } catch (ParseException e) { - // fallback is to return null - return null; - } - } - - private String internAndCopyString(String string) { - String internedString = (String) internedStrings.get(string); - if (internedString == null) { - internedString = new String(string); - internedStrings.put(internedString, internedString); - } - return internedString; - } - - private String internString(String string) { - String internedString = (String) internedStrings.get(string); - if (internedString == null) { - internedString = string; - internedStrings.put(internedString, internedString); - } - return internedString; - } - - private static class VersionInfo { + /** + * Converts a time stamp as sent from a cvs server for a "log" command into a + * <code>Date</code>. + */ + private Date convertFromLogTime(String modTime) { + DateFormat format = LOG_DATE_FORMATTER; + // Compatibility for older cvs version (pre 1.12.9) + if (modTime.length() > 4 && modTime.charAt(4) == '/') + format = LOG_DATE_FORMATTER_OLD; + + try { + return format.parse(modTime); + } catch (ParseException e) { + // fallback is to return null + return null; + } + } + + private String internAndCopyString(String string) { + String internedString = (String) internedStrings.get(string); + if (internedString == null) { + internedString = new String(string); + internedStrings.put(internedString, internedString); + } + return internedString; + } + + private String internString(String string) { + String internedString = (String) internedStrings.get(string); + if (internedString == null) { + internedString = string; + internedStrings.put(internedString, internedString); + } + return internedString; + } + + private static class VersionInfo { private final boolean isBranch; private String tagRevision; private String branchRevision; private final String tagName; - public VersionInfo(String version, String tagName) { + public VersionInfo(String version, String tagName) { this.tagName = tagName; this.isBranch = isBranchTag(version); tagRevision = version; @@ -347,7 +347,7 @@ public class LogListener extends CommandOutputListener { tagRevision = version.substring(0, lastDot); } } - } + } public String getTagName() { return this.tagName; @@ -356,34 +356,34 @@ public class LogListener extends CommandOutputListener { public String getTagRevision() { return this.tagRevision; } - - public boolean isBranch() { - return isBranch; - } - - /** branch tags have odd number of segments or have - * an even number with a zero as the second last segment - * e.g: 1.1.1, 1.26.0.2 are branch revision numbers */ - private boolean isBranchTag(String tagName) { - // First check if we have an odd number of segments (i.e. even number of dots) - int numberOfDots = 0; - int lastDot = 0; - for (int i = 0; i < tagName.length(); i++) { - if (tagName.charAt(i) == '.') { - numberOfDots++; - lastDot = i; - } - } - if ((numberOfDots % 2) == 0) return true; - if (numberOfDots == 1) return false; - - // If not, check if the second lat segment is a zero - if (tagName.charAt(lastDot - 1) == '0' && tagName.charAt(lastDot - 2) == '.') return true; - return false; - } + + public boolean isBranch() { + return isBranch; + } + + /** branch tags have odd number of segments or have + * an even number with a zero as the second last segment + * e.g: 1.1.1, 1.26.0.2 are branch revision numbers */ + private boolean isBranchTag(String tagName) { + // First check if we have an odd number of segments (i.e. even number of dots) + int numberOfDots = 0; + int lastDot = 0; + for (int i = 0; i < tagName.length(); i++) { + if (tagName.charAt(i) == '.') { + numberOfDots++; + lastDot = i; + } + } + if ((numberOfDots % 2) == 0) return true; + if (numberOfDots == 1) return false; + + // If not, check if the second lat segment is a zero + if (tagName.charAt(lastDot - 1) == '0' && tagName.charAt(lastDot - 2) == '.') return true; + return false; + } public String getBranchRevision() { return branchRevision; } - } + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java index f1538dd52..849ab09c2 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java @@ -238,9 +238,9 @@ public class UpdateListener extends CommandOutputListener { if (resource != null) { return new CVSStatus(IStatus.ERROR, CVSStatus.UNMEGERED_BINARY_CONFLICT, NLS.bind(CVSMessages.UpdateListener_0, (new Object[] { - resource.getFullPath().toString(), - mergedBinaryFileRevision, - resource.getFullPath().removeLastSegments(1).append(backupFile).toString()})), commandRoot); + resource.getFullPath().toString(), + mergedBinaryFileRevision, + resource.getFullPath().removeLastSegments(1).append(backupFile).toString()})), commandRoot); } } } catch (CVSException e1) { @@ -265,8 +265,8 @@ public class UpdateListener extends CommandOutputListener { // To get the folders, the update request should be re-issued for HEAD return new CVSStatus(IStatus.WARNING, CVSStatus.NO_SUCH_TAG, line, commandRoot); } else if (message.startsWith("Numeric join") && message.endsWith("may not contain a date specifier")) { //$NON-NLS-1$ //$NON-NLS-2$ - // This error indicates a join failed because a date tag was used - return super.errorLine(line, location, commandRoot, monitor); + // This error indicates a join failed because a date tag was used + return super.errorLine(line, location, commandRoot, monitor); } else { return super.errorLine(line, location, commandRoot, monitor); } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSAuthenticationException.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSAuthenticationException.java index 256424391..8ff8f5f17 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSAuthenticationException.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSAuthenticationException.java @@ -25,7 +25,7 @@ public class CVSAuthenticationException extends CVSException { private int retryStatus = 0; - /** + /** * Code indicating that authentication can be retried after * prompting the user for corrected authentication information */ @@ -67,7 +67,7 @@ public class CVSAuthenticationException extends CVSException { this(new CVSStatus(IStatus.ERROR, CVSStatus.AUTHENTICATION_FAILURE,NLS.bind(CVSMessages.CVSAuthenticationException_detail, (new Object[] { detail })),cvsLocation)); // this.retryStatus = retryStatus; } - + /** * Creates a new <code>CVSAuthenticationException</code> * @@ -76,10 +76,10 @@ public class CVSAuthenticationException extends CVSException { * @param the location of the CVS server * @param the exception */ - public CVSAuthenticationException(String detail, int retryStatus,ICVSRepositoryLocation cvsLocation, Exception e) { - this(new CVSStatus(IStatus.ERROR, CVSStatus.AUTHENTICATION_FAILURE , NLS.bind(CVSMessages.CVSAuthenticationException_detail, (new Object[] { detail })), e, cvsLocation)); // - this.retryStatus = retryStatus; - } + public CVSAuthenticationException(String detail, int retryStatus,ICVSRepositoryLocation cvsLocation, Exception e) { + this(new CVSStatus(IStatus.ERROR, CVSStatus.AUTHENTICATION_FAILURE , NLS.bind(CVSMessages.CVSAuthenticationException_detail, (new Object[] { detail })), e, cvsLocation)); // + this.retryStatus = retryStatus; + } public int getRetryStatus() { return retryStatus; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSCommunicationException.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSCommunicationException.java index f5f227fb7..268297a2a 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSCommunicationException.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSCommunicationException.java @@ -24,7 +24,7 @@ public class CVSCommunicationException extends CVSException { private static final long serialVersionUID = 1L; - /** + /** * Create a new <code>CVSCommunicationException</code> with the * given status. */ @@ -75,18 +75,18 @@ public class CVSCommunicationException extends CVSException { } public static String getMessageFor(Throwable throwable) { - String message = Policy.getMessage(getMessageKey(throwable)); - if (message == null) { - message = NLS.bind(CVSMessages.CVSCommunicationException_io, (new Object[] {throwable.toString()})); - } else { - message = NLS.bind(message, (new Object[] {throwable.getMessage()})); - } + String message = Policy.getMessage(getMessageKey(throwable)); + if (message == null) { + message = NLS.bind(CVSMessages.CVSCommunicationException_io, (new Object[] {throwable.toString()})); + } else { + message = NLS.bind(message, (new Object[] {throwable.getMessage()})); + } return message; } - - private static String getMessageKey(Throwable t) { - String name = t.getClass().getName(); - name = name.replace('.', '_'); - return name; - } + + private static String getMessageKey(Throwable t) { + String name = t.getClass().getName(); + name = name.replace('.', '_'); + return name; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java index f484b4055..51486a6ad 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java @@ -290,7 +290,7 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit // Save options in hash table StringTokenizer stOpt = new StringTokenizer( location.substring(optionStart+1, end), - "=;" //$NON-NLS-1$ + "=;" //$NON-NLS-1$ ); while (stOpt.hasMoreTokens()) { hmOptions.put(stOpt.nextToken(), stOpt.nextToken()); @@ -343,11 +343,11 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit end= location.indexOf(COLON, start); int hostEnd = end; if (end == -1) { - // The last colon is optional so look for the slash that starts the path - end = location.indexOf('/', start); - hostEnd = end; - // Decrement the end since the slash is part of the path - if (end != -1) end--; + // The last colon is optional so look for the slash that starts the path + end = location.indexOf('/', start); + hostEnd = end; + // Decrement the end since the slash is part of the path + if (end != -1) end--; } String host = (hmOptions.containsKey("hostname")) ? hmOptions.get("hostname").toString() : location.substring(start, hostEnd); //$NON-NLS-1$ //$NON-NLS-2$ int port = USE_DEFAULT_PORT; @@ -721,8 +721,8 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit * for any connection made to this remote location. */ public Connection openConnection(IProgressMonitor monitor) throws CVSException { - // Get the lock for the host to ensure that we are not connecting to the same host concurrently. - Policy.checkCanceled(monitor); + // Get the lock for the host to ensure that we are not connecting to the same host concurrently. + Policy.checkCanceled(monitor); ILock hostLock; synchronized(hostLocks) { hostLock = hostLocks.get(getHost()); @@ -732,11 +732,11 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit } } try { - boolean acquired = false; - int count = 0; - int timeout = CVSProviderPlugin.getPlugin().getTimeout(); - while (!acquired) { - try { + boolean acquired = false; + int count = 0; + int timeout = CVSProviderPlugin.getPlugin().getTimeout(); + while (!acquired) { + try { acquired = hostLock.acquire(1000); } catch (InterruptedException e) { // Ignore @@ -746,7 +746,7 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit } count++; Policy.checkCanceled(monitor); - } + } // Allow two ticks in case of a retry monitor.beginTask(NLS.bind(CVSMessages.CVSRepositoryLocation_openingConnection, new String[] { getHost() }), 2); ensureLocationCached(); @@ -773,9 +773,9 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit // password = "";//$NON-NLS-1$ Connection connection = createConnection(password, monitor); if (cacheNeedsUpdate) - updateCachedLocation(); + updateCachedLocation(); previousAuthenticationFailed = false; - return connection; + return connection; } catch (CVSAuthenticationException ex) { previousAuthenticationFailed = true; if (ex.getRetryStatus() == CVSAuthenticationException.RETRY) { @@ -789,7 +789,7 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit } } } finally { - hostLock.release(); + hostLock.release(); monitor.done(); } } @@ -805,76 +805,76 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit authenticator.promptForUserInfo(this, this, message); } - /* + /* * Ensure that this location is in the known repositories list * and that the authentication information matches what is in the * cache, if this instance is not the instance in the cache. - */ - private void ensureLocationCached() { - String location = getLocation(); - KnownRepositories repositories = KnownRepositories.getInstance(); - if (repositories.isKnownRepository(location)) { - try { - // The repository is already known. - // Ensure that the authentication information of this - // location matches that of the known location - setAuthenticationInformation((CVSRepositoryLocation)repositories.getRepository(location)); - } catch (CVSException e) { - // Log the exception and continue - CVSProviderPlugin.log(e); - } - } else { - // The repository is not known so record it so any authentication - // information the user may provide is remembered - repositories.addRepository(this, true /* broadcast */); - } - } + */ + private void ensureLocationCached() { + String location = getLocation(); + KnownRepositories repositories = KnownRepositories.getInstance(); + if (repositories.isKnownRepository(location)) { + try { + // The repository is already known. + // Ensure that the authentication information of this + // location matches that of the known location + setAuthenticationInformation((CVSRepositoryLocation)repositories.getRepository(location)); + } catch (CVSException e) { + // Log the exception and continue + CVSProviderPlugin.log(e); + } + } else { + // The repository is not known so record it so any authentication + // information the user may provide is remembered + repositories.addRepository(this, true /* broadcast */); + } + } /* * Set the authentication information of this instance such that it matches the * provided instances. - */ - private void setAuthenticationInformation(CVSRepositoryLocation other) { - if (other != this) { - // The instances differ so copy from the other location to this one - if (other.getUserInfoCached()) { - // The user info is cached for the other instance - // so null all the values in this instance so the - // information is obtained from the cache - this.allowCaching = true; - if (!userFixed) this.user = null; - if (!passwordFixed) this.password = null; - } else { - // The user info is not cached for the other instance so - // copy the authentication information into this instance - setAllowCaching(false); /* this will clear any cached values */ - // Only copy the username and password if they are not fixed. - // (If they are fixed, they would be included in the location - // identifier and therefore must already match) - if (!other.userFixed) - this.user = other.user; - if (!other.passwordFixed) - this.password = other.password; - } - } - } + */ + private void setAuthenticationInformation(CVSRepositoryLocation other) { + if (other != this) { + // The instances differ so copy from the other location to this one + if (other.getUserInfoCached()) { + // The user info is cached for the other instance + // so null all the values in this instance so the + // information is obtained from the cache + this.allowCaching = true; + if (!userFixed) this.user = null; + if (!passwordFixed) this.password = null; + } else { + // The user info is not cached for the other instance so + // copy the authentication information into this instance + setAllowCaching(false); /* this will clear any cached values */ + // Only copy the username and password if they are not fixed. + // (If they are fixed, they would be included in the location + // identifier and therefore must already match) + if (!other.userFixed) + this.user = other.user; + if (!other.passwordFixed) + this.password = other.password; + } + } + } - /* - * The connection was successfully made. Update the cached - * repository location if it is a different instance than - * this location. - */ - private void updateCachedLocation() { - try { - CVSRepositoryLocation known = (CVSRepositoryLocation)KnownRepositories.getInstance().getRepository(getLocation()); - known.setAuthenticationInformation(this); - } catch (CVSException e) { - // Log the exception and continue - CVSProviderPlugin.log(e); - } - } - - /* + /* + * The connection was successfully made. Update the cached + * repository location if it is a different instance than + * this location. + */ + private void updateCachedLocation() { + try { + CVSRepositoryLocation known = (CVSRepositoryLocation)KnownRepositories.getInstance().getRepository(getLocation()); + known.setAuthenticationInformation(this); + } catch (CVSException e) { + // Log the exception and continue + CVSProviderPlugin.log(e); + } + } + + /* * Implementation of inherited toString() */ public String toString() { @@ -950,13 +950,13 @@ public class CVSRepositoryLocation extends PlatformObject implements ICVSReposit public void setAllowCaching(boolean value) { allowCaching = value; - if (allowCaching) { - updateCache(); - } else { - if (password == null) - password = retrievePassword(); - removeNode(); - } + if (allowCaching) { + updateCache(); + } else { + if (password == null) + password = retrievePassword(); + removeNode(); + } } public void updateCache() { diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSServerException.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSServerException.java index 7c9e36c3d..c4b7c7b7c 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSServerException.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSServerException.java @@ -26,7 +26,7 @@ public class CVSServerException extends CVSException { private static final long serialVersionUID = 1L; - /** + /** * Return true if the exception from the cvs server is the no tag error, and false * otherwise. */ diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/Connection.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/Connection.java index c298a78b2..230eaf0a7 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/Connection.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/Connection.java @@ -173,7 +173,7 @@ public class Connection { String result = new String(buffer, 0, index, getEncoding(location)); if (Policy.isDebugProtocol()) - Policy.printProtocolLine(result); + Policy.printProtocolLine(result); return result; } @@ -183,7 +183,7 @@ public class Connection { * Sends the given string to the server. */ public void write(String s) throws CVSException { - try { + try { write(s.getBytes(fServerEncoding), false); } catch (UnsupportedEncodingException e) { IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.SERVER_ERROR, e.getMessage(), e, fCVSRoot); @@ -224,7 +224,7 @@ public class Connection { throw new CVSCommunicationException(CVSMessages.Connection_writeUnestablishedConnection,fCVSRoot,null); if (Policy.isDebugProtocol()) - Policy.printProtocol(new String(b, off, len), newline); + Policy.printProtocol(new String(b, off, len), newline); try { OutputStream out= getOutputStream(); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java index 935069365..4d628c7a6 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java @@ -101,31 +101,31 @@ public class PServerConnection implements IServerConnection { InputStream is = null; OutputStream os = null; - - Proxy proxy = getProxy(); - if (proxy!=null) { - String host = cvsroot.getHost(); - int port = cvsroot.getPort(); - if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) { - port = DEFAULT_PORT; - } - try { - int timeout = CVSProviderPlugin.getPlugin().getTimeout() * 1000; - IJSchService service = CVSProviderPlugin.getPlugin().getJSchService(); - service.connect(proxy, host, port, timeout, monitor); - } catch( Exception ex) { - ex.printStackTrace(); - throw new IOException(ex.getMessage()); - } - is = proxy.getInputStream(); - os = proxy.getOutputStream(); - - } else { - fSocket = createSocket(monitor); - is = fSocket.getInputStream(); - os = fSocket.getOutputStream(); - } - + + Proxy proxy = getProxy(); + if (proxy!=null) { + String host = cvsroot.getHost(); + int port = cvsroot.getPort(); + if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) { + port = DEFAULT_PORT; + } + try { + int timeout = CVSProviderPlugin.getPlugin().getTimeout() * 1000; + IJSchService service = CVSProviderPlugin.getPlugin().getJSchService(); + service.connect(proxy, host, port, timeout, monitor); + } catch( Exception ex) { + ex.printStackTrace(); + throw new IOException(ex.getMessage()); + } + is = proxy.getInputStream(); + os = proxy.getOutputStream(); + + } else { + fSocket = createSocket(monitor); + is = fSocket.getInputStream(); + os = fSocket.getOutputStream(); + } + boolean connected = false; try { this.inputStream = new BufferedInputStream(new PollingInputStream(is, @@ -147,8 +147,8 @@ public class PServerConnection implements IServerConnection { Proxy proxy = service.getProxyForHost(cvsroot.getHost(), IProxyData.SOCKS_PROXY_TYPE); if (proxy == null) proxy = service.getProxyForHost(cvsroot.getHost(), IProxyData.HTTPS_PROXY_TYPE); - return proxy; - } + return proxy; + } @Override public InputStream getInputStream() { @@ -204,29 +204,29 @@ public class PServerConnection implements IServerConnection { String message = "";//$NON-NLS-1$ String separator = ""; //$NON-NLS-1$ - if(!CVSProviderPlugin.getPlugin().isUseProxy()) { - while (line.length() > 0 && line.charAt(0) == ERROR_CHAR) { - if (line.length() > 2) { - message += separator + line.substring(2); - separator = " "; //$NON-NLS-1$ - } - line = Connection.readLine(cvsroot, getInputStream()); - } - } else { - while (line.length() > 0) { - message += separator + line; - separator = "\n"; //$NON-NLS-1$ - line = Connection.readLine(cvsroot, getInputStream()); - } - } + if(!CVSProviderPlugin.getPlugin().isUseProxy()) { + while (line.length() > 0 && line.charAt(0) == ERROR_CHAR) { + if (line.length() > 2) { + message += separator + line.substring(2); + separator = " "; //$NON-NLS-1$ + } + line = Connection.readLine(cvsroot, getInputStream()); + } + } else { + while (line.length() > 0) { + message += separator + line; + separator = "\n"; //$NON-NLS-1$ + line = Connection.readLine(cvsroot, getInputStream()); + } + } // If the last line is the login failed (I HATE YOU) message, return authentication failure if (LOGIN_FAILED.equals(line)) { - if (message.length() == 0) { - throw new CVSAuthenticationException(CVSMessages.PServerConnection_loginRefused, CVSAuthenticationException.RETRY,cvsroot); - } else { - throw new CVSAuthenticationException(message, CVSAuthenticationException.RETRY,cvsroot); - } + if (message.length() == 0) { + throw new CVSAuthenticationException(CVSMessages.PServerConnection_loginRefused, CVSAuthenticationException.RETRY,cvsroot); + } else { + throw new CVSAuthenticationException(message, CVSAuthenticationException.RETRY,cvsroot); + } } // Remove leading "error 0" @@ -276,5 +276,5 @@ public class PServerConnection implements IServerConnection { private void throwInValidCharacter() throws CVSAuthenticationException { throw new CVSAuthenticationException(CVSMessages.PServerConnection_invalidChars, CVSAuthenticationException.RETRY, cvsroot); } - + } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filesystem/CVSFileSystem.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filesystem/CVSFileSystem.java index 94e6e8834..99fc9869d 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filesystem/CVSFileSystem.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/filesystem/CVSFileSystem.java @@ -57,7 +57,7 @@ public class CVSFileSystem extends FileSystem { public CVSFileTree refreshTree(URI uri, IProgressMonitor monitor){ - CVSURI cvsURI = CVSURI.fromUri(uri); + CVSURI cvsURI = CVSURI.fromUri(uri); //Make sure that we're building the tree from the topmost level - keep cycling until you hit null ICVSRemoteFolder folder = cvsURI.getProjectURI().toFolder(); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/mapping/CVSCheckedInChangeSet.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/mapping/CVSCheckedInChangeSet.java index 95b5132de..fc79e9783 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/mapping/CVSCheckedInChangeSet.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/mapping/CVSCheckedInChangeSet.java @@ -22,29 +22,29 @@ import org.eclipse.team.internal.core.subscribers.DiffChangeSet; public class CVSCheckedInChangeSet extends DiffChangeSet { - private final ILogEntry entry; + private final ILogEntry entry; - public CVSCheckedInChangeSet(ILogEntry entry) { - this.entry = entry; + public CVSCheckedInChangeSet(ILogEntry entry) { + this.entry = entry; Date date = entry.getDate(); String comment = LogEntry.flattenText(entry.getComment()); if (date == null) { setName("["+entry.getAuthor()+ "] " + comment); //$NON-NLS-1$ //$NON-NLS-2$ } else { String dateString = DateFormat.getDateTimeInstance().format(date); - setName("["+entry.getAuthor()+ "] (" + dateString +") " + comment); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + setName("["+entry.getAuthor()+ "] (" + dateString +") " + comment); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } - } - - public String getAuthor() { - return entry.getAuthor(); - } + } + + public String getAuthor() { + return entry.getAuthor(); + } - public Date getDate() { - return entry.getDate(); - } + public Date getDate() { + return entry.getDate(); + } - public String getComment() { - return entry.getComment(); - } + public String getComment() { + return entry.getComment(); + } }
\ No newline at end of file diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSEntryLineTag.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSEntryLineTag.java index 3f9315fdc..e0d4904e1 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSEntryLineTag.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSEntryLineTag.java @@ -23,10 +23,10 @@ import org.eclipse.team.internal.ccvs.core.*; public class CVSEntryLineTag extends CVSTag { - /* - * This is the format of a date as it appears in the entry line. The date in an entry - * line is always in GMT. - */ + /* + * This is the format of a date as it appears in the entry line. The date in an entry + * line is always in GMT. + */ private static final String ENTRY_LINE_DATE_TAG_FORMAT = "yyyy.MM.dd.HH.mm.ss"; //$NON-NLS-1$ /* @@ -62,7 +62,7 @@ public class CVSEntryLineTag extends CVSTag { static synchronized public Date entryLineToDate(String text){ try { - entryLineDateTagFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$ + entryLineDateTagFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$ return entryLineDateTagFormatter.parse(text); } catch (ParseException e) { CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, CVSStatus.ERROR, "Tag name " + text + " is not of the expected format " + ENTRY_LINE_DATE_TAG_FORMAT, e)); //$NON-NLS-1$ //$NON-NLS-2$ diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSWorkspaceRoot.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSWorkspaceRoot.java index 12c2553d2..b0ce6e55d 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSWorkspaceRoot.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/CVSWorkspaceRoot.java @@ -54,12 +54,12 @@ public class CVSWorkspaceRoot { if ( ! info.equals(folderInfo)) { throw new CVSException(new CVSStatus(IStatus.ERROR, NLS.bind(CVSMessages.CVSProvider_infoMismatch, new String[] { project.getName() }))); } - - // Ensure that the repository location format is supported - String root = info.getRoot(); - // This will try to create a repository location for the root. - // If it fails, an exception is thrown. - KnownRepositories.getInstance().getRepository(root); + + // Ensure that the repository location format is supported + String root = info.getRoot(); + // This will try to create a repository location for the root. + // If it fails, an exception is thrown. + KnownRepositories.getInstance().getRepository(root); // Register the project with Team RepositoryProvider.map(project, CVSProviderPlugin.getTypeId()); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFile.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFile.java index 4c094f94d..fc7f6e359 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFile.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFile.java @@ -59,12 +59,12 @@ public class EclipseFile extends EclipseResource implements ICVSFile { } public InputStream getContents() throws CVSException { - try { + try { return getIFile().getContents(); } catch (CoreException e) { - throw CVSException.wrapException(resource, NLS.bind(CVSMessages.EclipseFile_Problem_accessing_resource, new String[] { resource.getFullPath().toString(), e.getStatus().getMessage() }), e); // - } - } + throw CVSException.wrapException(resource, NLS.bind(CVSMessages.EclipseFile_Problem_accessing_resource, new String[] { resource.getFullPath().toString(), e.getStatus().getMessage() }), e); // + } + } @Override public Date getTimeStamp() { @@ -204,10 +204,10 @@ public class EclipseFile extends EclipseResource implements ICVSFile { if (attributes != null) { attributes.setReadOnly(readOnly); try { - resource.setResourceAttributes(attributes); - } catch (CoreException e) { - throw CVSException.wrapException(e); - } + resource.setResourceAttributes(attributes); + } catch (CoreException e) { + throw CVSException.wrapException(e); + } } } @@ -222,10 +222,10 @@ public class EclipseFile extends EclipseResource implements ICVSFile { if (attributes != null) { attributes.setExecutable(executable); try { - resource.setResourceAttributes(attributes); - } catch (CoreException e) { - throw CVSException.wrapException(e); - } + resource.setResourceAttributes(attributes); + } catch (CoreException e) { + throw CVSException.wrapException(e); + } } } @@ -355,12 +355,12 @@ public class EclipseFile extends EclipseResource implements ICVSFile { } try { - // allow editing - setReadOnly(false); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + // allow editing + setReadOnly(false); + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } }, monitor); } @@ -400,12 +400,12 @@ public class EclipseFile extends EclipseResource implements ICVSFile { setBaserevInfo(null); try { - // prevent editing - setReadOnly(true); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + // prevent editing + setReadOnly(true); + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } }, monitor); } @@ -442,28 +442,28 @@ public class EclipseFile extends EclipseResource implements ICVSFile { modificationState = ICVSFile.DIRTY; } else { // cvs commit: commit of a changed file - // cvs update: update of a file whose contents match the server contents - Date timeStamp; - if (commit) { - // This is a commit. Put the file timestamp in the entry - timeStamp = getTimeStamp(); - } else { - // This is an update. We need to change the tiemstamp in the - // entry file to match the file timestamp returned by Java - timeStamp = oldInfo.getTimeStamp(); - if (timeStamp == null) { - timeStamp = getTimeStamp(); - } else { - // First, set the timestamp of the file to the timestamp from the entry - // There is a chance this will do nothing as the call to Java on some - // file systems munges the timestamps - setTimeStamp(timeStamp); - // To compensate for the above, reset the timestamp in the entry - // to match the timestamp in the file - timeStamp = getTimeStamp(); - } - } - newInfo = new ResourceSyncInfo(entryLine, timeStamp); + // cvs update: update of a file whose contents match the server contents + Date timeStamp; + if (commit) { + // This is a commit. Put the file timestamp in the entry + timeStamp = getTimeStamp(); + } else { + // This is an update. We need to change the tiemstamp in the + // entry file to match the file timestamp returned by Java + timeStamp = oldInfo.getTimeStamp(); + if (timeStamp == null) { + timeStamp = getTimeStamp(); + } else { + // First, set the timestamp of the file to the timestamp from the entry + // There is a chance this will do nothing as the call to Java on some + // file systems munges the timestamps + setTimeStamp(timeStamp); + // To compensate for the above, reset the timestamp in the entry + // to match the timestamp in the file + timeStamp = getTimeStamp(); + } + } + newInfo = new ResourceSyncInfo(entryLine, timeStamp); } //see bug 106876 @@ -483,23 +483,23 @@ public class EclipseFile extends EclipseResource implements ICVSFile { if (base != null) { setBaserevInfo(null); try { - setReadOnly(true); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + setReadOnly(true); + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } } else { - // Check to see if watch-edit is enabled for the project - CVSTeamProvider provider = (CVSTeamProvider)RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()); - if (provider != null && provider.isWatchEditEnabled()) { - try { - setReadOnly(true); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } - } - } + // Check to see if watch-edit is enabled for the project + CVSTeamProvider provider = (CVSTeamProvider)RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()); + if (provider != null && provider.isWatchEditEnabled()) { + try { + setReadOnly(true); + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } + } + } } @Override diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFolder.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFolder.java index 5ccf5374f..d15a35d64 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFolder.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseFolder.java @@ -53,31 +53,31 @@ class EclipseFolder extends EclipseResource implements ICVSFolder { for (int i = 0; i < resources.length; i++) { IResource resource = resources[i]; int type = resource.getType(); - if ((includeFiles && (type==IResource.FILE)) + if ((includeFiles && (type==IResource.FILE)) || (includeFolders && (type==IResource.FOLDER))) { - boolean exists = resource.exists(); - if ((includeExisting && exists) || (includePhantoms && !exists)) { - ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource); - boolean includeResource = false; - if ((includeManaged && includeUnmanaged && includeIgnored)) { - includeResource = true; - } else { - boolean isManaged = cvsResource.isManaged(); - if (isManaged && includeManaged) { - includeResource = true; - } else if (exists) { - boolean isIgnored = cvsResource.isIgnored(); - if (isIgnored && includeIgnored) { - includeResource = true; - } else if (! isManaged && ! isIgnored && includeUnmanaged) { - includeResource = true; - } - } - } - if (includeResource) { - result.add(cvsResource); - } - } + boolean exists = resource.exists(); + if ((includeExisting && exists) || (includePhantoms && !exists)) { + ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource); + boolean includeResource = false; + if ((includeManaged && includeUnmanaged && includeIgnored)) { + includeResource = true; + } else { + boolean isManaged = cvsResource.isManaged(); + if (isManaged && includeManaged) { + includeResource = true; + } else if (exists) { + boolean isIgnored = cvsResource.isIgnored(); + if (isIgnored && includeIgnored) { + includeResource = true; + } else if (! isManaged && ! isIgnored && includeUnmanaged) { + includeResource = true; + } + } + } + if (includeResource) { + result.add(cvsResource); + } + } } } return result.toArray(new ICVSResource[result.size()]); @@ -234,12 +234,12 @@ class EclipseFolder extends EclipseResource implements ICVSFolder { monitor.worked(1); IResource resource = members[i]; if (resource.getType() == IResource.FILE) { - ResourceAttributes attrs = resource.getResourceAttributes(); - if (attrs != null && attrs.isReadOnly()) { - attrs.setReadOnly(false); - resource.setResourceAttributes(attrs); - } - } else { + ResourceAttributes attrs = resource.getResourceAttributes(); + if (attrs != null && attrs.isReadOnly()) { + attrs.setReadOnly(false); + resource.setResourceAttributes(attrs); + } + } else { recursiveUnmanage((IContainer) resource, monitor); } } @@ -260,12 +260,12 @@ class EclipseFolder extends EclipseResource implements ICVSFolder { @Override public ICVSResource getChild(String namedPath) throws CVSException { - if (namedPath.equals(Session.CURRENT_LOCAL_FOLDER)) { - return this; - } + if (namedPath.equals(Session.CURRENT_LOCAL_FOLDER)) { + return this; + } IPath path = new Path(null, namedPath); if(path.segmentCount()==0) { - return this; + return this; } IResource child = ((IContainer)resource).findMember(path, true /* include phantoms */); if(child!=null) { diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseResource.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseResource.java index be79effb9..30f4a16f8 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseResource.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseResource.java @@ -33,8 +33,8 @@ import org.eclipse.team.internal.ccvs.core.util.Util; */ abstract class EclipseResource implements ICVSResource, Comparable { - // The separator that must be used when creating CVS resource paths. Never use - // the platform default separator since it is not compatible with CVS resources. + // The separator that must be used when creating CVS resource paths. Never use + // the platform default separator since it is not compatible with CVS resources. protected static final String SEPARATOR = Session.SERVER_SEPARATOR; protected static final String CURRENT_LOCAL_FOLDER = Session.CURRENT_LOCAL_FOLDER; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseSynchronizer.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseSynchronizer.java index 11fdf0b81..fb010a389 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseSynchronizer.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/EclipseSynchronizer.java @@ -148,10 +148,10 @@ public class EclipseSynchronizer implements IFlushOperation { */ public FolderSyncInfo getFolderSync(IContainer folder) throws CVSException { if (folder.getType() == IResource.ROOT || !isValid(folder)) return null; - // Do a check outside the lock for any folder sync info - FolderSyncInfo info = getSyncInfoCacheFor(folder).getCachedFolderSync(folder, false /* not thread safe */); - if (info != null) - return info; + // Do a check outside the lock for any folder sync info + FolderSyncInfo info = getSyncInfoCacheFor(folder).getCachedFolderSync(folder, false /* not thread safe */); + if (info != null) + return info; try { beginOperation(); cacheFolderSync(folder); @@ -262,10 +262,10 @@ public class EclipseSynchronizer implements IFlushOperation { public byte[] getSyncBytes(IResource resource) throws CVSException { IContainer parent = resource.getParent(); if (parent == null || parent.getType() == IResource.ROOT || !isValid(parent)) return null; - // Do a quick check outside the lock to see if there are sync butes for the resource. - byte[] info = getSyncInfoCacheFor(resource).getCachedSyncBytes(resource, false /* not thread safe */); - if (info != null) - return info; + // Do a quick check outside the lock to see if there are sync butes for the resource. + byte[] info = getSyncInfoCacheFor(resource).getCachedSyncBytes(resource, false /* not thread safe */); + if (info != null) + return info; try { beginOperation(); // cache resource sync for siblings, then return for self @@ -368,20 +368,20 @@ public class EclipseSynchronizer implements IFlushOperation { */ public boolean isIgnored(IResource resource) throws CVSException { if (resource.getType() == IResource.ROOT || - resource.getType() == IResource.PROJECT || - ! resource.exists()) { + resource.getType() == IResource.PROJECT || + ! resource.exists()) { return false; } IContainer parent = resource.getParent(); - FileNameMatcher matcher = sessionPropertyCache.getFolderIgnores(parent, false /* not thread safe */); - if (matcher == null) { - try { - beginOperation(); - matcher = cacheFolderIgnores(parent); - } finally { - endOperation(); - } - } + FileNameMatcher matcher = sessionPropertyCache.getFolderIgnores(parent, false /* not thread safe */); + if (matcher == null) { + try { + beginOperation(); + matcher = cacheFolderIgnores(parent); + } finally { + endOperation(); + } + } return matcher.match(resource.getName()); } @@ -499,10 +499,10 @@ public class EclipseSynchronizer implements IFlushOperation { */ public void endBatching(ISchedulingRule rule, IProgressMonitor monitor) throws CVSException { try { - resourceLock.release(rule, monitor); - } catch (TeamException e) { - throw CVSException.wrapException(e); - } + resourceLock.release(rule, monitor); + } catch (TeamException e) { + throw CVSException.wrapException(e); + } } /* @@ -532,21 +532,21 @@ public class EclipseSynchronizer implements IFlushOperation { */ private void beginOperation() { try { - // Do not try to acquire the lock if the resources tree is locked - // The reason for this is that during the resource delta phase (i.e. when the tree is locked) - // the workspace lock is held. If we obtain our lock, there is - // a chance of dealock. It is OK if we don't as we are still protected - // by scheduling rules and the workspace lock. - if (ResourcesPlugin.getWorkspace().isTreeLocked()) return; - } catch (RuntimeException e) { - // If we are not active, throw a cancel. Otherwise, propogate it. - // (see bug 78303) - if (Platform.getBundle(CVSProviderPlugin.ID).getState() == Bundle.ACTIVE) { - throw e; - } else { - throw new OperationCanceledException(); - } - } + // Do not try to acquire the lock if the resources tree is locked + // The reason for this is that during the resource delta phase (i.e. when the tree is locked) + // the workspace lock is held. If we obtain our lock, there is + // a chance of dealock. It is OK if we don't as we are still protected + // by scheduling rules and the workspace lock. + if (ResourcesPlugin.getWorkspace().isTreeLocked()) return; + } catch (RuntimeException e) { + // If we are not active, throw a cancel. Otherwise, propogate it. + // (see bug 78303) + if (Platform.getBundle(CVSProviderPlugin.ID).getState() == Bundle.ACTIVE) { + throw e; + } else { + throw new OperationCanceledException(); + } + } lock.acquire(); } @@ -555,17 +555,17 @@ public class EclipseSynchronizer implements IFlushOperation { */ private void endOperation() { try { - // See beginOperation() for a description of why the lock is not obtained when the tree is locked - if (ResourcesPlugin.getWorkspace().isTreeLocked()) return; - } catch (RuntimeException e) { - // If we are not active, throw a cancel. Otherwise, propogate it. - // (see bug 78303) - if (Platform.getBundle(CVSProviderPlugin.ID).getState() == Bundle.ACTIVE) { - throw e; - } else { - throw new OperationCanceledException(); - } - } + // See beginOperation() for a description of why the lock is not obtained when the tree is locked + if (ResourcesPlugin.getWorkspace().isTreeLocked()) return; + } catch (RuntimeException e) { + // If we are not active, throw a cancel. Otherwise, propogate it. + // (see bug 78303) + if (Platform.getBundle(CVSProviderPlugin.ID).getState() == Bundle.ACTIVE) { + throw e; + } else { + throw new OperationCanceledException(); + } + } lock.release(); } @@ -595,8 +595,8 @@ public class EclipseSynchronizer implements IFlushOperation { // Flush changes to disk resourceLock.flush(Policy.subMonitorFor(monitor, 8)); } catch (TeamException e) { - throw CVSException.wrapException(e); - } finally { + throw CVSException.wrapException(e); + } finally { // Purge the in-memory cache sessionPropertyCache.purgeCache(root, deep); } @@ -638,55 +638,55 @@ public class EclipseSynchronizer implements IFlushOperation { public void ignoreFilesChanged(IContainer[] roots) throws CVSException { for (int i = 0; i < roots.length; i++) { IContainer container = roots[i]; - if (container.exists()) { - ISchedulingRule rule = null; - try { - Set<IResource> changed = new HashSet<>(); - rule = beginBatching(container, null); - try { - beginOperation(); - - // Record the previous ignore pattterns - FileNameMatcher oldIgnores = null; - if (sessionPropertyCache.isFolderSyncInfoCached(container)) { - oldIgnores = cacheFolderIgnores(container); - } - - // Purge the cached state for direct children of the container - changed.addAll(Arrays.asList( - sessionPropertyCache.purgeCache(container, oldIgnores == null /*flush deeply if the old patterns are not known*/))); - - // Purge the state for any children of previously ignored containers - if (oldIgnores != null) { - FileNameMatcher newIgnores = cacheFolderIgnores(container); - try { - IResource[] members = container.members(); - for (int j = 0; j < members.length; j++) { - IResource resource = members[j]; - if (resource.getType() == IResource.FOLDER) { - String name = resource.getName(); - if (oldIgnores.match(name) && !newIgnores.match(name)) { - changed.addAll(Arrays.asList( - sessionPropertyCache.purgeCache((IContainer)resource, true /*flush deeply*/))); - } - } - } - } catch (CoreException e) { - // Just log and continue - CVSProviderPlugin.log(e); - } - } - } finally { - endOperation(); - } - if (!changed.isEmpty()) { - ResourceStateChangeListeners.getListener().resourceSyncInfoChanged( - changed.toArray(new IResource[changed.size()])); - } - } finally { - if (rule != null) endBatching(rule, null); - } - } + if (container.exists()) { + ISchedulingRule rule = null; + try { + Set<IResource> changed = new HashSet<>(); + rule = beginBatching(container, null); + try { + beginOperation(); + + // Record the previous ignore pattterns + FileNameMatcher oldIgnores = null; + if (sessionPropertyCache.isFolderSyncInfoCached(container)) { + oldIgnores = cacheFolderIgnores(container); + } + + // Purge the cached state for direct children of the container + changed.addAll(Arrays.asList( + sessionPropertyCache.purgeCache(container, oldIgnores == null /*flush deeply if the old patterns are not known*/))); + + // Purge the state for any children of previously ignored containers + if (oldIgnores != null) { + FileNameMatcher newIgnores = cacheFolderIgnores(container); + try { + IResource[] members = container.members(); + for (int j = 0; j < members.length; j++) { + IResource resource = members[j]; + if (resource.getType() == IResource.FOLDER) { + String name = resource.getName(); + if (oldIgnores.match(name) && !newIgnores.match(name)) { + changed.addAll(Arrays.asList( + sessionPropertyCache.purgeCache((IContainer)resource, true /*flush deeply*/))); + } + } + } + } catch (CoreException e) { + // Just log and continue + CVSProviderPlugin.log(e); + } + } + } finally { + endOperation(); + } + if (!changed.isEmpty()) { + ResourceStateChangeListeners.getListener().resourceSyncInfoChanged( + changed.toArray(new IResource[changed.size()])); + } + } finally { + if (rule != null) endBatching(rule, null); + } + } } } @@ -954,9 +954,9 @@ public class EclipseSynchronizer implements IFlushOperation { IResource[] changedResources = threadInfo.getChangedResources(); IContainer[] changedFolders; if (threadInfo instanceof CVSThreadInfo) { - changedFolders = ((CVSThreadInfo)threadInfo).getChangedFolders(); + changedFolders = ((CVSThreadInfo)threadInfo).getChangedFolders(); } else { - changedFolders = new IContainer[0]; + changedFolders = new IContainer[0]; } Set<IContainer> dirtyParents = new HashSet<>(); for (int i = 0; i < changedResources.length; i++) { @@ -981,7 +981,7 @@ public class EclipseSynchronizer implements IFlushOperation { IContainer folder = changedFolders[i]; if (folder.exists() && folder.getType() != IResource.ROOT) { try { - beginOperation(); + beginOperation(); FolderSyncInfo info = sessionPropertyCache.getCachedFolderSync(folder, true); // Do not write the folder sync for linked resources if (info == null) { @@ -1002,8 +1002,8 @@ public class EclipseSynchronizer implements IFlushOperation { } errors.add(e.getStatus()); } finally { - endOperation(); - } + endOperation(); + } } monitor.worked(1); } @@ -1017,7 +1017,7 @@ public class EclipseSynchronizer implements IFlushOperation { if (folder.exists() && folder.getType() != IResource.ROOT) { // write sync info for all children in one go try { - beginOperation(); + beginOperation(); List<byte[]> infos = new ArrayList<>(); IResource[] children = folder.members(true); for (int i = 0; i < children.length; i++) { @@ -1046,8 +1046,8 @@ public class EclipseSynchronizer implements IFlushOperation { } errors.add(e.getStatus()); } finally { - endOperation(); - } + endOperation(); + } } monitor.worked(1); } @@ -1114,9 +1114,9 @@ public class EclipseSynchronizer implements IFlushOperation { } /** - * Sets the resource sync info for the resource; if null, deletes it. Parent - * must exist and must not be the workspace root. The resource sync info for - * the children of the parent container MUST ALREADY BE CACHED. + * Sets the resource sync info for the resource; if null, deletes it. Parent + * must exist and must not be the workspace root. The resource sync info for + * the children of the parent container MUST ALREADY BE CACHED. * * @param resource the resource * @param info the new resource sync info @@ -1523,10 +1523,10 @@ public class EclipseSynchronizer implements IFlushOperation { } protected String getDirtyIndicator(IResource resource) throws CVSException { - // Do a check outside the lock for the dirty indicator - String indicator = getSyncInfoCacheFor(resource).getDirtyIndicator(resource, false /* not thread safe */); - if (indicator != null) - return indicator; + // Do a check outside the lock for the dirty indicator + String indicator = getSyncInfoCacheFor(resource).getDirtyIndicator(resource, false /* not thread safe */); + if (indicator != null) + return indicator; try { beginOperation(); return getSyncInfoCacheFor(resource).getDirtyIndicator(resource, true); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFile.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFile.java index 3a9b0e33f..f1521f44c 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFile.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFile.java @@ -40,23 +40,23 @@ import org.eclipse.team.internal.ccvs.core.syncinfo.*; * use by the repository and sync view. */ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { - /* - * Listener for accumulating the entries fetched using the "cvs log" command - */ + /* + * Listener for accumulating the entries fetched using the "cvs log" command + */ private final class LogEntryListener implements ILogEntryListener { - private final List<ILogEntry> entries = new ArrayList<>(); - @Override + private final List<ILogEntry> entries = new ArrayList<>(); + @Override public void handleLogEntryReceived(ILogEntry entry) { - if (entry.getRemoteFile().getRepositoryRelativePath().equals(getRepositoryRelativePath())) { - entries.add(entry); - } - } - public ILogEntry[] getEntries() { - return entries.toArray(new ILogEntry[entries.size()]); - } - } + if (entry.getRemoteFile().getRepositoryRelativePath().equals(getRepositoryRelativePath())) { + entries.add(entry); + } + } + public ILogEntry[] getEntries() { + return entries.toArray(new ILogEntry[entries.size()]); + } + } - // sync info in byte form + // sync info in byte form private byte[] syncBytes; // cache the log entry for the remote file private ILogEntry entry; @@ -204,7 +204,7 @@ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { private void internalFetchContents(IProgressMonitor monitor) throws CVSException { monitor.beginTask(CVSMessages.RemoteFile_getContents, 100); - monitor.subTask(CVSMessages.RemoteFile_getContents); + monitor.subTask(CVSMessages.RemoteFile_getContents); if (getRevision().equals(ResourceSyncInfo.ADDED_REVISION)) { // The revision of the remote file is not known so we need to use the tag to get the status of the file CVSTag tag = getSyncInfo().getTag(); @@ -242,7 +242,7 @@ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { session.open(Policy.subMonitorFor(monitor, 10), false /* read-only */); try { try { - LogEntryListener listener = new LogEntryListener(); + LogEntryListener listener = new LogEntryListener(); IStatus status = Command.LOG.execute( session, Command.NO_GLOBAL_OPTIONS, @@ -423,7 +423,7 @@ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { @Override public void setReadOnly(boolean readOnly) { // RemoteFiles are always read only - } + } @Override public boolean isReadOnly() { @@ -465,7 +465,7 @@ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { * * The revision of the remote file is used as the base for the tagging operation */ - @Override + @Override public IStatus tag(final CVSTag tag, final LocalOption[] localOptions, IProgressMonitor monitor) throws CVSException { monitor = Policy.monitorFor(monitor); monitor.beginTask(null, 100); @@ -483,7 +483,7 @@ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { } finally { session.close(); } - } + } @Override public boolean equals(Object target) { @@ -602,7 +602,7 @@ public class RemoteFile extends RemoteResource implements ICVSRemoteFile { * @throws TeamException */ public void setContents(IFile file, IProgressMonitor monitor) throws TeamException, CoreException { - setContents(file.getContents(), monitor); + setContents(file.getContents(), monitor); } @Override diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolder.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolder.java index 567c90813..8b5770dc4 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolder.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolder.java @@ -412,9 +412,9 @@ public class RemoteFolder extends RemoteResource implements ICVSRemoteFolder, IC * @see ICVSRemoteFolder#setTag(String) */ public void setTag(CVSTag tag) { - MutableFolderSyncInfo newInfo = folderInfo.cloneMutable(); - newInfo.setTag(tag); - setFolderSyncInfo(newInfo); + MutableFolderSyncInfo newInfo = folderInfo.cloneMutable(); + newInfo.setTag(tag); + setFolderSyncInfo(newInfo); } @Override @@ -451,8 +451,8 @@ public class RemoteFolder extends RemoteResource implements ICVSRemoteFolder, IC } finally { session.close(); } - } - + } + @Override public ICVSResource[] fetchChildren(IProgressMonitor monitor) throws CVSException { try { diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderMemberFetcher.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderMemberFetcher.java index d6d297ffc..b2bf01607 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderMemberFetcher.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderMemberFetcher.java @@ -175,10 +175,10 @@ public class RemoteFolderMemberFetcher implements IUpdateMessageListener, IStatu try { IPath path = this.parentFolder.getRelativePathFromRootRelativePath(commandRoot, new Path(null, stringPath)); if (path.segmentCount() == 1) { - String pathName = path.lastSegment(); - if (!pathName.equals(".")) { //$NON-NLS-1$ - recordFolder(path.lastSegment()); - } + String pathName = path.lastSegment(); + if (!pathName.equals(".")) { //$NON-NLS-1$ + recordFolder(path.lastSegment()); + } } } catch (CVSException e) { exceptions.add(e); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderTreeBuilder.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderTreeBuilder.java index 4c2f3a2ae..6ff79882a 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderTreeBuilder.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteFolderTreeBuilder.java @@ -126,7 +126,7 @@ public class RemoteFolderTreeBuilder { IProgressMonitor subProgress = Policy.infiniteSubMonitorFor(progress, 100); subProgress.beginTask(null, 512); subProgress.subTask(NLS.bind(CVSMessages.RemoteFolderTreeBuilder_buildingBase, new String[] { root.getName() })); - return builder.buildBaseTree(null, root, subProgress); + return builder.buildBaseTree(null, root, subProgress); } finally { progress.done(); } @@ -138,11 +138,11 @@ public class RemoteFolderTreeBuilder { public static RemoteFolderTree buildRemoteTree(CVSRepositoryLocation repository, ICVSFolder root, CVSTag tag, IProgressMonitor monitor) throws CVSException { RemoteFolderTreeBuilder builder = new RemoteFolderTreeBuilder(repository, root, tag); - return builder.buildTree(new ICVSResource[] { root }, monitor); + return builder.buildTree(new ICVSResource[] { root }, monitor); } public static RemoteFile buildRemoteTree(CVSRepositoryLocation repository, ICVSFile file, CVSTag tag, IProgressMonitor monitor) throws CVSException { RemoteFolderTreeBuilder builder = new RemoteFolderTreeBuilder(repository, file.getParent(), tag); - return builder.buildTree(file, monitor); + return builder.buildTree(file, monitor); } /* package */ RemoteFolderTree buildTree(ICVSResource[] resources, IProgressMonitor monitor) throws CVSException { @@ -215,24 +215,24 @@ public class RemoteFolderTreeBuilder { Session session; FolderSyncInfo folderSyncInfo = root.getFolderSyncInfo(); if (folderSyncInfo == null) { - // We've lost the mapping in the local workspace. - // This could be due to the project being deleted. - if (root.exists()) { - IResource resource = root.getIResource(); - String path; - if (resource == null) { - path = root.getName(); - } else { - path = resource.getFullPath().toString(); - } - IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.ERROR, NLS.bind(CVSMessages.RemoteFolderTreeBuilder_0, new String[] { path }), root); - throw new CVSException(status); - } else { - // Just return. The remote tree will be null - return; - } + // We've lost the mapping in the local workspace. + // This could be due to the project being deleted. + if (root.exists()) { + IResource resource = root.getIResource(); + String path; + if (resource == null) { + path = root.getName(); + } else { + path = resource.getFullPath().toString(); + } + IStatus status = new CVSStatus(IStatus.ERROR, CVSStatus.ERROR, NLS.bind(CVSMessages.RemoteFolderTreeBuilder_0, new String[] { path }), root); + throw new CVSException(status); + } else { + // Just return. The remote tree will be null + return; + } } - remoteRoot = + remoteRoot = new RemoteFolderTree(null, root.getName(), repository, folderSyncInfo.getRepository(), tagForRemoteFolder(root, tag)); @@ -374,7 +374,7 @@ public class RemoteFolderTreeBuilder { // Create a remote folder tree corresponding to the local resource FolderSyncInfo folderSyncInfo = local.getFolderSyncInfo(); if (folderSyncInfo == null) return null; - RemoteFolder remote = createRemoteFolder(local, parent, folderSyncInfo); + RemoteFolder remote = createRemoteFolder(local, parent, folderSyncInfo); // Create a List to contain the created children List<RemoteResource> children = new ArrayList<>(); @@ -387,7 +387,7 @@ public class RemoteFolderTreeBuilder { monitor.worked(1); RemoteFolder tree = buildBaseTree(remote, folder, monitor); if (tree != null) - children.add(tree); + children.add(tree); } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteModule.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteModule.java index 0877316bb..09935efe9 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteModule.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteModule.java @@ -54,11 +54,11 @@ public class RemoteModule extends RemoteFolder { } } - private static ICVSFolder getRemoteRootFolder(ICVSRepositoryLocation repository) { - return new RemoteFolder(null, repository, "/", null); //$NON-NLS-1$ - } + private static ICVSFolder getRemoteRootFolder(ICVSRepositoryLocation repository) { + return new RemoteFolder(null, repository, "/", null); //$NON-NLS-1$ + } - /** + /** * Create a set of RemoteModules from the provided module definition strings returned from the server * * At the moment, we are very restrictive on the types of modules we support. @@ -191,7 +191,7 @@ public class RemoteModule extends RemoteFolder { // XXX Unsupported for now expandable = false; } else { - referencedFolders.add(child); + referencedFolders.add(child); } } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteResource.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteResource.java index 33e526700..0af77ed00 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteResource.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/RemoteResource.java @@ -62,13 +62,13 @@ public abstract class RemoteResource extends CachedResourceVariant implements IC public abstract ICVSRepositoryLocation getRepository(); - public int getWorkspaceSyncState() { - return workspaceSyncState; - } - - public void setWorkspaceSyncState(int workspaceSyncState) { - this.workspaceSyncState = workspaceSyncState; - } + public int getWorkspaceSyncState() { + return workspaceSyncState; + } + + public void setWorkspaceSyncState(int workspaceSyncState) { + this.workspaceSyncState = workspaceSyncState; + } public void delete() { // For now, do nothing but we could provide this in the future. @@ -92,7 +92,7 @@ public abstract class RemoteResource extends CachedResourceVariant implements IC public ICVSFolder getParent() { return parent; - } + } public boolean isIgnored() { return false; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SessionPropertySyncInfoCache.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SessionPropertySyncInfoCache.java index 0c09bafc6..3ec9dc795 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SessionPropertySyncInfoCache.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SessionPropertySyncInfoCache.java @@ -82,10 +82,10 @@ import org.eclipse.team.internal.ccvs.core.util.SyncFileWriter; } return matcher; } - - /* package */ boolean isIgnoresCached(IContainer container) throws CVSException { - return safeGetSessionProperty(container, IGNORE_SYNC_KEY) != null; - } + + /* package */ boolean isIgnoresCached(IContainer container) throws CVSException { + return safeGetSessionProperty(container, IGNORE_SYNC_KEY) != null; + } /*package*/ boolean isFolderSyncInfoCached(IContainer container) throws CVSException { Object info = safeGetSessionProperty(container, FOLDER_SYNC_KEY); @@ -115,9 +115,9 @@ import org.eclipse.team.internal.ccvs.core.util.SyncFileWriter; */ FolderSyncInfo getCachedFolderSync(IContainer container, boolean threadSafeAccess) throws CVSException { FolderSyncInfo info = (FolderSyncInfo)safeGetSessionProperty(container, FOLDER_SYNC_KEY); - // If we are not thread safe, just return whatever was found in the session property - if (!threadSafeAccess) - return info == NULL_FOLDER_SYNC_INFO ? null : info; + // If we are not thread safe, just return whatever was found in the session property + if (!threadSafeAccess) + return info == NULL_FOLDER_SYNC_INFO ? null : info; if (info == null) { // Defer to the synchronizer in case the folder was recreated info = synchronizerCache.getCachedFolderSync(container, true); @@ -258,10 +258,10 @@ import org.eclipse.team.internal.ccvs.core.util.SyncFileWriter; } else { di = RECOMPUTE_INDICATOR; } - // Only set the session property if we are thread safe - if (threadSafeAccess) { - setDirtyIndicator(container, di); - } + // Only set the session property if we are thread safe + if (threadSafeAccess) { + setDirtyIndicator(container, di); + } } return di; } catch (CoreException e) { @@ -306,8 +306,8 @@ import org.eclipse.team.internal.ccvs.core.util.SyncFileWriter; byte[] getCachedSyncBytes(IResource resource, boolean threadSafeAccess) throws CVSException { byte[] bytes = (byte[])safeGetSessionProperty(resource, RESOURCE_SYNC_KEY); // If we are not thread safe, just return whatever was found in the session property - if (!threadSafeAccess) - return bytes; + if (!threadSafeAccess) + return bytes; if (bytes == null) { // Defer to the synchronizer in case the file was recreated bytes = synchronizerCache.getCachedSyncBytes(resource, true); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SyncInfoCache.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SyncInfoCache.java index 75077dfe5..2dcbbb1e2 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SyncInfoCache.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/SyncInfoCache.java @@ -54,7 +54,7 @@ import org.eclipse.team.internal.ccvs.core.syncinfo.FolderSyncInfo; * holds a scheduling rule that encompasses the resource and the workspace is * open for modification. * @param container the container - * @param threadSafeAccess if false, the return value can only be used if not null + * @param threadSafeAccess if false, the return value can only be used if not null * @param canModifyWorkspace indicates if it is OK to modify the ISycnrhonizer * * @return the folder sync info for the folder, or null if none. diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/UpdateContentCachingService.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/UpdateContentCachingService.java index 18280a3d2..c062b6a19 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/UpdateContentCachingService.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/resources/UpdateContentCachingService.java @@ -97,10 +97,10 @@ public class UpdateContentCachingService implements IUpdateMessageListener { // Handle execute try { if (executable) mFile.setExecutable(true); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } } } @@ -164,14 +164,14 @@ public class UpdateContentCachingService implements IUpdateMessageListener { IProgressMonitor subProgress = Policy.infiniteSubMonitorFor(progress, 100); subProgress.beginTask(null, 512); subProgress.subTask(NLS.bind(CVSMessages.RemoteFolderTreeBuilder_buildingBase, new String[] { root.getName() })); - RemoteFolder tree = builder.buildBaseTree(null, root, subProgress); - if (tree == null) { - // The local tree is empty and was pruned. - // Return the root folder so that the operation can proceed - FolderSyncInfo folderSyncInfo = root.getFolderSyncInfo(); - if (folderSyncInfo == null) return null; - return new RemoteFolderSandbox(null, root.getName(), repository, folderSyncInfo.getRepository(), folderSyncInfo.getTag(), folderSyncInfo.getIsStatic()); - } + RemoteFolder tree = builder.buildBaseTree(null, root, subProgress); + if (tree == null) { + // The local tree is empty and was pruned. + // Return the root folder so that the operation can proceed + FolderSyncInfo folderSyncInfo = root.getFolderSyncInfo(); + if (folderSyncInfo == null) return null; + return new RemoteFolderSandbox(null, root.getName(), repository, folderSyncInfo.getRepository(), folderSyncInfo.getTag(), folderSyncInfo.getIsStatic()); + } return tree; } finally { progress.done(); @@ -250,8 +250,8 @@ public class UpdateContentCachingService implements IUpdateMessageListener { private boolean isReportableError(IStatus status) { return CVSStatus.isInternalError(status) || status.getCode() == TeamException.UNABLE - || status.getCode() == CVSStatus.INVALID_LOCAL_RESOURCE_PATH - || status.getCode() == CVSStatus.RESPONSE_HANDLING_FAILURE; + || status.getCode() == CVSStatus.INVALID_LOCAL_RESOURCE_PATH + || status.getCode() == CVSStatus.RESPONSE_HANDLING_FAILURE; } private LocalOption[] getLocalOptions() { diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/CVSResourceVariantTree.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/CVSResourceVariantTree.java index 6b8ad8fec..d15e2158c 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/CVSResourceVariantTree.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/CVSResourceVariantTree.java @@ -160,9 +160,9 @@ public class CVSResourceVariantTree extends ResourceVariantTree { bytes = null; } else { // Use the folder sync from the workspace and the tag from the store - MutableFolderSyncInfo newInfo = info.cloneMutable(); - newInfo.setTag(tag); - newInfo.setStatic(false); + MutableFolderSyncInfo newInfo = info.cloneMutable(); + newInfo.setTag(tag); + newInfo.setStatic(false); bytes = newInfo.getBytes(); } return bytes; @@ -206,42 +206,42 @@ public class CVSResourceVariantTree extends ResourceVariantTree { e); throw new CVSException(status); } - MutableFolderSyncInfo newInfo = info.cloneMutable(); - newInfo.setTag(tag); + MutableFolderSyncInfo newInfo = info.cloneMutable(); + newInfo.setTag(tag); ICVSFolder cvsFolder = CVSWorkspaceRoot.getCVSFolderFor((IFolder)local); cvsFolder.setFolderSyncInfo(newInfo); } - if (remote == null && !isManaged(local)) { - // Do not record the lack of existence of a remote for unmanaged local files - // Instead, just flush the remote bytes if there are any - boolean changed = getByteStore().getBytes(local) != null; - flushVariants(local, IResource.DEPTH_ZERO); - return changed; - } else { - boolean changed = super.setVariant(local, remote); - if (local.getType() == IResource.FILE && getByteStore().getBytes(local) != null && !parentHasSyncBytes(local)) { - // Log a warning if there is no sync bytes available for the resource's - // parent but there is valid sync bytes for the child - CVSProviderPlugin.log(new TeamException(NLS.bind(CVSMessages.ResourceSynchronizer_missingParentBytesOnSet, new String[] { getSyncName(getByteStore()), local.getFullPath().toString() }))); - } - return changed; - } + if (remote == null && !isManaged(local)) { + // Do not record the lack of existence of a remote for unmanaged local files + // Instead, just flush the remote bytes if there are any + boolean changed = getByteStore().getBytes(local) != null; + flushVariants(local, IResource.DEPTH_ZERO); + return changed; + } else { + boolean changed = super.setVariant(local, remote); + if (local.getType() == IResource.FILE && getByteStore().getBytes(local) != null && !parentHasSyncBytes(local)) { + // Log a warning if there is no sync bytes available for the resource's + // parent but there is valid sync bytes for the child + CVSProviderPlugin.log(new TeamException(NLS.bind(CVSMessages.ResourceSynchronizer_missingParentBytesOnSet, new String[] { getSyncName(getByteStore()), local.getFullPath().toString() }))); + } + return changed; + } } private boolean isManaged(IResource local) { - try { - return CVSWorkspaceRoot.getCVSResourceFor(local).isManaged(); - } catch (CVSException e) { - return false; - } - } + try { + return CVSWorkspaceRoot.getCVSResourceFor(local).isManaged(); + } catch (CVSException e) { + return false; + } + } - private boolean parentHasSyncBytes(IResource resource) throws TeamException { + private boolean parentHasSyncBytes(IResource resource) throws TeamException { if (resource.getType() == IResource.PROJECT) return true; return getParentBytes(resource) != null; } - @Override + @Override protected IResource[] collectedMembers(IResource local, IResource[] members) throws TeamException { // Look for resources that have sync bytes but are not in the resources we care about IResource[] resources = getStoredMembers(local); @@ -307,17 +307,17 @@ public class CVSResourceVariantTree extends ResourceVariantTree { } count++; if (count >= 10) { - waitTime = 1000; + waitTime = 1000; } else if (count >= 5) { - waitTime = 100; + waitTime = 100; } Policy.checkCanceled(monitor); } try { changedResources = super.refresh(resource, depth, Policy.subMonitorFor(monitor, 99)); } catch (TeamException e) { - // Try to properly handle exceptions that are due to project modifications - // performed while the refresh was happening + // Try to properly handle exceptions that are due to project modifications + // performed while the refresh was happening if (!resource.getProject().isAccessible()) { // The project is closed so silently skip it return new IResource[0]; diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/DeferredResourceChangeHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/DeferredResourceChangeHandler.java index f0fe8866d..94c96483a 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/DeferredResourceChangeHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/DeferredResourceChangeHandler.java @@ -87,11 +87,11 @@ public class DeferredResourceChangeHandler extends BackgroundEventHandler { // Handle ignore file changes boolean workDone = !changedIgnoreFiles.isEmpty() || !recreatedResources.isEmpty(); try { - EclipseSynchronizer.getInstance().ignoreFilesChanged(getParents(changedIgnoreFiles)); - } catch (CVSException e) { - // Log and continue - CVSProviderPlugin.log(e); - } + EclipseSynchronizer.getInstance().ignoreFilesChanged(getParents(changedIgnoreFiles)); + } catch (CVSException e) { + // Log and continue + CVSProviderPlugin.log(e); + } changedIgnoreFiles.clear(); // Handle recreations by project to reduce locking granularity Map recreations = getResourcesByProject((IResource[]) recreatedResources.toArray(new IResource[recreatedResources.size()])); diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/FolderSyncInfo.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/FolderSyncInfo.java index 9cbc96c48..d58011df4 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/FolderSyncInfo.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/FolderSyncInfo.java @@ -39,14 +39,14 @@ public class FolderSyncInfo { protected String repository; // :pserver:user@host:/home/user/repo - protected String root; + protected String root; // sticky tag (e.g. version, date, or branch tag applied to folder) private CVSEntryLineTag tag; // if true then it means only part of the folder was fetched from the repository, and CVS will not create // additional files in that folder. - protected boolean isStatic; + protected boolean isStatic; /** * Construct a folder sync object. @@ -133,17 +133,17 @@ public class FolderSyncInfo { // If the username is missing, we have to find the third ':'. index = root.indexOf(CVSRepositoryLocation.COLON); if (index == 0) { - // This indicates that the conection method is present. - // It is surrounded by two colons so skip them. + // This indicates that the conection method is present. + // It is surrounded by two colons so skip them. index = root.indexOf(CVSRepositoryLocation.COLON, index + 1); index = root.indexOf(CVSRepositoryLocation.COLON, index + 1); } if (index == -1) { - // The host colon is missing. - // Look for a slash to find the path - index = root.indexOf(ResourceSyncInfo.SEPARATOR); - // Decrement the index since the slash is part of the path - if (index != -1) index--; + // The host colon is missing. + // Look for a slash to find the path + index = root.indexOf(ResourceSyncInfo.SEPARATOR); + // Decrement the index since the slash is part of the path + if (index != -1) index--; } } else { // If the username was there, we find the first ':' past the '@' @@ -323,7 +323,7 @@ public class FolderSyncInfo { return getRepository().equals(VIRTUAL_DIRECTORY); } - public FolderSyncInfo asImmutable() { - return this; - } + public FolderSyncInfo asImmutable() { + return this; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/MutableFolderSyncInfo.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/MutableFolderSyncInfo.java index e249a329a..a2939d737 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/MutableFolderSyncInfo.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/MutableFolderSyncInfo.java @@ -47,15 +47,15 @@ public class MutableFolderSyncInfo extends FolderSyncInfo { this.repository = repository; } - public void setStatic(boolean isStatic) { - this.isStatic = isStatic; - } - - public FolderSyncInfo asImmutable() { - return new FolderSyncInfo(getRepository(), getRoot(), getTag(), getIsStatic()); - } + public void setStatic(boolean isStatic) { + this.isStatic = isStatic; + } + + public FolderSyncInfo asImmutable() { + return new FolderSyncInfo(getRepository(), getRoot(), getTag(), getIsStatic()); + } - public void setRoot(String root) { - this.root = root; - } + public void setRoot(String root) { + this.root = root; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/ReentrantLock.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/ReentrantLock.java index 1cf5b283e..24e6bddc2 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/ReentrantLock.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/syncinfo/ReentrantLock.java @@ -63,10 +63,10 @@ public class ReentrantLock extends BatchingLock { } @Override - protected ThreadInfo createThreadInfo(IFlushOperation operation) { - return new CVSThreadInfo(operation); - } - + protected ThreadInfo createThreadInfo(IFlushOperation operation) { + return new CVSThreadInfo(operation); + } + public void folderChanged(IContainer folder) { CVSThreadInfo info = (CVSThreadInfo)getThreadInfo(); Assert.isNotNull(info, "Folder changed outside of resource lock"); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java index f578bbeed..3a3adc6e6 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java @@ -80,8 +80,8 @@ public class CVSDateFormatter { * Timezone string is of the following format: [-|+]MMSS */ static private TimeZone getTimeZone(String dateFromServer) { - if (dateFromServer.lastIndexOf("0000") != -1) //$NON-NLS-1$ - return TimeZone.getTimeZone("GMT");//$NON-NLS-1$ + if (dateFromServer.lastIndexOf("0000") != -1) //$NON-NLS-1$ + return TimeZone.getTimeZone("GMT");//$NON-NLS-1$ String tz = null; StringBuffer resultTz = new StringBuffer("GMT");//$NON-NLS-1$ if (dateFromServer.indexOf("-") != -1) {//$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/ResponsiveSocketFactory.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/ResponsiveSocketFactory.java index c5f4a169d..3b9a11d28 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/ResponsiveSocketFactory.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/ResponsiveSocketFactory.java @@ -26,156 +26,156 @@ import org.eclipse.team.internal.ccvs.core.*; * Class copied from "org.eclipse.jsch.internal.core" */ public class ResponsiveSocketFactory { - private static final String JAVA_NET_PROXY="java.net.Proxy"; //$NON-NLS-1$ - private static final int DEFAULT_TIMEOUT=60; // Seconds - private IProgressMonitor monitor; - private final int timeout; - private static Class proxyClass; - private static boolean hasProxyClass = true; - public ResponsiveSocketFactory(IProgressMonitor monitor, int timeout) { - if (monitor == null) - monitor = new NullProgressMonitor(); - this.monitor = monitor; - this.timeout=timeout; - } - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - Socket socket = null; - socket = createSocket(host, port, timeout / 1000, monitor); - // Null out the monitor so we don't hold onto anything - // (i.e. the SSH2 session will keep a handle to the socket factory around - monitor = new NullProgressMonitor(); - // Set the socket timeout - socket.setSoTimeout(timeout); - return socket; - } - - /** - * Helper method that will time out when making a socket connection. - * This is required because there is no way to provide a timeout value - * when creating a socket and in some instances, they don't seem to - * timeout at all. - */ - private Socket createSocket(final String host, final int port, int timeout, IProgressMonitor monitor) throws UnknownHostException, IOException { - - // Start a thread to open a socket - final Socket[] socket = new Socket[] { null }; - final Exception[] exception = new Exception[] {null }; - final Thread thread = new Thread(() -> { - try { - Socket newSocket = internalCreateSocket(host, port); - synchronized (socket) { - if (Thread.interrupted()) { - // we we're either canceled or timed out so just close the socket - newSocket.close(); - } else { - socket[0] = newSocket; - } - } - } catch (UnknownHostException e1) { - exception[0] = e1; - } catch (IOException e2) { - exception[0] = e2; - } - }); - thread.start(); - - // Wait the appropriate number of seconds - if (timeout == 0) timeout = DEFAULT_TIMEOUT; - for (int i = 0; i < timeout; i++) { - try { - // wait for the thread to complete or 1 second, which ever comes first - thread.join(1000); - } catch (InterruptedException e) { - // I think this means the thread was interrupted but not necessarily timed out - // so we don't need to do anything - } - synchronized (socket) { - // if the user canceled, clean up before preempting the operation - if (monitor.isCanceled()) { - if (thread.isAlive()) { - thread.interrupt(); - } - if (socket[0] != null) { - socket[0].close(); - } - // this method will throw the proper exception - Policy.checkCanceled(monitor); - } - } - } - // If the thread is still running (i.e. we timed out) signal that it is too late - synchronized (socket) { - if (thread.isAlive()) { - thread.interrupt(); - } - } - if (exception[0] != null) { - if (exception[0] instanceof UnknownHostException) - throw (UnknownHostException)exception[0]; - else - throw (IOException)exception[0]; - } - if (socket[0] == null) { - throw new InterruptedIOException(NLS.bind(CVSMessages.Util_timeout, new String[] { host })); - } - return socket[0]; - } - - /* private */ Socket internalCreateSocket(final String host, final int port) - throws UnknownHostException, IOException{ - Class proxyClass = getProxyClass(); - if (proxyClass != null) { - // We need to disable proxy support for the socket - try{ - - // Obtain the value of the NO_PROXY static field of the proxy class - Field field = proxyClass.getField("NO_PROXY"); //$NON-NLS-1$ - Object noProxyObject = field.get(null); - Constructor constructor = Socket.class.getConstructor(new Class[] { proxyClass }); - Object o = constructor.newInstance(new Object[] { noProxyObject }); - if(o instanceof Socket){ - Socket socket=(Socket)o; - socket.connect(new InetSocketAddress(host, port), timeout * 1000); - return socket; - } - } - catch(SecurityException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - catch(NoSuchFieldException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - catch(IllegalArgumentException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - catch(IllegalAccessException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - catch(NoSuchMethodException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - catch(InstantiationException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - catch(InvocationTargetException e){ - CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ - } - - } - return new Socket(host, port); - } - - private synchronized Class getProxyClass() { - if (hasProxyClass && proxyClass == null) { - try{ - proxyClass = Class.forName(JAVA_NET_PROXY); - } - catch(ClassNotFoundException e){ - // We couldn't find the class so we'll assume we are using pre-1.5 JRE - hasProxyClass = false; - } - } - return proxyClass; - } + private static final String JAVA_NET_PROXY="java.net.Proxy"; //$NON-NLS-1$ + private static final int DEFAULT_TIMEOUT=60; // Seconds + private IProgressMonitor monitor; + private final int timeout; + private static Class proxyClass; + private static boolean hasProxyClass = true; + public ResponsiveSocketFactory(IProgressMonitor monitor, int timeout) { + if (monitor == null) + monitor = new NullProgressMonitor(); + this.monitor = monitor; + this.timeout=timeout; + } + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + Socket socket = null; + socket = createSocket(host, port, timeout / 1000, monitor); + // Null out the monitor so we don't hold onto anything + // (i.e. the SSH2 session will keep a handle to the socket factory around + monitor = new NullProgressMonitor(); + // Set the socket timeout + socket.setSoTimeout(timeout); + return socket; + } + + /** + * Helper method that will time out when making a socket connection. + * This is required because there is no way to provide a timeout value + * when creating a socket and in some instances, they don't seem to + * timeout at all. + */ + private Socket createSocket(final String host, final int port, int timeout, IProgressMonitor monitor) throws UnknownHostException, IOException { + + // Start a thread to open a socket + final Socket[] socket = new Socket[] { null }; + final Exception[] exception = new Exception[] {null }; + final Thread thread = new Thread(() -> { + try { + Socket newSocket = internalCreateSocket(host, port); + synchronized (socket) { + if (Thread.interrupted()) { + // we we're either canceled or timed out so just close the socket + newSocket.close(); + } else { + socket[0] = newSocket; + } + } + } catch (UnknownHostException e1) { + exception[0] = e1; + } catch (IOException e2) { + exception[0] = e2; + } + }); + thread.start(); + + // Wait the appropriate number of seconds + if (timeout == 0) timeout = DEFAULT_TIMEOUT; + for (int i = 0; i < timeout; i++) { + try { + // wait for the thread to complete or 1 second, which ever comes first + thread.join(1000); + } catch (InterruptedException e) { + // I think this means the thread was interrupted but not necessarily timed out + // so we don't need to do anything + } + synchronized (socket) { + // if the user canceled, clean up before preempting the operation + if (monitor.isCanceled()) { + if (thread.isAlive()) { + thread.interrupt(); + } + if (socket[0] != null) { + socket[0].close(); + } + // this method will throw the proper exception + Policy.checkCanceled(monitor); + } + } + } + // If the thread is still running (i.e. we timed out) signal that it is too late + synchronized (socket) { + if (thread.isAlive()) { + thread.interrupt(); + } + } + if (exception[0] != null) { + if (exception[0] instanceof UnknownHostException) + throw (UnknownHostException)exception[0]; + else + throw (IOException)exception[0]; + } + if (socket[0] == null) { + throw new InterruptedIOException(NLS.bind(CVSMessages.Util_timeout, new String[] { host })); + } + return socket[0]; + } + + /* private */ Socket internalCreateSocket(final String host, final int port) + throws UnknownHostException, IOException{ + Class proxyClass = getProxyClass(); + if (proxyClass != null) { + // We need to disable proxy support for the socket + try{ + + // Obtain the value of the NO_PROXY static field of the proxy class + Field field = proxyClass.getField("NO_PROXY"); //$NON-NLS-1$ + Object noProxyObject = field.get(null); + Constructor constructor = Socket.class.getConstructor(new Class[] { proxyClass }); + Object o = constructor.newInstance(new Object[] { noProxyObject }); + if(o instanceof Socket){ + Socket socket=(Socket)o; + socket.connect(new InetSocketAddress(host, port), timeout * 1000); + return socket; + } + } + catch(SecurityException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + catch(NoSuchFieldException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + catch(IllegalArgumentException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + catch(IllegalAccessException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + catch(NoSuchMethodException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + catch(InstantiationException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + catch(InvocationTargetException e){ + CVSProviderPlugin.log(IStatus.ERROR, NLS.bind("An internal error occurred while connecting to {0}", host), e); //$NON-NLS-1$ + } + + } + return new Socket(host, port); + } + + private synchronized Class getProxyClass() { + if (hasProxyClass && proxyClass == null) { + try{ + proxyClass = Class.forName(JAVA_NET_PROXY); + } + catch(ClassNotFoundException e){ + // We couldn't find the class so we'll assume we are using pre-1.5 JRE + hasProxyClass = false; + } + } + return proxyClass; + } } diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileChangeListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileChangeListener.java index d589cf7ce..c04708776 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileChangeListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileChangeListener.java @@ -245,9 +245,9 @@ public class SyncFileChangeListener implements IResourceChangeListener { protected boolean isMetaFile(IResource resource) { IContainer parent = resource.getParent(); return resource.getType() == IResource.FILE && - parent!=null && - parent.getName().equals(SyncFileWriter.CVS_DIRNAME) && - (parent.isTeamPrivateMember() || !parent.exists()); + parent!=null && + parent.getName().equals(SyncFileWriter.CVS_DIRNAME) && + (parent.isTeamPrivateMember() || !parent.exists()); } /* diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileWriter.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileWriter.java index ac943f1fb..b63bf4a2e 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileWriter.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/SyncFileWriter.java @@ -70,12 +70,12 @@ public class SyncFileWriter { * If the folder does not have a CVS subdirectory then <code>null</code> is returned. */ public static byte[][] readAllResourceSync(IContainer parent) throws CVSException { - IFolder cvsSubDir = getCVSSubdirectory(parent); - - if (!folderExists(cvsSubDir)){ - return null; - } - + IFolder cvsSubDir = getCVSSubdirectory(parent); + + if (!folderExists(cvsSubDir)){ + return null; + } + if (Policy.DEBUG_METAFILE_CHANGES) { System.out.println("Reading Entries file for " + parent.getFullPath()); //$NON-NLS-1$ } @@ -126,14 +126,14 @@ public class SyncFileWriter { } private static boolean folderExists(IFolder cvsSubDir) throws CVSException { - try { - URI uri = cvsSubDir.getLocationURI(); - if (uri != null){ + try { + URI uri = cvsSubDir.getLocationURI(); + if (uri != null){ IFileStore store = EFS.getStore(uri); if (store != null){ return store.fetchInfo().exists(); } - } + } } catch (CoreException e) { throw CVSException.wrapException(e); } @@ -171,11 +171,11 @@ public class SyncFileWriter { public static FolderSyncInfo readFolderSync(IContainer folder) throws CVSException { IFolder cvsSubDir = getCVSSubdirectory(folder); - if (!folderExists(cvsSubDir)){ - return null; - } + if (!folderExists(cvsSubDir)){ + return null; + } - if (Policy.DEBUG_METAFILE_CHANGES) { + if (Policy.DEBUG_METAFILE_CHANGES) { System.out.println("Reading Root/Repository files for " + folder.getFullPath()); //$NON-NLS-1$ } @@ -328,10 +328,10 @@ public class SyncFileWriter { public static NotifyInfo[] readAllNotifyInfo(IContainer parent) throws CVSException { IFolder cvsSubDir = getCVSSubdirectory(parent); - if (!folderExists(cvsSubDir)){ - return null; - } - + if (!folderExists(cvsSubDir)){ + return null; + } + // process Notify file contents String[] entries = readLines(cvsSubDir.getFile(NOTIFY)); if (entries == null) return null; @@ -340,13 +340,13 @@ public class SyncFileWriter { String line = entries[i]; if(!"".equals(line)) { //$NON-NLS-1$ try { - NotifyInfo info = new NotifyInfo(parent, line); - infos.put(info.getName(), info); - } catch (CVSException e) { - // We couldn't parse the notify info - // Log it and ignore - CVSProviderPlugin.log(e); - } + NotifyInfo info = new NotifyInfo(parent, line); + infos.put(info.getName(), info); + } catch (CVSException e) { + // We couldn't parse the notify info + // Log it and ignore + CVSProviderPlugin.log(e); + } } } @@ -393,11 +393,11 @@ public class SyncFileWriter { */ public static BaserevInfo[] readAllBaserevInfo(IContainer parent) throws CVSException { IFolder cvsSubDir = getCVSSubdirectory(parent); - - if (!folderExists(cvsSubDir)){ - return null; - } - + + if (!folderExists(cvsSubDir)){ + return null; + } + // process Notify file contents String[] entries = readLines(cvsSubDir.getFile(BASEREV)); if (entries == null) return null; @@ -504,8 +504,8 @@ public class SyncFileWriter { } finally { reader.close(); } - } - return null; + } + return null; } catch (IOException e) { throw CVSException.wrapException(e); } catch (CoreException e) { @@ -524,7 +524,7 @@ public class SyncFileWriter { private static InputStream getInputStream(IFile file) throws CoreException, FileNotFoundException { if (file.exists()) { - return file.getContents(true); + return file.getContents(true); } URI uri = file.getLocationURI(); @@ -692,11 +692,11 @@ public class SyncFileWriter { if (attrs != null && attrs.isReadOnly() != readOnly) { attrs.setReadOnly(readOnly); try { - source.setResourceAttributes(attrs); - } catch (CoreException e) { - // Just log the failure since the move may succeed anyway - CVSProviderPlugin.log(e); - } + source.setResourceAttributes(attrs); + } catch (CoreException e) { + // Just log the failure since the move may succeed anyway + CVSProviderPlugin.log(e); + } } } diff --git a/bundles/org.eclipse.team.cvs.ssh2/META-INF/MANIFEST.MF b/bundles/org.eclipse.team.cvs.ssh2/META-INF/MANIFEST.MF index d86a618c3..99b67fbb8 100644 --- a/bundles/org.eclipse.team.cvs.ssh2/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.team.cvs.ssh2/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.team.cvs.ssh2; singleton:=true -Bundle-Version: 3.3.300.qualifier +Bundle-Version: 3.3.400.qualifier Bundle-Activator: org.eclipse.team.internal.ccvs.ssh2.CVSSSH2Plugin Bundle-Vendor: %providerName Bundle-Localization: plugin diff --git a/bundles/org.eclipse.team.cvs.ssh2/pom.xml b/bundles/org.eclipse.team.cvs.ssh2/pom.xml index 9ea53c2f3..65da49d81 100644 --- a/bundles/org.eclipse.team.cvs.ssh2/pom.xml +++ b/bundles/org.eclipse.team.cvs.ssh2/pom.xml @@ -19,6 +19,6 @@ </parent> <groupId>org.eclipse.team</groupId> <artifactId>org.eclipse.team.cvs.ssh2</artifactId> - <version>3.3.300-SNAPSHOT</version> + <version>3.3.400-SNAPSHOT</version> <packaging>eclipse-plugin</packaging> </project> diff --git a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2Plugin.java b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2Plugin.java index a31de7776..7bdb66a7b 100644 --- a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2Plugin.java +++ b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2Plugin.java @@ -62,11 +62,11 @@ public class CVSSSH2Plugin extends Plugin { properties.put(DebugOptions.LISTENER_SYMBOLICNAME, ID); debugRegistration = context.registerService(DebugOptionsListener.class, Policy.DEBUG_OPTIONS_LISTENER, properties); - tracker = new ServiceTracker(getBundle().getBundleContext(), IJSchService.class.getName(), null); - tracker.open(); + tracker = new ServiceTracker(getBundle().getBundleContext(), IJSchService.class.getName(), null); + tracker.open(); } - public IJSchService getJSchService() { - return (IJSchService)tracker.getService(); - } + public IJSchService getJSchService() { + return (IJSchService)tracker.getService(); + } } diff --git a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2ServerConnection.java b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2ServerConnection.java index f99e461c5..567f45514 100644 --- a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2ServerConnection.java +++ b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/CVSSSH2ServerConnection.java @@ -45,20 +45,20 @@ public class CVSSSH2ServerConnection implements IServerConnection { private static final String SSH1_COMPATIBILITY_CLASS = "org.eclipse.team.internal.ccvs.ssh.SSHServerConnection"; //$NON-NLS-1$ private final class SSH2IOException extends IOException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final JSchException e; + private final JSchException e; - SSH2IOException(String s, JSchException e) { - super(s); - this.e = e; - } + SSH2IOException(String s, JSchException e) { + super(s); + this.e = e; + } - public Throwable getCause() { - return e; - } - } - private static final String COMMAND = "cvs server"; //$NON-NLS-1$ + public Throwable getCause() { + return e; + } + } + private static final String COMMAND = "cvs server"; //$NON-NLS-1$ private ICVSRepositoryLocation location; private String password; private InputStream inputStream; @@ -130,10 +130,10 @@ public class CVSSSH2ServerConnection implements IServerConnection { try { OutputStream channel_out = null; InputStream channel_in = null; - boolean firstTime = true; - boolean tryAgain = false; + boolean firstTime = true; + boolean tryAgain = false; while (firstTime || tryAgain) { - tryAgain = false; // reset the try again flag + tryAgain = false; // reset the try again flag session = JSchSession.getSession(location, location.getUsername(), password, location.getHost(), location.getPort(), monitor); channel = session.getSession().openChannel("exec"); //$NON-NLS-1$ ((ChannelExec) channel).setCommand(COMMAND); @@ -142,24 +142,24 @@ public class CVSSSH2ServerConnection implements IServerConnection { try { channel.connect(); } catch (JSchException ee) { - // This strange logic is here due to how the JSch client shares sessions. - // It is possible that we have obtained a session that thinks it is connected - // but is not. Channel connection only works if the session is connected so the - // above channel connect may fail because the session is down. For this reason, - // we want to retry if the connection fails. - try { - if (firstTime && (isSessionDownError(ee) || isChannelNotOpenError(ee))) { - tryAgain = true; - } - if (!tryAgain) { - throw ee; - } - } finally { - // Always dispose of the current session when a failure occurs so we can start from scratch - session.dispose(); - } + // This strange logic is here due to how the JSch client shares sessions. + // It is possible that we have obtained a session that thinks it is connected + // but is not. Channel connection only works if the session is connected so the + // above channel connect may fail because the session is down. For this reason, + // we want to retry if the connection fails. + try { + if (firstTime && (isSessionDownError(ee) || isChannelNotOpenError(ee))) { + tryAgain = true; + } + if (!tryAgain) { + throw ee; + } + } finally { + // Always dispose of the current session when a failure occurs so we can start from scratch + session.dispose(); + } } - firstTime = false; // the first time is done + firstTime = false; // the first time is done } int timeout = location.getTimeout(); inputStream = new PollingInputStream(new TimeoutInputStream(new FilterInputStream(channel_in) { @@ -182,31 +182,31 @@ public class CVSSSH2ServerConnection implements IServerConnection { CVSSSH2Messages.CVSSSH2ServerConnection_4, e); } ssh1.open(monitor); - } else { - String message = e.getMessage(); - if (JSchSession.isAuthenticationFailure(e)) { - // Do not retry as the Jsh library has it's own retry logic - throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_0, CVSAuthenticationException.NO_RETRY,location, e); - } else if (message.startsWith("Session.connect: ")) { //$NON-NLS-1$ - // Jsh has messages formatted like "Session.connect: java.net.NoRouteToHostException: ..." - // Strip of the exception and try to convert it to a more meaningfull string - int start = message.indexOf(": ") + 1; //$NON-NLS-1$ - if (start != -1) { - int end = message.indexOf(": ", start); //$NON-NLS-1$ - if (end != -1) { - String exception = message.substring(start, end).trim(); - if (exception.indexOf("NoRouteToHostException") != -1) { //$NON-NLS-1$ - message = NLS.bind(CVSSSH2Messages.CVSSSH2ServerConnection_1, new String[] { location.getHost() }); - throw new NoRouteToHostException(message); - } else if (exception.indexOf("java.net.UnknownHostException") != -1) { //$NON-NLS-1$ - throw new UnknownHostException(location.getHost()); - } else { - message = message.substring(end + 1).trim(); - } - } - } - } - throw new SSH2IOException(message, e); + } else { + String message = e.getMessage(); + if (JSchSession.isAuthenticationFailure(e)) { + // Do not retry as the Jsh library has it's own retry logic + throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_0, CVSAuthenticationException.NO_RETRY,location, e); + } else if (message.startsWith("Session.connect: ")) { //$NON-NLS-1$ + // Jsh has messages formatted like "Session.connect: java.net.NoRouteToHostException: ..." + // Strip of the exception and try to convert it to a more meaningfull string + int start = message.indexOf(": ") + 1; //$NON-NLS-1$ + if (start != -1) { + int end = message.indexOf(": ", start); //$NON-NLS-1$ + if (end != -1) { + String exception = message.substring(start, end).trim(); + if (exception.indexOf("NoRouteToHostException") != -1) { //$NON-NLS-1$ + message = NLS.bind(CVSSSH2Messages.CVSSSH2ServerConnection_1, new String[] { location.getHost() }); + throw new NoRouteToHostException(message); + } else if (exception.indexOf("java.net.UnknownHostException") != -1) { //$NON-NLS-1$ + throw new UnknownHostException(location.getHost()); + } else { + message = message.substring(end + 1).trim(); + } + } + } + } + throw new SSH2IOException(message, e); } } } @@ -247,14 +247,14 @@ public class CVSSSH2ServerConnection implements IServerConnection { } return null; } - - private boolean isChannelNotOpenError(JSchException ee) { - return ee.getMessage().indexOf("channel is not opened") != -1; //$NON-NLS-1$ - } - private boolean isSessionDownError(JSchException ee) { - return ee.getMessage().equals("session is down"); //$NON-NLS-1$ - } - private boolean isSSH2Unsupported(JSchException e) { - return e.toString().indexOf("invalid server's version string") != -1; //$NON-NLS-1$ - } + + private boolean isChannelNotOpenError(JSchException ee) { + return ee.getMessage().indexOf("channel is not opened") != -1; //$NON-NLS-1$ + } + private boolean isSessionDownError(JSchException ee) { + return ee.getMessage().equals("session is down"); //$NON-NLS-1$ + } + private boolean isSSH2Unsupported(JSchException e) { + return e.toString().indexOf("invalid server's version string") != -1; //$NON-NLS-1$ + } } diff --git a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/JSchSession.java b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/JSchSession.java index 3e290148c..3a7b051d9 100644 --- a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/JSchSession.java +++ b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/JSchSession.java @@ -31,24 +31,24 @@ class JSchSession { private static final int SSH_DEFAULT_PORT = 22; private static Hashtable<String, JSchSession> pool = new Hashtable<>(); - private final Session session; - private final ICVSRepositoryLocation location; - - protected static int getCVSTimeoutInMillis() { - //return CVSProviderPlugin.getPlugin().getTimeout() * 1000; - // TODO Hard-code the timeout for now since JSch doesn't respect CVS timeout - // See bug 92887 - return 60000; - } - - public static boolean isAuthenticationFailure(JSchException ee) { - return ee.getMessage().equals("Auth fail"); //$NON-NLS-1$ - } - - static JSchSession getSession(final ICVSRepositoryLocation location, String username, String password, String hostname, int port, IProgressMonitor monitor) throws JSchException { - int actualPort = port; - if (actualPort == ICVSRepositoryLocation.USE_DEFAULT_PORT) - actualPort = getPort(location); + private final Session session; + private final ICVSRepositoryLocation location; + + protected static int getCVSTimeoutInMillis() { + //return CVSProviderPlugin.getPlugin().getTimeout() * 1000; + // TODO Hard-code the timeout for now since JSch doesn't respect CVS timeout + // See bug 92887 + return 60000; + } + + public static boolean isAuthenticationFailure(JSchException ee) { + return ee.getMessage().equals("Auth fail"); //$NON-NLS-1$ + } + + static JSchSession getSession(final ICVSRepositoryLocation location, String username, String password, String hostname, int port, IProgressMonitor monitor) throws JSchException { + int actualPort = port; + if (actualPort == ICVSRepositoryLocation.USE_DEFAULT_PORT) + actualPort = getPort(location); String key = getPoolKey(username, hostname, actualPort); @@ -56,47 +56,47 @@ class JSchSession { JSchSession jschSession = pool.get(key); if (jschSession != null && !jschSession.getSession().isConnected()) { pool.remove(key); - jschSession = null; + jschSession = null; } if (jschSession == null) { - IJSchService service = getJSchService(); - IJSchLocation jlocation=service.getLocation(username, hostname, actualPort); - - // As for the connection method "pserverssh2", - // there is not a place to save the given password for ssh2. - if (!location.getMethod().getName().equals("pserverssh2")) { //$NON-NLS-1$ - IPasswordStore pstore = new IPasswordStore() { - public void clear(IJSchLocation l) { - location.flushUserInfo(); - } - public boolean isCached(IJSchLocation l) { - return location.getUserInfoCached(); - } - public void update(IJSchLocation l) { - location.setPassword(l.getPassword()); - location.setAllowCaching(true); - } - }; - jlocation.setPasswordStore(pstore); - } - jlocation.setComment(NLS.bind(CVSSSH2Messages.JSchSession_3, new String[] {location.toString()})); - - Session session = null; - try { - session = createSession(service, jlocation, password, monitor); - } catch (JSchException e) { - throw e; - } - if (session == null) - throw new JSchException(CVSSSH2Messages.JSchSession_4); - if (session.getTimeout() != location.getTimeout() * 1000) - session.setTimeout(location.getTimeout() * 1000); - JSchSession schSession = new JSchSession(session, location); - pool.put(key, schSession); - return schSession; + IJSchService service = getJSchService(); + IJSchLocation jlocation=service.getLocation(username, hostname, actualPort); + + // As for the connection method "pserverssh2", + // there is not a place to save the given password for ssh2. + if (!location.getMethod().getName().equals("pserverssh2")) { //$NON-NLS-1$ + IPasswordStore pstore = new IPasswordStore() { + public void clear(IJSchLocation l) { + location.flushUserInfo(); + } + public boolean isCached(IJSchLocation l) { + return location.getUserInfoCached(); + } + public void update(IJSchLocation l) { + location.setPassword(l.getPassword()); + location.setAllowCaching(true); + } + }; + jlocation.setPasswordStore(pstore); + } + jlocation.setComment(NLS.bind(CVSSSH2Messages.JSchSession_3, new String[] {location.toString()})); + + Session session = null; + try { + session = createSession(service, jlocation, password, monitor); + } catch (JSchException e) { + throw e; + } + if (session == null) + throw new JSchException(CVSSSH2Messages.JSchSession_4); + if (session.getTimeout() != location.getTimeout() * 1000) + session.setTimeout(location.getTimeout() * 1000); + JSchSession schSession = new JSchSession(session, location); + pool.put(key, schSession); + return schSession; } - return jschSession; + return jschSession; } catch (JSchException e) { pool.remove(key); if(e.toString().indexOf("Auth cancel")!=-1){ //$NON-NLS-1$ @@ -106,35 +106,35 @@ class JSchSession { } } - private static Session createSession(IJSchService service, IJSchLocation location, String password, IProgressMonitor monitor) throws JSchException { - if (password != null) - location.setPassword(password); - Session session = service.createSession(location, null); - session.setTimeout(getCVSTimeoutInMillis()); - if (password != null) + private static Session createSession(IJSchService service, IJSchLocation location, String password, IProgressMonitor monitor) throws JSchException { + if (password != null) + location.setPassword(password); + Session session = service.createSession(location, null); + session.setTimeout(getCVSTimeoutInMillis()); + if (password != null) session.setPassword(password); - service.connect(session, getCVSTimeoutInMillis(), monitor); - return session; - } + service.connect(session, getCVSTimeoutInMillis(), monitor); + return session; + } - private static IJSchService getJSchService(){ - return CVSSSH2Plugin.getDefault().getJSchService(); - } + private static IJSchService getJSchService(){ + return CVSSSH2Plugin.getDefault().getJSchService(); + } - private static String getPoolKey(String username, String hostname, int port) { - return username + "@" + hostname + ":" + port; //$NON-NLS-1$ //$NON-NLS-2$ - } + private static String getPoolKey(String username, String hostname, int port) { + return username + "@" + hostname + ":" + port; //$NON-NLS-1$ //$NON-NLS-2$ + } - private static String getPoolKey(ICVSRepositoryLocation location){ - return location.getUsername() + "@" + location.getHost() + ":" + getPort(location); //$NON-NLS-1$ //$NON-NLS-2$ - } + private static String getPoolKey(ICVSRepositoryLocation location){ + return location.getUsername() + "@" + location.getHost() + ":" + getPort(location); //$NON-NLS-1$ //$NON-NLS-2$ + } private static int getPort(ICVSRepositoryLocation location) { - int port = location.getPort(); - if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) - port = SSH_DEFAULT_PORT; - return port; - } + int port = location.getPort(); + if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) + port = SSH_DEFAULT_PORT; + return port; + } static void shutdown() { if (getJSch() != null && pool.size() > 0) { @@ -153,21 +153,21 @@ class JSchSession { static JSch getJSch() { return getJSchService().getJSch(); } - - private JSchSession(Session session, ICVSRepositoryLocation location) { - this.session = session; - this.location = location; - } - - public Session getSession() { - return session; - } - - public void dispose() { - if (session.isConnected()) { - session.disconnect(); - } - pool.remove(getPoolKey(location)); - } + + private JSchSession(Session session, ICVSRepositoryLocation location) { + this.session = session; + this.location = location; + } + + public Session getSession() { + return session; + } + + public void dispose() { + if (session.isConnected()) { + session.disconnect(); + } + pool.remove(getPoolKey(location)); + } } diff --git a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java index 00ff5bea8..700719e82 100644 --- a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java +++ b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java @@ -112,14 +112,14 @@ public class PServerSSH2ServerConnection implements IServerConnection { session.setPortForwardingL(lport, rhost, rport); } } catch (JSchException ee) { - retry--; - if(retry<0){ - throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_3, CVSAuthenticationException.NO_RETRY, location); - } - if(session != null && session.isConnected()){ - session.disconnect(); - } - continue; + retry--; + if(retry<0){ + throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_3, CVSAuthenticationException.NO_RETRY, location); + } + if(session != null && session.isConnected()){ + session.disconnect(); + } + continue; } break; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AddToVersionControlDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AddToVersionControlDialog.java index 3e5499027..ec34ce9b9 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AddToVersionControlDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AddToVersionControlDialog.java @@ -57,7 +57,7 @@ public class AddToVersionControlDialog extends DetailsDialog { Composite composite = new Composite(parent, SWT.NULL); composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - + // add a description label if (unaddedResources.length==1) { createWrappingLabel(composite, NLS.bind(CVSUIMessages.AddToVersionControlDialog_thereIsAnUnaddedResource, new String[] { Integer.valueOf(unaddedResources.length).toString() })); @@ -66,10 +66,10 @@ public class AddToVersionControlDialog extends DetailsDialog { } } - @Override + @Override protected String getHelpContextId() { - return IHelpContextIds.ADD_TO_VERSION_CONTROL_DIALOG; - } + return IHelpContextIds.ADD_TO_VERSION_CONTROL_DIALOG; + } @Override protected Composite createDropDownDialogArea(Composite parent) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AlternateUserValidationDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AlternateUserValidationDialog.java index 27f85d95d..647d18e14 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AlternateUserValidationDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AlternateUserValidationDialog.java @@ -144,7 +144,7 @@ public class AlternateUserValidationDialog extends Dialog { data.widthHint = 70; b.setLayoutData(data); b.addListener(SWT.Selection, event -> cancelPressed()); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); return main; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSCompareEditorInput.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSCompareEditorInput.java index 0727d9a56..029e7ed15 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSCompareEditorInput.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSCompareEditorInput.java @@ -48,7 +48,7 @@ public class CVSCompareEditorInput extends CompareEditorInput { private static final int NODE_UNKNOWN = 2; String toolTipText; - private String title; + private String title; /** * Creates a new CVSCompareEditorInput. @@ -412,52 +412,52 @@ public class CVSCompareEditorInput extends CompareEditorInput { setLabels(cc, event.getStructuredSelection()); }); ((StructuredViewer)viewer).addOpenListener(event -> { - ISelection selection = event.getSelection(); - if (! selection.isEmpty() && selection instanceof IStructuredSelection) { - Object o = ((IStructuredSelection)selection).getFirstElement(); - if (o instanceof DiffNode) { - updateLabelsFor((DiffNode)o); - } - } + ISelection selection = event.getSelection(); + if (! selection.isEmpty() && selection instanceof IStructuredSelection) { + Object o = ((IStructuredSelection)selection).getFirstElement(); + if (o instanceof DiffNode) { + updateLabelsFor((DiffNode)o); + } + } }); - ((StructuredViewer)viewer).addDoubleClickListener(event -> { - ISelection selection = event.getSelection(); - if (! selection.isEmpty() && selection instanceof IStructuredSelection) { - Object o = ((IStructuredSelection)selection).getFirstElement(); - if (o instanceof DiffNode) { - DiffNode diffNode = ((DiffNode)o); - if (diffNode.hasChildren()) { - AbstractTreeViewer atv = ((AbstractTreeViewer)viewer); - atv.setExpandedState(o, !atv.getExpandedState(o)); - } - } - } + ((StructuredViewer)viewer).addDoubleClickListener(event -> { + ISelection selection = event.getSelection(); + if (! selection.isEmpty() && selection instanceof IStructuredSelection) { + Object o = ((IStructuredSelection)selection).getFirstElement(); + if (o instanceof DiffNode) { + DiffNode diffNode = ((DiffNode)o); + if (diffNode.hasChildren()) { + AbstractTreeViewer atv = ((AbstractTreeViewer)viewer); + atv.setExpandedState(o, !atv.getExpandedState(o)); + } + } + } }); return viewer; } /* * Update the labels for the given DiffNode - */ - protected void updateLabelsFor(DiffNode node) { - CompareConfiguration cc = getCompareConfiguration(); - ITypedElement l = node.getLeft(); - if (l == null) { - cc.setLeftLabel(CVSUIMessages.CVSCompareEditorInput_0); - cc.setLeftImage(null); - } else { - cc.setLeftLabel(getLabel(l)); - cc.setLeftImage(l.getImage()); - } - ITypedElement r = node.getRight(); - if (r == null) { - cc.setRightLabel(CVSUIMessages.CVSCompareEditorInput_1); - cc.setRightImage(null); - } else { - cc.setRightLabel(getLabel(r)); - cc.setRightImage(r.getImage()); - } - } + */ + protected void updateLabelsFor(DiffNode node) { + CompareConfiguration cc = getCompareConfiguration(); + ITypedElement l = node.getLeft(); + if (l == null) { + cc.setLeftLabel(CVSUIMessages.CVSCompareEditorInput_0); + cc.setLeftImage(null); + } else { + cc.setLeftLabel(getLabel(l)); + cc.setLeftImage(l.getImage()); + } + ITypedElement r = node.getRight(); + if (r == null) { + cc.setRightLabel(CVSUIMessages.CVSCompareEditorInput_1); + cc.setRightImage(null); + } else { + cc.setRightLabel(getLabel(r)); + cc.setRightImage(r.getImage()); + } + } @Override public String getToolTipText() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java index 93241c352..06fbde3e5 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java @@ -271,14 +271,14 @@ public class CVSDecoration { bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, location.getRootDirectory()); bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, repository); - RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager(); - RepositoryRoot root = repositoryManager.getRepositoryRootFor(location); - CVSUIPlugin.getPlugin().getRepositoryManager(); - String label = root.getName(); - if (label == null) { - label = location.getLocation(true); - } - bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label); + RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager(); + RepositoryRoot root = repositoryManager.getRepositoryRootFor(location); + CVSUIPlugin.getPlugin().getRepositoryManager(); + String label = root.getName(); + if (label == null) { + label = location.getLocation(true); + } + bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label); } CVSDecoratorConfiguration.decorate(this, getTextFormatter(), bindings); } @@ -446,9 +446,9 @@ public class CVSDecoration { public void setStateFlags(int stateFlags) { this.stateFlags = stateFlags; - if ((stateFlags & IThreeWayDiff.OUTGOING) != 0) { - setDirty(true); - } + if ((stateFlags & IThreeWayDiff.OUTGOING) != 0) { + setDirty(true); + } } public TeamStateDescription asTeamStateDescription(String[] properties) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorPreferencesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorPreferencesPage.java index 15c6caac1..3ecbab3a8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorPreferencesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorPreferencesPage.java @@ -344,8 +344,8 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork final Composite composite= SWTUtils.createHFillComposite(parent, SWTUtils.MARGINS_DEFAULT); Dialog.applyDialogFont(composite); - SWTUtils.createPreferenceLink((IWorkbenchPreferenceContainer) getContainer(), composite, CVSUIMessages.CVSDecoratorPreferencesPage_36, CVSUIMessages.CVSDecoratorPreferencesPage_37); - + SWTUtils.createPreferenceLink((IWorkbenchPreferenceContainer) getContainer(), composite, CVSUIMessages.CVSDecoratorPreferencesPage_36, CVSUIMessages.CVSDecoratorPreferencesPage_37); + fShowDirty= SWTUtils.createCheckBox(composite, CVSUIMessages.CVSDecoratorPreferencesPage_16); SWTUtils.createLabel(composite, CVSUIMessages.CVSDecoratorPreferencesPage_17); @@ -407,7 +407,7 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork private final TreeViewer fViewer; public Preview(Composite composite) { - SWTUtils.createLabel(composite, CVSUIMessages.CVSDecoratorPreferencesPage_39); + SWTUtils.createLabel(composite, CVSUIMessages.CVSDecoratorPreferencesPage_39); fImageCache= new LocalResourceManager(JFaceResources.getResources()); fViewer = new TreeViewer(composite); fViewer.getControl().setLayoutData(SWTUtils.createHVFillGridData()); @@ -472,7 +472,7 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork @Override public void dispose() { - fImageCache.dispose(); + fImageCache.dispose(); } @Override @@ -528,11 +528,11 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork if (overlay == null) return baseImage; try { - return fImageCache.createImage(new DecorationOverlayIcon(baseImage, overlay, IDecoration.BOTTOM_RIGHT)); - } catch (DeviceResourceException e) { - CVSUIPlugin.log(new Status(IStatus.ERROR, CVSUIPlugin.ID, 0, "Error creating decorator image", e)); //$NON-NLS-1$ - } - return null; + return fImageCache.createImage(new DecorationOverlayIcon(baseImage, overlay, IDecoration.BOTTOM_RIGHT)); + } catch (DeviceResourceException e) { + CVSUIPlugin.log(new Status(IStatus.ERROR, CVSUIPlugin.ID, 0, "Error creating decorator image", e)); //$NON-NLS-1$ + } + return null; } } @@ -570,7 +570,7 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork FOLDER_BINDINGS.put(CVSDecoratorConfiguration.REMOTELOCATION_USER, CVSUIMessages.CVSDecoratorPreferencesPage_32); FOLDER_BINDINGS.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, CVSUIMessages.CVSDecoratorPreferencesPage_33); FOLDER_BINDINGS.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, CVSUIMessages.CVSDecoratorPreferencesPage_34); - FOLDER_BINDINGS.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, CVSUIMessages.CVSDecoratorPreferencesPage_38); + FOLDER_BINDINGS.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, CVSUIMessages.CVSDecoratorPreferencesPage_38); FOLDER_BINDINGS.put(CVSDecoratorConfiguration.NEW_DIRTY_FLAG, CVSUIMessages.CVSDecoratorPreferencesPage_35); final PreviewFile project= new PreviewFile("Project", IResource.PROJECT, false, false, false, false, true, null, "v1_0"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -617,7 +617,7 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork fGeneralTab.addObserver(fPreview); initializeValues(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.DECORATORS_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.DECORATORS_PREFERENCE_PAGE); Dialog.applyDialogFont(parent); PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(fThemeListener= new ThemeListener(fPreview)); @@ -629,8 +629,8 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork public void dispose() { if (fThemeListener != null) PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(fThemeListener); - if (fPreview != null) - fPreview.dispose(); + if (fPreview != null) + fPreview.dispose(); } /** @@ -660,10 +660,10 @@ public class CVSDecoratorPreferencesPage extends PreferencePage implements IWork fTextTab.performOk(store); fIconTab.performOk(store); fGeneralTab.performOk(store); - if (store.needsSaving()) { - CVSUIPlugin.broadcastPropertyChange(new PropertyChangeEvent(this, CVSUIPlugin.P_DECORATORS_CHANGED, null, null)); - CVSUIPlugin.getPlugin().savePluginPreferences(); - } + if (store.needsSaving()) { + CVSUIPlugin.broadcastPropertyChange(new PropertyChangeEvent(this, CVSUIPlugin.P_DECORATORS_CHANGED, null, null)); + CVSUIPlugin.getPlugin().savePluginPreferences(); + } return true; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSFolderPropertiesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSFolderPropertiesPage.java index 20de8a4c2..751b529bc 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSFolderPropertiesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSFolderPropertiesPage.java @@ -106,8 +106,8 @@ public class CVSFolderPropertiesPage extends CVSPropertiesPage { // Display error text createLabel(composite, CVSUIMessages.CVSFilePropertiesPage_error, 2); } - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.FOLDER_PROPERTY_PAGE); - Dialog.applyDialogFont(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.FOLDER_PROPERTY_PAGE); + Dialog.applyDialogFont(parent); return composite; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryPage.java index 52163627b..5b2485847 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryPage.java @@ -305,30 +305,30 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC } private TextViewer createText(SashForm parent) { - SourceViewer result = new SourceViewer(parent, null, null, true, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY); - result.getTextWidget().setIndent(2); - result.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore()) { - @Override + SourceViewer result = new SourceViewer(parent, null, null, true, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY); + result.getTextWidget().setIndent(2); + result.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore()) { + @Override protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) { - return Collections.singletonMap("org.eclipse.ui.DefaultTextEditor", //$NON-NLS-1$ - new IAdaptable() { - @Override + return Collections.singletonMap("org.eclipse.ui.DefaultTextEditor", //$NON-NLS-1$ + new IAdaptable() { + @Override public <T> T getAdapter(Class<T> adapter) { - if(adapter==IFile.class && getInput() instanceof IFile) { - return adapter.cast(getInput()); - } else if(adapter==IFileHistory.class && getInput() instanceof IFileHistory) { - return adapter.cast(getInput()); - } - return Platform.getAdapterManager().getAdapter(CVSHistoryPage.this, adapter); - } - }); - } - }); - - result.addSelectionChangedListener(event -> copyAction.update()); - result.setTextDoubleClickStrategy( - new DefaultTextDoubleClickStrategy(), - IDocument.DEFAULT_CONTENT_TYPE); + if(adapter==IFile.class && getInput() instanceof IFile) { + return adapter.cast(getInput()); + } else if(adapter==IFileHistory.class && getInput() instanceof IFileHistory) { + return adapter.cast(getInput()); + } + return Platform.getAdapterManager().getAdapter(CVSHistoryPage.this, adapter); + } + }); + } + }); + + result.addSelectionChangedListener(event -> copyAction.update()); + result.setTextDoubleClickStrategy( + new DefaultTextDoubleClickStrategy(), + IDocument.DEFAULT_CONTENT_TYPE); result.activatePlugins(); return result; } @@ -380,10 +380,10 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC CVSTag tag1 = (CVSTag) e1; CVSTag tag2 = (CVSTag) e2; int type1 = tag1.getType(); - int type2 = tag2.getType(); - if (type1 != type2) { - return type2 - type1; - } + int type2 = tag2.getType(); + if (type1 != type2) { + return type2 - type1; + } if (sortTagsAscending) return super.compare(viewer, tag1, tag2); else @@ -591,7 +591,7 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC monitor.done(); } }); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, IHelpContextIds.GET_FILE_CONTENTS_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, IHelpContextIds.GET_FILE_CONTENTS_ACTION); getRevisionAction = getContextMenuAction(CVSUIMessages.HistoryView_getRevisionAction, true /* needs progress */, monitor -> { ICVSRemoteFile remoteFile = (ICVSRemoteFile) CVSWorkspaceRoot.getRemoteResourceFor(((CVSFileRevision) currentSelection).getCVSRemoteFile()); @@ -616,7 +616,7 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC // Cancelled by user } }); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getRevisionAction, IHelpContextIds.GET_FILE_REVISION_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getRevisionAction, IHelpContextIds.GET_FILE_REVISION_ACTION); // Override MoveRemoteTagAction to work for log entries final IActionDelegate tagActionDelegate = new MoveRemoteTagAction() { @@ -651,31 +651,31 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC } return resources; } - /* - * Override the creation of the tag operation in order to support - * the refresh of the view after the tag operation completes - */ - @Override + /* + * Override the creation of the tag operation in order to support + * the refresh of the view after the tag operation completes + */ + @Override protected ITagOperation createTagOperation() { - return new TagInRepositoryOperation(getTargetPart(), getSelectedRemoteResources()) { - @Override + return new TagInRepositoryOperation(getTargetPart(), getSelectedRemoteResources()) { + @Override public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { - super.execute(monitor); - Display.getDefault().asyncExec(() -> { - if( ! wasCancelled()) { - refresh(); - } + super.execute(monitor); + Display.getDefault().asyncExec(() -> { + if( ! wasCancelled()) { + refresh(); + } }); - }; - }; - } + }; + }; + } }; tagWithExistingAction = getContextMenuAction(CVSUIMessages.HistoryView_tagWithExistingAction, false /* no progress */, monitor -> { tagActionDelegate.selectionChanged(tagWithExistingAction, treeViewer.getSelection()); tagActionDelegate.run(tagWithExistingAction); }); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getRevisionAction, IHelpContextIds.TAG_WITH_EXISTING_ACTION); - + PlatformUI.getWorkbench().getHelpSystem().setHelp(getRevisionAction, IHelpContextIds.TAG_WITH_EXISTING_ACTION); + // Toggle text visible action toggleTextAction = new Action(TeamUIMessages.GenericHistoryView_ShowCommentViewer) { @Override @@ -717,7 +717,7 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC store.setValue(ICVSUIConstants.PREF_SHOW_SEARCH, toggleSearchAction.isChecked()); if (!toggleSearchAction.isChecked()){ if (searchFilter != null) - treeViewer.removeFilter(searchFilter); + treeViewer.removeFilter(searchFilter); } else { searchField.setMessage(CVSUIMessages.CVSHistoryPage_EnterSearchTerm); searchField.selectAll(); @@ -863,7 +863,7 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC manager.add(new Separator("openCompare")); //$NON-NLS-1$ } if (file != null && - !(file instanceof RemoteFile)) { + !(file instanceof RemoteFile)) { // Add the "Add to Workspace" action if 1 revision is selected. ISelection sel = treeViewer.getSelection(); if (!sel.isEmpty()) { @@ -1416,8 +1416,8 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC String searchString = searchField.getText(); if (searchString.equals("") || //$NON-NLS-1$ searchString.equals(CVSUIMessages.CVSHistoryPage_EnterSearchTerm)) { - if (searchFilter != null) - treeViewer.removeFilter(searchFilter); + if (searchFilter != null) + treeViewer.removeFilter(searchFilter); return; } @@ -1698,7 +1698,7 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC message = CVSUIMessages.CVSHistoryPage_NoRevisions; break; } - + MessageHistoryCategory messageCategory = new MessageHistoryCategory(NLS.bind(CVSUIMessages.CVSHistoryPage_NoRevisionsForMode, new String[] { message })); return messageCategory; } @@ -1746,7 +1746,7 @@ public class CVSHistoryPage extends HistoryPage implements IAdaptable, IHistoryC //Safety check for non-managed files that are added with the CVSHistoryPage //in view if (file == null || file.getIResource() == null) - return; + return; IResourceDelta resourceDelta = root.findMember(((IFile)file.getIResource()).getFullPath()); if (resourceDelta != null){ diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryTableProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryTableProvider.java index 39993dfcb..b888c3eb6 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryTableProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSHistoryTableProvider.java @@ -726,8 +726,8 @@ public class CVSHistoryTableProvider { treeViewer.getTree().setSortDirection(oldSorter.isReversed() ? SWT.DOWN : SWT.UP); treeViewer.refresh(); } else { - treeViewer.getTree().setSortColumn(treeColumn); - treeViewer.getTree().setSortDirection(SWT.UP); + treeViewer.getTree().setSortColumn(treeColumn); + treeViewer.getTree().setSortDirection(SWT.UP); treeViewer.setComparator(new HistoryComparator(column)); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSLightweightDecorator.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSLightweightDecorator.java index 1b72d8a43..9a7f7608c 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSLightweightDecorator.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSLightweightDecorator.java @@ -166,12 +166,12 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig } catch(CoreException e) { handleException(element, e); } catch (IllegalStateException e) { - // This is thrown by Core if the workspace is in an illegal state - // If we are not active, ignore it. Otherwise, propagate it. - // (see bug 78303) - if (Platform.getBundle(CVSUIPlugin.ID).getState() == Bundle.ACTIVE) { - throw e; - } + // This is thrown by Core if the workspace is in an illegal state + // If we are not active, ignore it. Otherwise, propagate it. + // (see bug 78303) + if (Platform.getBundle(CVSUIPlugin.ID).getState() == Bundle.ACTIVE) { + throw e; + } } } @@ -185,29 +185,29 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig /* * Return whether any of the projects of the mapping are mapped to CVS */ - private boolean isMappedToCVS(ResourceMapping mapping) { - IProject[] projects = mapping.getProjects(); - boolean foundOne = false; - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - if (project != null) { - RepositoryProvider provider = RepositoryProvider.getProvider(project); + private boolean isMappedToCVS(ResourceMapping mapping) { + IProject[] projects = mapping.getProjects(); + boolean foundOne = false; + for (int i = 0; i < projects.length; i++) { + IProject project = projects[i]; + if (project != null) { + RepositoryProvider provider = RepositoryProvider.getProvider(project); if (provider instanceof CVSTeamProvider) { foundOne = true; - } else if (provider != null) { - return false; - } - } - } - return foundOne; - } - - public static CVSDecoration decorate(Object element, SynchronizationStateTester tester) throws CoreException { - IPreferenceStore store = CVSUIPlugin.getPlugin().getPreferenceStore(); - CVSDecoration result = new CVSDecoration(); - - // First, decorate the synchronization state - int state = IDiff.NO_CHANGE; + } else if (provider != null) { + return false; + } + } + } + return foundOne; + } + + public static CVSDecoration decorate(Object element, SynchronizationStateTester tester) throws CoreException { + IPreferenceStore store = CVSUIPlugin.getPlugin().getPreferenceStore(); + CVSDecoration result = new CVSDecoration(); + + // First, decorate the synchronization state + int state = IDiff.NO_CHANGE; if (isSupervised(element)) { // TODO: Not quite right result.setHasRemote(true); @@ -217,9 +217,9 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig : 0, new NullProgressMonitor()); result.setStateFlags(state); - } else { - result.setIgnored(true); - } + } else { + result.setIgnored(true); + } // Tag if (!result.isIgnored()) { CVSTag tag = getTagToShow(element); @@ -243,9 +243,9 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig decorate(resource, result); } tester.elementDecorated(element, result.asTeamStateDescription(null)); - return result; - } - + return result; + } + private static boolean isSupervised(Object element) throws CoreException { IResource[] resources = getTraversalRoots(element); for (int i = 0; i < resources.length; i++) { @@ -342,13 +342,13 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig } if (!cvsDecoration.isIgnored()) { // Dirty - if (includeDirtyCheck) { - boolean computeDeepDirtyCheck = store.getBoolean(ICVSUIConstants.PREF_CALCULATE_DIRTY); - int type = resource.getType(); - if (type == IResource.FILE || computeDeepDirtyCheck) { - cvsDecoration.setDirty(CVSLightweightDecorator.isDirty(resource)); - } - } + if (includeDirtyCheck) { + boolean computeDeepDirtyCheck = store.getBoolean(ICVSUIConstants.PREF_CALCULATE_DIRTY); + int type = resource.getType(); + if (type == IResource.FILE || computeDeepDirtyCheck) { + cvsDecoration.setDirty(CVSLightweightDecorator.isDirty(resource)); + } + } } decorate(resource, cvsDecoration); return cvsDecoration; @@ -462,7 +462,7 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig /* * Add resource and its parents to the List */ - + private void addWithParents(IResource resource, Set resources) { IResource current = resource; @@ -482,7 +482,7 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig /* * Update the decorators for every resource in project */ - + public void refresh(IProject project) { final List resources = new ArrayList(); try { @@ -597,22 +597,22 @@ public class CVSLightweightDecorator extends LabelProvider implements ILightweig public void propertyChange(PropertyChangeEvent event) { if (isEventOfInterest(event)) { ensureFontAndColorsCreated(fonts, colors); - refresh(); + refresh(); } } - private boolean isEventOfInterest(PropertyChangeEvent event) { - String prop = event.getProperty(); - return prop.equals(TeamUI.GLOBAL_IGNORES_CHANGED) - || prop.equals(TeamUI.GLOBAL_FILE_TYPES_CHANGED) - || prop.equals(CVSUIPlugin.P_DECORATORS_CHANGED) + private boolean isEventOfInterest(PropertyChangeEvent event) { + String prop = event.getProperty(); + return prop.equals(TeamUI.GLOBAL_IGNORES_CHANGED) + || prop.equals(TeamUI.GLOBAL_FILE_TYPES_CHANGED) + || prop.equals(CVSUIPlugin.P_DECORATORS_CHANGED) || prop.equals(CVSDecoratorConfiguration.OUTGOING_CHANGE_BACKGROUND_COLOR) || prop.equals(CVSDecoratorConfiguration.OUTGOING_CHANGE_FOREGROUND_COLOR) || prop.equals(CVSDecoratorConfiguration.OUTGOING_CHANGE_FONT) || prop.equals(CVSDecoratorConfiguration.IGNORED_FOREGROUND_COLOR) || prop.equals(CVSDecoratorConfiguration.IGNORED_BACKGROUND_COLOR) || prop.equals(CVSDecoratorConfiguration.IGNORED_FONT); - } + } private static CVSWorkspaceSubscriber getSubscriber() { return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPerspective.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPerspective.java index 755071061..7c234e2b1 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPerspective.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPerspective.java @@ -20,7 +20,7 @@ import org.eclipse.ui.*; public class CVSPerspective implements IPerspectiveFactory { - + public final static String ID = "org.eclipse.team.cvs.ui.cvsPerspective"; //$NON-NLS-1$ @Override diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPreferencesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPreferencesPage.java index 0156e8466..ea9a9140a 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPreferencesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSPreferencesPage.java @@ -65,7 +65,7 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref return 0; } } - + private abstract class Field { protected final String fKey; @@ -86,7 +86,7 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref super(key); fCheckbox= new Button(composite, SWT.CHECK); fCheckbox.setText(label); - PlatformUI.getWorkbench().getHelpSystem().setHelp(fCheckbox, helpID); + PlatformUI.getWorkbench().getHelpSystem().setHelp(fCheckbox, helpID); } public void initializeValue(IPreferenceStore store) { @@ -117,7 +117,7 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref label.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, false, false)); } - PlatformUI.getWorkbench().getHelpSystem().setHelp(fCombo, helpID); + PlatformUI.getWorkbench().getHelpSystem().setHelp(fCombo, helpID); } public Combo getCombo() { @@ -191,16 +191,16 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref fButtons[i].setText(labels[i]); } SWTUtils.equalizeControls(SWTUtils.createDialogPixelConverter(composite), fButtons, 0, fButtons.length - 2); - PlatformUI.getWorkbench().getHelpSystem().setHelp(fGroup, helpID); + PlatformUI.getWorkbench().getHelpSystem().setHelp(fGroup, helpID); } public void initializeValue(IPreferenceStore store) { final Object value= loadValue(store, fKey); final int index= fValues.indexOf(value); - for (int i = 0; i < fButtons.length; i++) { - Button b = fButtons[i]; - b.setSelection(index == i); - } + for (int i = 0; i < fButtons.length; i++) { + Button b = fButtons[i]; + b.setSelection(index == i); + } } public void performOk(IPreferenceStore store) { @@ -258,10 +258,10 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref label.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, false, false)); fText= SWTUtils.createText(composite); - fText.addModifyListener(this); + fText.addModifyListener(this); - if (helpID != null) - PlatformUI.getWorkbench().getHelpSystem().setHelp(fText, helpID); + if (helpID != null) + PlatformUI.getWorkbench().getHelpSystem().setHelp(fText, helpID); } public void initializeValue(IPreferenceStore store) { @@ -273,10 +273,10 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref store.setValue(fKey, fText.getText()); } - public void modifyText(ModifyEvent e) { - modifyText(fText); - } - + public void modifyText(ModifyEvent e) { + modifyText(fText); + } + protected abstract void modifyText(Text text); } @@ -334,9 +334,9 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref COMPRESSION_VALUES[i]= Integer.valueOf(i); } - final IPerspectiveDescriptor [] perspectives= PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives(); - PERSPECTIVE_VALUES= new String[perspectives.length + 1]; - PERSPECTIVE_LABELS= new String [perspectives.length + 1]; + final IPerspectiveDescriptor [] perspectives= PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives(); + PERSPECTIVE_VALUES= new String[perspectives.length + 1]; + PERSPECTIVE_LABELS= new String [perspectives.length + 1]; Arrays.sort(perspectives, new PerspectiveDescriptorComparator()); PERSPECTIVE_VALUES[0]= ICVSUIConstants.OPTION_NO_PERSPECTIVE; PERSPECTIVE_LABELS[0]= CVSUIMessages.CVSPreferencesPage_10; @@ -363,7 +363,7 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref Dialog.applyDialogFont(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.GENERAL_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.GENERAL_PREFERENCE_PAGE); return tabFolder; } @@ -376,54 +376,54 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref new Checkbox(composite, ICVSUIConstants.PREF_CONFIRM_MOVE_TAG, CVSUIMessages.CVSPreferencesPage_16, IHelpContextIds.PREF_CONFIRM_MOVE_TAG); new Checkbox(composite, ICVSUIConstants.PREF_DEBUG_PROTOCOL, CVSUIMessages.CVSPreferencesPage_17, IHelpContextIds.PREF_DEBUG_PROTOCOL); new Checkbox(composite, ICVSUIConstants.PREF_AUTO_REFRESH_TAGS_IN_TAG_SELECTION_DIALOG, CVSUIMessages.CVSPreferencesPage_18, IHelpContextIds.PREF_AUTOREFRESH_TAG); - new Checkbox(composite, ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT, CVSUIMessages.CVSPreferencesPage_44, null); - new Checkbox(composite, ICVSUIConstants.PREF_USE_PROJECT_NAME_ON_CHECKOUT, CVSUIMessages.CVSPreferencesPage_45, null); - - final Composite textComposite= SWTUtils.createHFillComposite(composite, SWTUtils.MARGINS_NONE, 2); - new TextField( - textComposite, - ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD, - CVSUIMessages.CVSPreferencesPage_20, - null) { - protected void modifyText(Text text) { - // Parse the timeout value - try { - final int x = Integer.parseInt(text.getText()); - if (x >= 0) { - setErrorMessage(null); - setValid(true); - } else { - setErrorMessage(CVSUIMessages.CVSPreferencesPage_21); - setValid(false); - } - } catch (NumberFormatException ex) { - setErrorMessage(CVSUIMessages.CVSPreferencesPage_22); - setValid(false); - } - } - }; - new TextField( - textComposite, - ICVSUIConstants.PREF_COMMIT_COMMENTS_MAX_HISTORY, - CVSUIMessages.CVSPreferencesPage_47, - null) { - protected void modifyText(Text text) { - try { - final int x = Integer.parseInt(text.getText()); - if (x > 0) { - setErrorMessage(null); - setValid(true); - } else { - setErrorMessage(CVSUIMessages.CVSPreferencesPage_48); - setValid(false); - } - } catch (NumberFormatException ex) { - setErrorMessage(CVSUIMessages.CVSPreferencesPage_49); - setValid(false); - } - } - }; - + new Checkbox(composite, ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT, CVSUIMessages.CVSPreferencesPage_44, null); + new Checkbox(composite, ICVSUIConstants.PREF_USE_PROJECT_NAME_ON_CHECKOUT, CVSUIMessages.CVSPreferencesPage_45, null); + + final Composite textComposite= SWTUtils.createHFillComposite(composite, SWTUtils.MARGINS_NONE, 2); + new TextField( + textComposite, + ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD, + CVSUIMessages.CVSPreferencesPage_20, + null) { + protected void modifyText(Text text) { + // Parse the timeout value + try { + final int x = Integer.parseInt(text.getText()); + if (x >= 0) { + setErrorMessage(null); + setValid(true); + } else { + setErrorMessage(CVSUIMessages.CVSPreferencesPage_21); + setValid(false); + } + } catch (NumberFormatException ex) { + setErrorMessage(CVSUIMessages.CVSPreferencesPage_22); + setValid(false); + } + } + }; + new TextField( + textComposite, + ICVSUIConstants.PREF_COMMIT_COMMENTS_MAX_HISTORY, + CVSUIMessages.CVSPreferencesPage_47, + null) { + protected void modifyText(Text text) { + try { + final int x = Integer.parseInt(text.getText()); + if (x > 0) { + setErrorMessage(null); + setValid(true); + } else { + setErrorMessage(CVSUIMessages.CVSPreferencesPage_48); + setValid(false); + } + } catch (NumberFormatException ex) { + setErrorMessage(CVSUIMessages.CVSPreferencesPage_49); + setValid(false); + } + } + }; + return composite; } @@ -531,37 +531,37 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref ICVSUIConstants.PREF_SAVE_DIRTY_EDITORS, CVSUIMessages.CVSPreferencesPage_41, IHelpContextIds.PREF_SAVE_DIRTY_EDITORS, - YES_NO_PROMPT, - new Integer [] { Integer.valueOf(ICVSUIConstants.OPTION_AUTOMATIC), Integer.valueOf(ICVSUIConstants.OPTION_NEVER), Integer.valueOf(ICVSUIConstants.OPTION_PROMPT)}); - - new StringRadioButtons( - composite, - ICVSUIConstants.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, - CVSUIMessages.CVSPreferencesPage_46, - IHelpContextIds.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, - YES_NO_PROMPT, - new String [] { MessageDialogWithToggle.ALWAYS, MessageDialogWithToggle.NEVER, MessageDialogWithToggle.PROMPT } - ); - - new StringRadioButtons( - composite, - ICVSUIConstants.PREF_ALLOW_COMMIT_WITH_WARNINGS, - CVSUIMessages.CVSPreferencesPage_50, - IHelpContextIds.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, - YES_NO_PROMPT, - new String [] { MessageDialogWithToggle.ALWAYS, MessageDialogWithToggle.NEVER, MessageDialogWithToggle.PROMPT } - ); + YES_NO_PROMPT, + new Integer [] { Integer.valueOf(ICVSUIConstants.OPTION_AUTOMATIC), Integer.valueOf(ICVSUIConstants.OPTION_NEVER), Integer.valueOf(ICVSUIConstants.OPTION_PROMPT)}); + + new StringRadioButtons( + composite, + ICVSUIConstants.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, + CVSUIMessages.CVSPreferencesPage_46, + IHelpContextIds.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, + YES_NO_PROMPT, + new String [] { MessageDialogWithToggle.ALWAYS, MessageDialogWithToggle.NEVER, MessageDialogWithToggle.PROMPT } + ); + + new StringRadioButtons( + composite, + ICVSUIConstants.PREF_ALLOW_COMMIT_WITH_WARNINGS, + CVSUIMessages.CVSPreferencesPage_50, + IHelpContextIds.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, + YES_NO_PROMPT, + new String [] { MessageDialogWithToggle.ALWAYS, MessageDialogWithToggle.NEVER, MessageDialogWithToggle.PROMPT } + ); - new StringRadioButtons( - composite, - ICVSUIConstants.PREF_ALLOW_COMMIT_WITH_ERRORS, - CVSUIMessages.CVSPreferencesPage_51, - IHelpContextIds.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, - YES_NO_PROMPT, - new String [] { MessageDialogWithToggle.ALWAYS, MessageDialogWithToggle.NEVER, MessageDialogWithToggle.PROMPT } - ); - SWTUtils.createPlaceholder(composite, 1); - + new StringRadioButtons( + composite, + ICVSUIConstants.PREF_ALLOW_COMMIT_WITH_ERRORS, + CVSUIMessages.CVSPreferencesPage_51, + IHelpContextIds.PREF_INCLUDE_CHANGE_SETS_IN_COMMIT, + YES_NO_PROMPT, + new String [] { MessageDialogWithToggle.ALWAYS, MessageDialogWithToggle.NEVER, MessageDialogWithToggle.PROMPT } + ); + SWTUtils.createPlaceholder(composite, 1); + return composite; } @@ -597,7 +597,7 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(newKSubst); CVSProviderPlugin.getPlugin().setUsePlatformLineend(store.getBoolean(ICVSUIConstants.PREF_USE_PLATFORM_LINEEND)); CVSProviderPlugin.getPlugin().setDetermineVersionEnabled(store.getBoolean(ICVSUIConstants.PREF_DETERMINE_SERVER_VERSION)); - CVSProviderPlugin.getPlugin().setAutoshareOnImport(store.getBoolean(ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT)); + CVSProviderPlugin.getPlugin().setAutoshareOnImport(store.getBoolean(ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT)); // changing the default keyword substitution mode for text files may affect // information displayed in the decorators @@ -617,13 +617,13 @@ public class CVSPreferencesPage extends PreferencePage implements IWorkbenchPref } } - /** - * Returns preference store that belongs to the our plugin. - * This is important because we want to store - * our preferences separately from the desktop. - * - * @return the preference store for this plugin - */ + /** + * Returns preference store that belongs to the our plugin. + * This is important because we want to store + * our preferences separately from the desktop. + * + * @return the preference store for this plugin + */ protected IPreferenceStore doGetPreferenceStore() { return CVSUIPlugin.getPlugin().getPreferenceStore(); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java index d942b74c7..6a786d621 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java @@ -227,8 +227,8 @@ public class CVSProjectPropertiesPage extends CVSPropertiesPage { }); initializeValues(oldLocation); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.PROJECT_PROPERTY_PAGE); - Dialog.applyDialogFont(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.PROJECT_PROPERTY_PAGE); + Dialog.applyDialogFont(parent); return composite; } /** @@ -308,7 +308,7 @@ public class CVSProjectPropertiesPage extends CVSPropertiesPage { hostText.setText(location.getHost()); int port = location.getPort(); if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) { - portText.setText(CVSUIMessages.CVSPropertiesPage_defaultPort); + portText.setText(CVSUIMessages.CVSPropertiesPage_defaultPort); } else { portText.setText("" + port); //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSResourceTransfer.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSResourceTransfer.java index 90acf4934..0a2b0192b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSResourceTransfer.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSResourceTransfer.java @@ -28,81 +28,81 @@ import org.eclipse.team.internal.ccvs.core.util.KnownRepositories; * @author Eugene Kuleshov */ public final class CVSResourceTransfer extends ByteArrayTransfer { - - public static final String TYPE_NAME = "CVS-resource-transfer-format"; //$NON-NLS-1$ + + public static final String TYPE_NAME = "CVS-resource-transfer-format"; //$NON-NLS-1$ - public static int TYPE = registerType(TYPE_NAME); + public static int TYPE = registerType(TYPE_NAME); - private static CVSResourceTransfer instance = new CVSResourceTransfer(); + private static CVSResourceTransfer instance = new CVSResourceTransfer(); - - private CVSResourceTransfer() { - } + + private CVSResourceTransfer() { + } - public static CVSResourceTransfer getInstance() { - return instance; - } + public static CVSResourceTransfer getInstance() { + return instance; + } - - @Override + + @Override protected int[] getTypeIds() { - return new int[] { TYPE }; - } + return new int[] { TYPE }; + } - @Override + @Override protected String[] getTypeNames() { - return new String[] { TYPE_NAME }; - } + return new String[] { TYPE_NAME }; + } - @Override + @Override public void javaToNative(Object object, TransferData transferData) { - if (!isSupportedType(transferData)) { - DND.error(DND.ERROR_INVALID_DATA); - } + if (!isSupportedType(transferData)) { + DND.error(DND.ERROR_INVALID_DATA); + } - final byte[] bytes = toByteArray((ICVSRemoteFile) object); - if (bytes != null) { - super.javaToNative(bytes, transferData); - } - } + final byte[] bytes = toByteArray((ICVSRemoteFile) object); + if (bytes != null) { + super.javaToNative(bytes, transferData); + } + } - @Override + @Override protected Object nativeToJava(TransferData transferData) { - byte[] bytes = (byte[]) super.nativeToJava(transferData); - return fromByteArray(bytes); - } - - - public Object fromByteArray(byte[] bytes) { - final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); - - try { - String location = in.readUTF(); - String filePath = in.readUTF(); - String fileRevision = in.readUTF(); - - ICVSRepositoryLocation repositoryLocation = KnownRepositories.getInstance().getRepository(location); - RemoteFile file = RemoteFile.create( filePath, repositoryLocation); - file.setRevision(fileRevision); - file.setReadOnly(true); - return file; - } catch (Exception ex) { - return null; - } - } - - public byte[] toByteArray(ICVSRemoteFile file) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(bos); - try { - dos.writeUTF(file.getRepository().getLocation(false)); - dos.writeUTF(file.getRepositoryRelativePath()); - dos.writeUTF(file.getRevision()); - return bos.toByteArray(); - } catch (Exception ex) { - // ex.printStackTrace(); - return null; - } - } + byte[] bytes = (byte[]) super.nativeToJava(transferData); + return fromByteArray(bytes); + } + + + public Object fromByteArray(byte[] bytes) { + final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); + + try { + String location = in.readUTF(); + String filePath = in.readUTF(); + String fileRevision = in.readUTF(); + + ICVSRepositoryLocation repositoryLocation = KnownRepositories.getInstance().getRepository(location); + RemoteFile file = RemoteFile.create( filePath, repositoryLocation); + file.setRevision(fileRevision); + file.setReadOnly(true); + return file; + } catch (Exception ex) { + return null; + } + } + + public byte[] toByteArray(ICVSRemoteFile file) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(bos); + try { + dos.writeUTF(file.getRepository().getLocation(false)); + dos.writeUTF(file.getRepositoryRelativePath()); + dos.writeUTF(file.getRevision()); + return bos.toByteArray(); + } catch (Exception ex) { + // ex.printStackTrace(); + return null; + } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIMessages.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIMessages.java index bab538fa7..fee1372a9 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIMessages.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIMessages.java @@ -198,10 +198,10 @@ public class CVSUIMessages extends NLS { public static String CVSDecoratorPreferencesPage_33; public static String CVSDecoratorPreferencesPage_34; public static String CVSDecoratorPreferencesPage_35; - public static String CVSDecoratorPreferencesPage_36; - public static String CVSDecoratorPreferencesPage_37; - public static String CVSDecoratorPreferencesPage_38; // repository label - public static String CVSDecoratorPreferencesPage_39; + public static String CVSDecoratorPreferencesPage_36; + public static String CVSDecoratorPreferencesPage_37; + public static String CVSDecoratorPreferencesPage_38; // repository label + public static String CVSDecoratorPreferencesPage_39; public static String CVSDecoratorConfiguration_0; public static String CVSDecoratorConfiguration_1; public static String CVSDecoratorConfiguration_2; @@ -278,8 +278,8 @@ public class CVSUIMessages extends NLS { public static String CVSPreferencesPage_39; public static String CVSPreferencesPage_40; public static String CVSPreferencesPage_41; - public static String CVSPreferencesPage_44; - public static String CVSPreferencesPage_45; + public static String CVSPreferencesPage_44; + public static String CVSPreferencesPage_45; public static String CVSPropertiesPage_virtualModule; @@ -680,7 +680,7 @@ public class CVSUIMessages extends NLS { public static String TagConfigurationDialog_20; public static String TagConfigurationDialog_21; public static String TagConfigurationDialog_22; - public static String TagConfigurationDialog_AddDateTag; + public static String TagConfigurationDialog_AddDateTag; public static String ConfigureTagsFromRepoViewConfigure_Tag_Error_1; public static String RemoteRootAction_label; @@ -766,7 +766,7 @@ public class CVSUIMessages extends NLS { public static String WatchEditPreferencePage_checkoutReadOnly; public static String WatchEditPreferencePage_validateEditSaveAction; public static String WatchEditPreferencePage_edit; - public static String WatchEditPreferencePage_editInBackground; + public static String WatchEditPreferencePage_editInBackground; public static String WatchEditPreferencePage_highjack; public static String WatchEditPreferencePage_editPrompt; public static String WatchEditPreferencePage_neverPrompt; @@ -891,21 +891,21 @@ public class CVSUIMessages extends NLS { public static String CommitCommentArea_2; public static String CommitCommentArea_3; public static String CommitCommentArea_4; - public static String CommitCommentArea_5; - public static String CommitCommentArea_6; - - public static String CommentTemplatesPreferencePage_Description; - public static String CommentTemplatesPreferencePage_New; - public static String CommentTemplatesPreferencePage_Edit; - public static String CommentTemplatesPreferencePage_Remove; - public static String CommentTemplatesPreferencePage_Preview; - public static String CommentTemplatesPreferencePage_EditCommentTemplateTitle; - public static String CommentTemplatesPreferencePage_EditCommentTemplateMessage; + public static String CommitCommentArea_5; + public static String CommitCommentArea_6; + + public static String CommentTemplatesPreferencePage_Description; + public static String CommentTemplatesPreferencePage_New; + public static String CommentTemplatesPreferencePage_Edit; + public static String CommentTemplatesPreferencePage_Remove; + public static String CommentTemplatesPreferencePage_Preview; + public static String CommentTemplatesPreferencePage_EditCommentTemplateTitle; + public static String CommentTemplatesPreferencePage_EditCommentTemplateMessage; public static String CheckoutProjectOperation_8; public static String CheckoutProjectOperation_9; public static String CheckoutProjectOperation_0; - public static String CheckoutProjectOperation_1; + public static String CheckoutProjectOperation_1; public static String CVSOperation_0; public static String CVSOperation_1; public static String CVSOperation_2; @@ -970,8 +970,8 @@ public class CVSUIMessages extends NLS { public static String FileModificationValidator_3; public static String FileModificationValidator_4; - public static String FileModificationValidator_5; - public static String FileModificationValidator_6; + public static String FileModificationValidator_5; + public static String FileModificationValidator_6; public static String CVSSynchronizeWizard_0; public static String Participant_comparing; public static String Participant_merging; @@ -998,8 +998,8 @@ public class CVSUIMessages extends NLS { public static String SharingWizardSyncPage_8; public static String SharingWizardSyncPage_9; public static String SharingWizardSyncPage_12; - public static String ShareProjectOperation_2; - public static String ShareProjectOperation_3; + public static String ShareProjectOperation_2; + public static String ShareProjectOperation_3; public static String CVSProjectPropertiesPage_31; public static String CVSProjectPropertiesPage_32; public static String CVSProjectPropertiesPage_33; @@ -1072,9 +1072,9 @@ public class CVSUIMessages extends NLS { public static String ReplaceWithTagAction_2; public static String AddWizard_0; - public static String OpenChangeSetAction_0; - public static String OpenChangeSetAction_1; - + public static String OpenChangeSetAction_0; + public static String OpenChangeSetAction_1; + public static String WorkInProgressPage_0; public static String WorkInProgressPage_1; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIPlugin.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIPlugin.java index ab74ecc5d..daf9546f3 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIPlugin.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSUIPlugin.java @@ -163,7 +163,7 @@ public class CVSUIPlugin extends AbstractUIPlugin { * supplied operation will be run again. */ public static void runWithRefresh(Shell parent, IResource[] resources, - IRunnableWithProgress runnable, IProgressMonitor monitor) + IRunnableWithProgress runnable, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { boolean firstTime = true; while(true) { @@ -237,7 +237,7 @@ public class CVSUIPlugin extends AbstractUIPlugin { * @exception InterruptedException when the progress monitor is canceled */ public static void runWithProgress(Shell parent, boolean cancelable, - final IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { + final IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { Utils.runWithProgress(parent, cancelable, runnable); } @@ -270,7 +270,7 @@ public class CVSUIPlugin extends AbstractUIPlugin { } return repositoryManager; } - + /** * Initializes the table of images used in this plugin. */ @@ -598,11 +598,11 @@ public class CVSUIPlugin extends AbstractUIPlugin { store.setDefault(ICVSUIConstants.PREF_SHOW_COMPARE_REVISION_IN_DIALOG, false); store.setDefault(ICVSUIConstants.PREF_COMMIT_SET_DEFAULT_ENABLEMENT, false); store.setDefault(ICVSUIConstants.PREF_AUTO_REFRESH_TAGS_IN_TAG_SELECTION_DIALOG, false); - store.setDefault(ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT, true); - store.setDefault(ICVSUIConstants.PREF_ENABLE_WATCH_ON_EDIT, false); - store.setDefault(ICVSUIConstants.PREF_USE_PROJECT_NAME_ON_CHECKOUT, false); - store.setDefault(ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD, 1000); - store.setDefault(ICVSUIConstants.PREF_COMMIT_COMMENTS_MAX_HISTORY, RepositoryManager.DEFAULT_MAX_COMMENTS); + store.setDefault(ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT, true); + store.setDefault(ICVSUIConstants.PREF_ENABLE_WATCH_ON_EDIT, false); + store.setDefault(ICVSUIConstants.PREF_USE_PROJECT_NAME_ON_CHECKOUT, false); + store.setDefault(ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD, 1000); + store.setDefault(ICVSUIConstants.PREF_COMMIT_COMMENTS_MAX_HISTORY, RepositoryManager.DEFAULT_MAX_COMMENTS); PreferenceConverter.setDefault(store, ICVSUIConstants.PREF_CONSOLE_COMMAND_COLOR, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, ICVSUIConstants.PREF_CONSOLE_MESSAGE_COLOR, new RGB(0, 0, 255)); @@ -646,7 +646,7 @@ public class CVSUIPlugin extends AbstractUIPlugin { store.setDefault(ICVSUIConstants.PREF_CHECKOUT_READ_ONLY, corePrefs.getDefaultBoolean(CVSProviderPlugin.READ_ONLY)); store.setDefault(ICVSUIConstants.PREF_EDIT_ACTION, ICVSUIConstants.PREF_EDIT_IN_BACKGROUND); store.setDefault(ICVSUIConstants.PREF_EDIT_PROMPT, ICVSUIConstants.PREF_EDIT_PROMPT_IF_EDITORS); - store.setDefault(ICVSUIConstants.PREF_UPDATE_PROMPT, ICVSUIConstants.PREF_UPDATE_PROMPT_NEVER); + store.setDefault(ICVSUIConstants.PREF_UPDATE_PROMPT, ICVSUIConstants.PREF_UPDATE_PROMPT_NEVER); // Ensure that the preference values in UI match Core store.setValue(ICVSUIConstants.PREF_CHECKOUT_READ_ONLY, corePrefs.getBoolean(CVSProviderPlugin.READ_ONLY)); @@ -665,15 +665,15 @@ public class CVSUIPlugin extends AbstractUIPlugin { CVSProviderPlugin.getPlugin().setRepositoriesAreBinary(store.getBoolean(ICVSUIConstants.PREF_REPOSITORIES_ARE_BINARY)); CVSProviderPlugin.getPlugin().setDetermineVersionEnabled(store.getBoolean(ICVSUIConstants.PREF_DETERMINE_SERVER_VERSION)); CVSProviderPlugin.getPlugin().setDebugProtocol(CVSProviderPlugin.getPlugin().isDebugProtocol() || store.getBoolean(ICVSUIConstants.PREF_DEBUG_PROTOCOL)); - CVSProviderPlugin.getPlugin().setAutoshareOnImport(store.getBoolean(ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT)); - - // code to transfer CVS preference to Team preference - if (store.getBoolean(ICVSUIConstants.PREF_SHOW_AUTHOR_IN_EDITOR)) { - store.setValue(ICVSUIConstants.PREF_SHOW_AUTHOR_IN_EDITOR, false); - IPreferenceStore teamStore = TeamUIPlugin.getPlugin().getPreferenceStore(); - if (teamStore.isDefault(IPreferenceIds.SHOW_AUTHOR_IN_COMPARE_EDITOR)) - teamStore.setValue(IPreferenceIds.SHOW_AUTHOR_IN_COMPARE_EDITOR, true); - } + CVSProviderPlugin.getPlugin().setAutoshareOnImport(store.getBoolean(ICVSUIConstants.PREF_AUTO_SHARE_ON_IMPORT)); + + // code to transfer CVS preference to Team preference + if (store.getBoolean(ICVSUIConstants.PREF_SHOW_AUTHOR_IN_EDITOR)) { + store.setValue(ICVSUIConstants.PREF_SHOW_AUTHOR_IN_EDITOR, false); + IPreferenceStore teamStore = TeamUIPlugin.getPlugin().getPreferenceStore(); + if (teamStore.isDefault(IPreferenceIds.SHOW_AUTHOR_IN_COMPARE_EDITOR)) + teamStore.setValue(IPreferenceIds.SHOW_AUTHOR_IN_COMPARE_EDITOR, true); + } } @Override @@ -694,11 +694,11 @@ public class CVSUIPlugin extends AbstractUIPlugin { Platform.getAdapterManager().registerAdapters(factory, RepositoryRoot.class); try { - console = new CVSOutputConsole(); - } catch (RuntimeException e) { - // Don't let the console bring down the CVS UI - log(IStatus.ERROR, "Errors occurred starting the CVS console", e); //$NON-NLS-1$ - } + console = new CVSOutputConsole(); + } catch (RuntimeException e) { + // Don't let the console bring down the CVS UI + log(IStatus.ERROR, "Errors occurred starting the CVS console", e); //$NON-NLS-1$ + } IPreferenceStore store = getPreferenceStore(); if (store.getBoolean(ICVSUIConstants.PREF_FIRST_STARTUP)) { @@ -729,7 +729,7 @@ public class CVSUIPlugin extends AbstractUIPlugin { } if (console != null) - console.shutdown(); + console.shutdown(); } finally { super.stop(context); } @@ -741,16 +741,16 @@ public class CVSUIPlugin extends AbstractUIPlugin { public CVSOutputConsole getConsole() { return console; } - - public IEditorPart openEditor(ICVSRemoteFile file, IProgressMonitor monitor) throws InvocationTargetException { - IWorkbench workbench = getWorkbench(); - IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); - try { + + public IEditorPart openEditor(ICVSRemoteFile file, IProgressMonitor monitor) throws InvocationTargetException { + IWorkbench workbench = getWorkbench(); + IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); + try { return Utils.openEditor(page, file.getAdapter(IFileRevision.class), monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } - } + } /** * Helper method which access the preference store to determine if the diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommentTemplateEditDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommentTemplateEditDialog.java index 2a55ea5b2..29b965052 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommentTemplateEditDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommentTemplateEditDialog.java @@ -28,214 +28,214 @@ import org.eclipse.swt.widgets.*; * </p> */ public class CommentTemplateEditDialog extends Dialog { - /** - * The title of the dialog. - */ - private String title; - - /** - * The message to display, or <code>null</code> if none. - */ - private String message; - - /** - * The input value; the empty string by default. - */ - private String value = "";//$NON-NLS-1$ - - /** - * The input validator, or <code>null</code> if none. - */ - private IInputValidator validator; - - /** - * Ok button widget. - */ - private Button okButton; - - /** - * Input text widget. - */ - private Text text; - - /** - * Error message label widget. - */ - private Text errorMessageText; - - /** - * Creates an input dialog with OK and Cancel buttons. Note that the dialog - * will have no visual representation (no widgets) until it is told to open. - * <p> - * Note that the <code>open</code> method blocks for input dialogs. - * </p> - * - * @param parentShell - * the parent shell, or <code>null</code> to create a top-level - * shell - * @param dialogTitle - * the dialog title, or <code>null</code> if none - * @param dialogMessage - * the dialog message, or <code>null</code> if none - * @param initialValue - * the initial input value, or <code>null</code> if none - * (equivalent to the empty string) - * @param validator - * an input validator, or <code>null</code> if none - */ - public CommentTemplateEditDialog(Shell parentShell, String dialogTitle, - String dialogMessage, String initialValue, IInputValidator validator) { - super(parentShell); - this.title = dialogTitle; - message = dialogMessage; - if (initialValue == null) - value = "";//$NON-NLS-1$ - else - value = initialValue; - this.validator = validator; - } - - @Override + /** + * The title of the dialog. + */ + private String title; + + /** + * The message to display, or <code>null</code> if none. + */ + private String message; + + /** + * The input value; the empty string by default. + */ + private String value = "";//$NON-NLS-1$ + + /** + * The input validator, or <code>null</code> if none. + */ + private IInputValidator validator; + + /** + * Ok button widget. + */ + private Button okButton; + + /** + * Input text widget. + */ + private Text text; + + /** + * Error message label widget. + */ + private Text errorMessageText; + + /** + * Creates an input dialog with OK and Cancel buttons. Note that the dialog + * will have no visual representation (no widgets) until it is told to open. + * <p> + * Note that the <code>open</code> method blocks for input dialogs. + * </p> + * + * @param parentShell + * the parent shell, or <code>null</code> to create a top-level + * shell + * @param dialogTitle + * the dialog title, or <code>null</code> if none + * @param dialogMessage + * the dialog message, or <code>null</code> if none + * @param initialValue + * the initial input value, or <code>null</code> if none + * (equivalent to the empty string) + * @param validator + * an input validator, or <code>null</code> if none + */ + public CommentTemplateEditDialog(Shell parentShell, String dialogTitle, + String dialogMessage, String initialValue, IInputValidator validator) { + super(parentShell); + this.title = dialogTitle; + message = dialogMessage; + if (initialValue == null) + value = "";//$NON-NLS-1$ + else + value = initialValue; + this.validator = validator; + } + + @Override protected void buttonPressed(int buttonId) { - if (buttonId == IDialogConstants.OK_ID) { - value = text.getText(); - } else { - value = null; - } - super.buttonPressed(buttonId); - } - - @Override + if (buttonId == IDialogConstants.OK_ID) { + value = text.getText(); + } else { + value = null; + } + super.buttonPressed(buttonId); + } + + @Override protected void configureShell(Shell shell) { - super.configureShell(shell); - if (title != null) - shell.setText(title); - } + super.configureShell(shell); + if (title != null) + shell.setText(title); + } - @Override + @Override protected void createButtonsForButtonBar(Composite parent) { - // create OK and Cancel buttons by default - okButton = createButton(parent, IDialogConstants.OK_ID, - IDialogConstants.OK_LABEL, true); - createButton(parent, IDialogConstants.CANCEL_ID, - IDialogConstants.CANCEL_LABEL, false); - //do this here because setting the text will set enablement on the ok - // button - text.setFocus(); - if (value != null) { - text.setText(value); - text.selectAll(); - } - } - - @Override + // create OK and Cancel buttons by default + okButton = createButton(parent, IDialogConstants.OK_ID, + IDialogConstants.OK_LABEL, true); + createButton(parent, IDialogConstants.CANCEL_ID, + IDialogConstants.CANCEL_LABEL, false); + //do this here because setting the text will set enablement on the ok + // button + text.setFocus(); + if (value != null) { + text.setText(value); + text.selectAll(); + } + } + + @Override protected Control createDialogArea(Composite parent) { - // create composite - Composite composite = (Composite) super.createDialogArea(parent); - // create message - if (message != null) { - Label label = new Label(composite, SWT.WRAP); - label.setText(message); - GridData data = new GridData(GridData.GRAB_HORIZONTAL - | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL - | GridData.VERTICAL_ALIGN_CENTER); - data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); - label.setLayoutData(data); - label.setFont(parent.getFont()); - } - text = new Text(composite, SWT.MULTI | SWT.BORDER); - GridData gd = new GridData(GridData.GRAB_HORIZONTAL - | GridData.HORIZONTAL_ALIGN_FILL); + // create composite + Composite composite = (Composite) super.createDialogArea(parent); + // create message + if (message != null) { + Label label = new Label(composite, SWT.WRAP); + label.setText(message); + GridData data = new GridData(GridData.GRAB_HORIZONTAL + | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_CENTER); + data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); + label.setLayoutData(data); + label.setFont(parent.getFont()); + } + text = new Text(composite, SWT.MULTI | SWT.BORDER); + GridData gd = new GridData(GridData.GRAB_HORIZONTAL + | GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = convertHeightInCharsToPixels(5); text.setLayoutData(gd); text.addModifyListener(e -> validateInput()); - errorMessageText = new Text(composite, SWT.READ_ONLY); - errorMessageText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL - | GridData.HORIZONTAL_ALIGN_FILL)); - errorMessageText.setBackground(errorMessageText.getDisplay() - .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); - - applyDialogFont(composite); - return composite; - } - - /** - * Returns the error message label. - * - * @return the error message label - * @deprecated use setErrorMessage(String) instead - */ - @Deprecated + errorMessageText = new Text(composite, SWT.READ_ONLY); + errorMessageText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL + | GridData.HORIZONTAL_ALIGN_FILL)); + errorMessageText.setBackground(errorMessageText.getDisplay() + .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + + applyDialogFont(composite); + return composite; + } + + /** + * Returns the error message label. + * + * @return the error message label + * @deprecated use setErrorMessage(String) instead + */ + @Deprecated protected Label getErrorMessageLabel() { - return null; - } - - /** - * Returns the ok button. - * - * @return the ok button - */ - protected Button getOkButton() { - return okButton; - } - - /** - * Returns the text area. - * - * @return the text area - */ - protected Text getText() { - return text; - } - - /** - * Returns the validator. - * - * @return the validator - */ - protected IInputValidator getValidator() { - return validator; - } - - /** - * Returns the string typed into this input dialog. - * - * @return the input string - */ - public String getValue() { - return value; - } - - /** - * Validates the input. - * <p> - * The default implementation of this framework method delegates the request - * to the supplied input validator object; if it finds the input invalid, - * the error message is displayed in the dialog's message line. This hook - * method is called whenever the text changes in the input field. - * </p> - */ - protected void validateInput() { - String errorMessage = null; - if (validator != null) { - errorMessage = validator.isValid(text.getText()); - } - // Bug 16256: important not to treat "" (blank error) the same as null - // (no error) - setErrorMessage(errorMessage); - } - - /** - * Sets or clears the error message. - * If not <code>null</code>, the OK button is disabled. - * - * @param errorMessage - * the error message, or <code>null</code> to clear - * @since 3.0 - */ - public void setErrorMessage(String errorMessage) { - errorMessageText.setText(errorMessage == null ? "" : errorMessage); //$NON-NLS-1$ - okButton.setEnabled(errorMessage == null); - errorMessageText.getParent().update(); - } + return null; + } + + /** + * Returns the ok button. + * + * @return the ok button + */ + protected Button getOkButton() { + return okButton; + } + + /** + * Returns the text area. + * + * @return the text area + */ + protected Text getText() { + return text; + } + + /** + * Returns the validator. + * + * @return the validator + */ + protected IInputValidator getValidator() { + return validator; + } + + /** + * Returns the string typed into this input dialog. + * + * @return the input string + */ + public String getValue() { + return value; + } + + /** + * Validates the input. + * <p> + * The default implementation of this framework method delegates the request + * to the supplied input validator object; if it finds the input invalid, + * the error message is displayed in the dialog's message line. This hook + * method is called whenever the text changes in the input field. + * </p> + */ + protected void validateInput() { + String errorMessage = null; + if (validator != null) { + errorMessage = validator.isValid(text.getText()); + } + // Bug 16256: important not to treat "" (blank error) the same as null + // (no error) + setErrorMessage(errorMessage); + } + + /** + * Sets or clears the error message. + * If not <code>null</code>, the OK button is disabled. + * + * @param errorMessage + * the error message, or <code>null</code> to clear + * @since 3.0 + */ + public void setErrorMessage(String errorMessage) { + errorMessageText.setText(errorMessage == null ? "" : errorMessage); //$NON-NLS-1$ + okButton.setEnabled(errorMessage == null); + errorMessageText.getParent().update(); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java index f8bc0d4d0..11b8a76a2 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java @@ -57,65 +57,65 @@ import org.eclipse.ui.texteditor.*; */ public class CommitCommentArea extends DialogArea { - private class TextBox implements ModifyListener, TraverseListener, FocusListener, Observer, IDocumentListener { - - private final StyledText fTextField; // updated only by modify events - private final String fMessage; - private String fText; - private IDocument fDocument; - - public TextBox(Composite composite, String message, String initialText) { - - fMessage= message; - fText= initialText; - - AnnotationModel annotationModel = new AnnotationModel(); - IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess(); + private class TextBox implements ModifyListener, TraverseListener, FocusListener, Observer, IDocumentListener { + + private final StyledText fTextField; // updated only by modify events + private final String fMessage; + private String fText; + private IDocument fDocument; + + public TextBox(Composite composite, String message, String initialText) { + + fMessage= message; + fText= initialText; + + AnnotationModel annotationModel = new AnnotationModel(); + IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess(); - Composite cc = new Composite(composite, SWT.BORDER); - cc.setLayout(new FillLayout()); - cc.setLayoutData(new GridData(GridData.FILL_BOTH)); - - final SourceViewer sourceViewer = new SourceViewer(cc, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP); - fTextField = sourceViewer.getTextWidget(); - fTextField.setIndent(2); - - final SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(sourceViewer, null, annotationAccess, EditorsUI.getSharedTextColors()); - - Iterator e= new MarkerAnnotationPreferences().getAnnotationPreferences().iterator(); - while (e.hasNext()) - support.setAnnotationPreference((AnnotationPreference) e.next()); - - support.install(EditorsUI.getPreferenceStore()); - - final IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); - final IHandlerActivation handlerActivation = installQuickFixActionHandler(handlerService, sourceViewer); - - final TextViewerAction cutAction = new TextViewerAction(sourceViewer, ITextOperationTarget.CUT); - cutAction.setText(CVSUIMessages.CommitCommentArea_7); - cutAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); - - final TextViewerAction copyAction = new TextViewerAction(sourceViewer, ITextOperationTarget.COPY); - copyAction.setText(CVSUIMessages.CommitCommentArea_8); - copyAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); - - final TextViewerAction pasteAction = new TextViewerAction(sourceViewer, ITextOperationTarget.PASTE); - pasteAction.setText(CVSUIMessages.CommitCommentArea_9); - pasteAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); - - final TextViewerAction selectAllAction = new TextViewerAction(sourceViewer, ITextOperationTarget.SELECT_ALL); - selectAllAction.setText(CVSUIMessages.CommitCommentArea_10); - selectAllAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_SELECT_ALL); - - MenuManager contextMenu = new MenuManager(); - contextMenu.add(cutAction); - contextMenu.add(copyAction); - contextMenu.add(pasteAction); - contextMenu.add(selectAllAction); - contextMenu.add(new Separator()); - - final SubMenuManager quickFixMenu = new SubMenuManager(contextMenu); - quickFixMenu.setVisible(true); + Composite cc = new Composite(composite, SWT.BORDER); + cc.setLayout(new FillLayout()); + cc.setLayoutData(new GridData(GridData.FILL_BOTH)); + + final SourceViewer sourceViewer = new SourceViewer(cc, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP); + fTextField = sourceViewer.getTextWidget(); + fTextField.setIndent(2); + + final SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(sourceViewer, null, annotationAccess, EditorsUI.getSharedTextColors()); + + Iterator e= new MarkerAnnotationPreferences().getAnnotationPreferences().iterator(); + while (e.hasNext()) + support.setAnnotationPreference((AnnotationPreference) e.next()); + + support.install(EditorsUI.getPreferenceStore()); + + final IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); + final IHandlerActivation handlerActivation = installQuickFixActionHandler(handlerService, sourceViewer); + + final TextViewerAction cutAction = new TextViewerAction(sourceViewer, ITextOperationTarget.CUT); + cutAction.setText(CVSUIMessages.CommitCommentArea_7); + cutAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_CUT); + + final TextViewerAction copyAction = new TextViewerAction(sourceViewer, ITextOperationTarget.COPY); + copyAction.setText(CVSUIMessages.CommitCommentArea_8); + copyAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY); + + final TextViewerAction pasteAction = new TextViewerAction(sourceViewer, ITextOperationTarget.PASTE); + pasteAction.setText(CVSUIMessages.CommitCommentArea_9); + pasteAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE); + + final TextViewerAction selectAllAction = new TextViewerAction(sourceViewer, ITextOperationTarget.SELECT_ALL); + selectAllAction.setText(CVSUIMessages.CommitCommentArea_10); + selectAllAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_SELECT_ALL); + + MenuManager contextMenu = new MenuManager(); + contextMenu.add(cutAction); + contextMenu.add(copyAction); + contextMenu.add(pasteAction); + contextMenu.add(selectAllAction); + contextMenu.add(new Separator()); + + final SubMenuManager quickFixMenu = new SubMenuManager(contextMenu); + quickFixMenu.setVisible(true); quickFixMenu.addMenuListener(manager -> { quickFixMenu.removeAll(); @@ -151,9 +151,9 @@ public class CommitCommentArea extends DialogArea { } } }); - - fTextField.addFocusListener(new FocusListener() { - + + fTextField.addFocusListener(new FocusListener() { + private IHandlerActivation cutHandlerActivation; private IHandlerActivation copyHandlerActivation; private IHandlerActivation pasteHandlerActivation; @@ -165,11 +165,11 @@ public class CommitCommentArea extends DialogArea { copyAction.update(); IHandlerService service = PlatformUI.getWorkbench().getService(IHandlerService.class); this.cutHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_CUT, new ActionHandler(cutAction), new ActiveShellExpression(getComposite().getShell())); - this.copyHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_COPY, new ActionHandler(copyAction), new ActiveShellExpression(getComposite().getShell())); - this.pasteHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_PASTE, new ActionHandler(pasteAction), new ActiveShellExpression(getComposite().getShell())); - this.selectAllHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_SELECT_ALL, new ActionHandler(selectAllAction), new ActiveShellExpression(getComposite().getShell())); - - + this.copyHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_COPY, new ActionHandler(copyAction), new ActiveShellExpression(getComposite().getShell())); + this.pasteHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_PASTE, new ActionHandler(pasteAction), new ActiveShellExpression(getComposite().getShell())); + this.selectAllHandlerActivation = service.activateHandler(IWorkbenchCommandConstants.EDIT_SELECT_ALL, new ActionHandler(selectAllAction), new ActiveShellExpression(getComposite().getShell())); + + } @Override @@ -194,275 +194,275 @@ public class CommitCommentArea extends DialogArea { } }); - + sourceViewer.addSelectionChangedListener(event -> { cutAction.update(); copyAction.update(); }); - + sourceViewer.getTextWidget().addDisposeListener(e1 -> { support.uninstall(); handlerService.deactivateHandler(handlerActivation); }); - - fDocument = new Document(initialText); + + fDocument = new Document(initialText); - // NOTE: Configuration must be applied before the document is set in order for - // Hyperlink coloring to work. (Presenter needs document object up front) - sourceViewer.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore())); - sourceViewer.setDocument(fDocument, annotationModel); - fDocument.addDocumentListener(this); - fTextField.addTraverseListener(this); - fTextField.addModifyListener(this); - fTextField.addFocusListener(this); - - fTextField.setMenu(contextMenu.createContextMenu(fTextField)); - fTextField.selectAll(); - } - - protected boolean includes(Position position, int caretOffset) { + // NOTE: Configuration must be applied before the document is set in order for + // Hyperlink coloring to work. (Presenter needs document object up front) + sourceViewer.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore())); + sourceViewer.setDocument(fDocument, annotationModel); + fDocument.addDocumentListener(this); + fTextField.addTraverseListener(this); + fTextField.addModifyListener(this); + fTextField.addFocusListener(this); + + fTextField.setMenu(contextMenu.createContextMenu(fTextField)); + fTextField.selectAll(); + } + + protected boolean includes(Position position, int caretOffset) { return position.includes(caretOffset) || (position.offset + position.length) == caretOffset; } - - /** - * Installs the quick fix action handler - * and returns the handler activation. - * - * @param handlerService the handler service - * @param sourceViewer the source viewer - * @return the handler activation - * @since 3.4 - */ + + /** + * Installs the quick fix action handler + * and returns the handler activation. + * + * @param handlerService the handler service + * @param sourceViewer the source viewer + * @return the handler activation + * @since 3.4 + */ private IHandlerActivation installQuickFixActionHandler(IHandlerService handlerService, SourceViewer sourceViewer) { - return handlerService.activateHandler( - ITextEditorActionDefinitionIds.QUICK_ASSIST, - createQuickFixActionHandler(sourceViewer), - new ActiveShellExpression(sourceViewer.getTextWidget().getShell())); - } - - /** - * Creates and returns a quick fix action handler. - * - * @param textOperationTarget the target for text operations - * @since 3.4 - */ - private ActionHandler createQuickFixActionHandler(final ITextOperationTarget textOperationTarget) { - Action quickFixAction= new Action() { - @Override + return handlerService.activateHandler( + ITextEditorActionDefinitionIds.QUICK_ASSIST, + createQuickFixActionHandler(sourceViewer), + new ActiveShellExpression(sourceViewer.getTextWidget().getShell())); + } + + /** + * Creates and returns a quick fix action handler. + * + * @param textOperationTarget the target for text operations + * @since 3.4 + */ + private ActionHandler createQuickFixActionHandler(final ITextOperationTarget textOperationTarget) { + Action quickFixAction= new Action() { + @Override public void run() { - textOperationTarget.doOperation(ISourceViewer.QUICK_ASSIST); - } - }; - quickFixAction.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICK_ASSIST); - return new ActionHandler(quickFixAction); - } + textOperationTarget.doOperation(ISourceViewer.QUICK_ASSIST); + } + }; + quickFixAction.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICK_ASSIST); + return new ActionHandler(quickFixAction); + } - @Override + @Override public void modifyText(ModifyEvent e) { - final String old = fText; - fText = fTextField.getText(); - if (!fText.equals(old)) - firePropertyChangeChange(COMMENT_MODIFIED, old, fText); - } - - @Override + final String old = fText; + fText = fTextField.getText(); + if (!fText.equals(old)) + firePropertyChangeChange(COMMENT_MODIFIED, old, fText); + } + + @Override public void keyTraversed(TraverseEvent e) { - if (e.detail == SWT.TRAVERSE_RETURN && (e.stateMask & SWT.CTRL) != 0) { - e.doit = false; - firePropertyChangeChange(OK_REQUESTED, null, null); - } - } - - @Override + if (e.detail == SWT.TRAVERSE_RETURN && (e.stateMask & SWT.CTRL) != 0) { + e.doit = false; + firePropertyChangeChange(OK_REQUESTED, null, null); + } + } + + @Override public void focusGained(FocusEvent e) { - if (fText.length() > 0) - return; - - fTextField.removeModifyListener(this); - fDocument.removeDocumentListener(this); - try { - fTextField.setText(fText); - } finally { - fTextField.addModifyListener(this); - fDocument.addDocumentListener(this); - } - } - - @Override + if (fText.length() > 0) + return; + + fTextField.removeModifyListener(this); + fDocument.removeDocumentListener(this); + try { + fTextField.setText(fText); + } finally { + fTextField.addModifyListener(this); + fDocument.addDocumentListener(this); + } + } + + @Override public void focusLost(FocusEvent e) { - - if (fText.length() > 0) - return; - - fTextField.removeModifyListener(this); - fDocument.removeDocumentListener(this); - try { - fTextField.setText(fMessage); - fTextField.selectAll(); - } finally { - fTextField.addModifyListener(this); - fDocument.addDocumentListener(this); - } - } - - public void setEnabled(boolean enabled) { - fTextField.setEnabled(enabled); - } - - @Override + + if (fText.length() > 0) + return; + + fTextField.removeModifyListener(this); + fDocument.removeDocumentListener(this); + try { + fTextField.setText(fMessage); + fTextField.selectAll(); + } finally { + fTextField.addModifyListener(this); + fDocument.addDocumentListener(this); + } + } + + public void setEnabled(boolean enabled) { + fTextField.setEnabled(enabled); + } + + @Override public void update(Observable o, Object arg) { - if (arg instanceof String) { - setText((String)arg); // triggers a modify event - } - } - - public String getText() { - return fText; - } - - private void setText(String text) { - if (text.length() == 0) { - fTextField.setText(fMessage); - fTextField.selectAll(); - } else - fTextField.setText(text); - } + if (arg instanceof String) { + setText((String)arg); // triggers a modify event + } + } + + public String getText() { + return fText; + } + + private void setText(String text) { + if (text.length() == 0) { + fTextField.setText(fMessage); + fTextField.selectAll(); + } else + fTextField.setText(text); + } - public void setFocus() { - fTextField.setFocus(); - } + public void setFocus() { + fTextField.setFocus(); + } - @Override + @Override public void documentAboutToBeChanged(DocumentEvent event) { - } + } - @Override + @Override public void documentChanged(DocumentEvent event) { - modifyText(null); - } + modifyText(null); + } } - - private static class ComboBox extends Observable implements SelectionListener, FocusListener { - - private final String fMessage; - private final String [] fComments; - private String[] fCommentTemplates; - private final Combo fCombo; - - - public ComboBox(Composite composite, String message, String [] options, - String[] commentTemplates) { - - fMessage= message; - fComments= options; - fCommentTemplates = commentTemplates; - - fCombo = new Combo(composite, SWT.READ_ONLY); - fCombo.setLayoutData(SWTUtils.createHFillGridData()); - fCombo.setVisibleItemCount(20); - - // populate the previous comment list - populateList(); - - // We don't want to have an initial selection - // (see bug 32078: http://bugs.eclipse.org/bugs/show_bug.cgi?id=32078) - fCombo.addFocusListener(this); - fCombo.addSelectionListener(this); - } + + private static class ComboBox extends Observable implements SelectionListener, FocusListener { + + private final String fMessage; + private final String [] fComments; + private String[] fCommentTemplates; + private final Combo fCombo; + + + public ComboBox(Composite composite, String message, String [] options, + String[] commentTemplates) { + + fMessage= message; + fComments= options; + fCommentTemplates = commentTemplates; + + fCombo = new Combo(composite, SWT.READ_ONLY); + fCombo.setLayoutData(SWTUtils.createHFillGridData()); + fCombo.setVisibleItemCount(20); + + // populate the previous comment list + populateList(); + + // We don't want to have an initial selection + // (see bug 32078: http://bugs.eclipse.org/bugs/show_bug.cgi?id=32078) + fCombo.addFocusListener(this); + fCombo.addSelectionListener(this); + } private void populateList() { fCombo.removeAll(); fCombo.add(fMessage); - for (int i = 0; i < fCommentTemplates.length; i++) { - fCombo.add(CVSUIMessages.CommitCommentArea_6 + ": " + //$NON-NLS-1$ - Util.flattenText(fCommentTemplates[i])); - } - for (int i = 0; i < fComments.length; i++) { - fCombo.add(Util.flattenText(fComments[i])); - } - fCombo.setText(fMessage); - } - - @Override + for (int i = 0; i < fCommentTemplates.length; i++) { + fCombo.add(CVSUIMessages.CommitCommentArea_6 + ": " + //$NON-NLS-1$ + Util.flattenText(fCommentTemplates[i])); + } + for (int i = 0; i < fComments.length; i++) { + fCombo.add(Util.flattenText(fComments[i])); + } + fCombo.setText(fMessage); + } + + @Override public void widgetSelected(SelectionEvent e) { - int index = fCombo.getSelectionIndex(); - if (index > 0) { - index--; - setChanged(); - - // map from combo box index to array index - String message; - if (index < fCommentTemplates.length) { - message = fCommentTemplates[index]; - } else { - message = fComments[index - fCommentTemplates.length]; - } - notifyObservers(message); - } - } - - @Override + int index = fCombo.getSelectionIndex(); + if (index > 0) { + index--; + setChanged(); + + // map from combo box index to array index + String message; + if (index < fCommentTemplates.length) { + message = fCommentTemplates[index]; + } else { + message = fComments[index - fCommentTemplates.length]; + } + notifyObservers(message); + } + } + + @Override public void widgetDefaultSelected(SelectionEvent e) { - } - - @Override + } + + @Override public void focusGained(FocusEvent e) { - } - - @Override + } + + @Override public void focusLost(FocusEvent e) { - fCombo.removeSelectionListener(this); - try { - fCombo.setText(fMessage); - } finally { - fCombo.addSelectionListener(this); - } - } - - public void setEnabled(boolean enabled) { - fCombo.setEnabled(enabled); - } - - void setCommentTemplates(String[] templates) { + fCombo.removeSelectionListener(this); + try { + fCombo.setText(fMessage); + } finally { + fCombo.addSelectionListener(this); + } + } + + public void setEnabled(boolean enabled) { + fCombo.setEnabled(enabled); + } + + void setCommentTemplates(String[] templates) { fCommentTemplates = templates; populateList(); } - } - - private static final String EMPTY_MESSAGE= CVSUIMessages.CommitCommentArea_0; - private static final String COMBO_MESSAGE= CVSUIMessages.CommitCommentArea_1; - private static final String CONFIGURE_TEMPLATES_MESSAGE= CVSUIMessages.CommitCommentArea_5; - - public static final String OK_REQUESTED = "OkRequested";//$NON-NLS-1$ - public static final String COMMENT_MODIFIED = "CommentModified";//$NON-NLS-1$ - - private TextBox fTextBox; - private ComboBox fComboBox; - - private IProject fMainProject; - private String fProposedComment; - private Composite fComposite; - - @Override + } + + private static final String EMPTY_MESSAGE= CVSUIMessages.CommitCommentArea_0; + private static final String COMBO_MESSAGE= CVSUIMessages.CommitCommentArea_1; + private static final String CONFIGURE_TEMPLATES_MESSAGE= CVSUIMessages.CommitCommentArea_5; + + public static final String OK_REQUESTED = "OkRequested";//$NON-NLS-1$ + public static final String COMMENT_MODIFIED = "CommentModified";//$NON-NLS-1$ + + private TextBox fTextBox; + private ComboBox fComboBox; + + private IProject fMainProject; + private String fProposedComment; + private Composite fComposite; + + @Override public void createArea(Composite parent) { - Dialog.applyDialogFont(parent); - initializeDialogUnits(parent); - - fComposite = createGrabbingComposite(parent, 1); - initializeDialogUnits(fComposite); - - fTextBox= new TextBox(fComposite, EMPTY_MESSAGE, getInitialComment()); - - final String [] comments = CVSUIPlugin.getPlugin().getRepositoryManager().getPreviousComments(); - final String[] commentTemplates = CVSUIPlugin.getPlugin().getRepositoryManager().getCommentTemplates(); - fComboBox= new ComboBox(fComposite, COMBO_MESSAGE, comments, commentTemplates); - - Link templatesPrefsLink = new Link(fComposite, 0); - templatesPrefsLink.setText("<a href=\"configureTemplates\">" + //$NON-NLS-1$ - CONFIGURE_TEMPLATES_MESSAGE + "</a>"); //$NON-NLS-1$ - templatesPrefsLink.addSelectionListener(new SelectionListener() { + Dialog.applyDialogFont(parent); + initializeDialogUnits(parent); + + fComposite = createGrabbingComposite(parent, 1); + initializeDialogUnits(fComposite); + + fTextBox= new TextBox(fComposite, EMPTY_MESSAGE, getInitialComment()); + + final String [] comments = CVSUIPlugin.getPlugin().getRepositoryManager().getPreviousComments(); + final String[] commentTemplates = CVSUIPlugin.getPlugin().getRepositoryManager().getCommentTemplates(); + fComboBox= new ComboBox(fComposite, COMBO_MESSAGE, comments, commentTemplates); + + Link templatesPrefsLink = new Link(fComposite, 0); + templatesPrefsLink.setText("<a href=\"configureTemplates\">" + //$NON-NLS-1$ + CONFIGURE_TEMPLATES_MESSAGE + "</a>"); //$NON-NLS-1$ + templatesPrefsLink.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { openCommentTemplatesPreferencePage(); @@ -473,11 +473,11 @@ public class CommitCommentArea extends DialogArea { openCommentTemplatesPreferencePage(); } }); - - fComboBox.addObserver(fTextBox); - } - - void openCommentTemplatesPreferencePage() { + + fComboBox.addObserver(fTextBox); + } + + void openCommentTemplatesPreferencePage() { PreferencesUtil.createPreferenceDialogOn( null, "org.eclipse.team.cvs.ui.CommentTemplatesPreferences", //$NON-NLS-1$ @@ -488,17 +488,17 @@ public class CommitCommentArea extends DialogArea { } public String getComment(boolean save) { - final String comment= fTextBox.getText(); - if (comment == null) - return ""; //$NON-NLS-1$ - - final String stripped= strip(comment); - if (save && comment.length() > 0) - CVSUIPlugin.getPlugin().getRepositoryManager().addComment(comment); + final String comment= fTextBox.getText(); + if (comment == null) + return ""; //$NON-NLS-1$ + + final String stripped= strip(comment); + if (save && comment.length() > 0) + CVSUIPlugin.getPlugin().getRepositoryManager().addComment(comment); - return stripped; - } - + return stripped; + } + /** * Calculates a shortened form of the commit message for use as a commit set * title @@ -534,111 +534,111 @@ public class CommitCommentArea extends DialogArea { return comment; } - public String getCommentWithPrompt(Shell shell) { - final String comment= getComment(false); - if (comment.length() == 0) { - final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore(); - final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); - - if (MessageDialogWithToggle.NEVER.equals(value)) - return null; - - if (MessageDialogWithToggle.PROMPT.equals(value)) { - - final String title= CVSUIMessages.CommitCommentArea_2; - final String message= CVSUIMessages.CommitCommentArea_3; - final String toggleMessage= CVSUIMessages.CommitCommentArea_4; - - final MessageDialogWithToggle dialog= MessageDialogWithToggle.openYesNoQuestion(shell, title, message, toggleMessage, false, store, ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); - if (dialog.getReturnCode() != IDialogConstants.YES_ID) { - fTextBox.setFocus(); - return null; - } - } - } - return getComment(true); - } + public String getCommentWithPrompt(Shell shell) { + final String comment= getComment(false); + if (comment.length() == 0) { + final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore(); + final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); + + if (MessageDialogWithToggle.NEVER.equals(value)) + return null; + + if (MessageDialogWithToggle.PROMPT.equals(value)) { + + final String title= CVSUIMessages.CommitCommentArea_2; + final String message= CVSUIMessages.CommitCommentArea_3; + final String toggleMessage= CVSUIMessages.CommitCommentArea_4; + + final MessageDialogWithToggle dialog= MessageDialogWithToggle.openYesNoQuestion(shell, title, message, toggleMessage, false, store, ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); + if (dialog.getReturnCode() != IDialogConstants.YES_ID) { + fTextBox.setFocus(); + return null; + } + } + } + return getComment(true); + } - - public void setProject(IProject iProject) { - this.fMainProject = iProject; - } - - public void setFocus() { - if (fTextBox != null) { - fTextBox.setFocus(); - } - } - - public void setProposedComment(String proposedComment) { - if (proposedComment == null || proposedComment.length() == 0) { - this.fProposedComment = null; - } else { - this.fProposedComment = proposedComment; - } - } - - public boolean hasCommitTemplate() { - try { - String commitTemplate = getCommitTemplate(); - return commitTemplate != null && commitTemplate.length() > 0; - } catch (CVSException e) { - CVSUIPlugin.log(e); - return false; - } - } - - public void setEnabled(boolean enabled) { - fTextBox.setEnabled(enabled); - fComboBox.setEnabled(enabled); - } - - public Composite getComposite() { - return fComposite; - } - - @Override + + public void setProject(IProject iProject) { + this.fMainProject = iProject; + } + + public void setFocus() { + if (fTextBox != null) { + fTextBox.setFocus(); + } + } + + public void setProposedComment(String proposedComment) { + if (proposedComment == null || proposedComment.length() == 0) { + this.fProposedComment = null; + } else { + this.fProposedComment = proposedComment; + } + } + + public boolean hasCommitTemplate() { + try { + String commitTemplate = getCommitTemplate(); + return commitTemplate != null && commitTemplate.length() > 0; + } catch (CVSException e) { + CVSUIPlugin.log(e); + return false; + } + } + + public void setEnabled(boolean enabled) { + fTextBox.setEnabled(enabled); + fComboBox.setEnabled(enabled); + } + + public Composite getComposite() { + return fComposite; + } + + @Override protected void firePropertyChangeChange(String property, Object oldValue, Object newValue) { - super.firePropertyChangeChange(property, oldValue, newValue); - } - - private String getInitialComment() { - if (fProposedComment != null) - return fProposedComment; - try { - return getCommitTemplate(); - } catch (CVSException e) { - CVSUIPlugin.log(e); - return ""; //$NON-NLS-1$ - } - } + super.firePropertyChangeChange(property, oldValue, newValue); + } + + private String getInitialComment() { + if (fProposedComment != null) + return fProposedComment; + try { + return getCommitTemplate(); + } catch (CVSException e) { + CVSUIPlugin.log(e); + return ""; //$NON-NLS-1$ + } + } - private String strip(String comment) { - // strip template from the comment entered - try { - final String commitTemplate = getCommitTemplate(); - if (comment.startsWith(commitTemplate)) { - return comment.substring(commitTemplate.length()); - } else if (comment.endsWith(commitTemplate)) { - return comment.substring(0, comment.length() - commitTemplate.length()); - } - } catch (CVSException e) { - // we couldn't get the commit template. Log the error and continue - CVSUIPlugin.log(e); - } - return comment; - } + private String strip(String comment) { + // strip template from the comment entered + try { + final String commitTemplate = getCommitTemplate(); + if (comment.startsWith(commitTemplate)) { + return comment.substring(commitTemplate.length()); + } else if (comment.endsWith(commitTemplate)) { + return comment.substring(0, comment.length() - commitTemplate.length()); + } + } catch (CVSException e) { + // we couldn't get the commit template. Log the error and continue + CVSUIPlugin.log(e); + } + return comment; + } - private CVSTeamProvider getProvider() { - if (fMainProject == null) return null; - return (CVSTeamProvider) RepositoryProvider.getProvider(fMainProject, CVSProviderPlugin.getTypeId()); - } + private CVSTeamProvider getProvider() { + if (fMainProject == null) return null; + return (CVSTeamProvider) RepositoryProvider.getProvider(fMainProject, CVSProviderPlugin.getTypeId()); + } - private String getCommitTemplate() throws CVSException { - CVSTeamProvider provider = getProvider(); - if (provider == null) - return ""; //$NON-NLS-1$ - final String template = provider.getCommitTemplate(); - return template != null ? template : ""; //$NON-NLS-1$ - } + private String getCommitTemplate() throws CVSException { + CVSTeamProvider provider = getProvider(); + if (provider == null) + return ""; //$NON-NLS-1$ + final String template = provider.getCommitTemplate(); + return template != null ? template : ""; //$NON-NLS-1$ + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ComparePreferencePage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ComparePreferencePage.java index 7afbdffcc..b64c43095 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ComparePreferencePage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ComparePreferencePage.java @@ -29,17 +29,17 @@ public class ComparePreferencePage extends CVSFieldEditorPreferencePage { private BooleanFieldEditor contents; private StringFieldEditor regex; - @Override + @Override protected String getPageHelpContextId() { - return IHelpContextIds.COMPARE_PREFERENCE_PAGE; - } + return IHelpContextIds.COMPARE_PREFERENCE_PAGE; + } - @Override + @Override protected String getPageDescription() { - return CVSUIMessages.ComparePreferencePage_0; - } + return CVSUIMessages.ComparePreferencePage_0; + } - @Override + @Override protected void createFieldEditors() { IPreferenceStore store = getPreferenceStore(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/DateTagDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/DateTagDialog.java index e7e8ac95c..96998e0fe 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/DateTagDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/DateTagDialog.java @@ -161,7 +161,7 @@ public class DateTagDialog extends TrayDialog { updateWidgetEnablements(); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(topLevel, IHelpContextIds.DATE_TAG_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(topLevel, IHelpContextIds.DATE_TAG_DIALOG); Dialog.applyDialogFont(parent); return topLevel; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsDialog.java index 0adfb8051..56f1b3e4c 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsDialog.java @@ -54,7 +54,7 @@ public class EditorsDialog extends TrayDialog { editorsView.setInput(editorsInfo); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IHelpContextIds.EDITORS_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IHelpContextIds.EDITORS_DIALOG); Dialog.applyDialogFont(parent); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsView.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsView.java index 158a89372..c9b45d214 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsView.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/EditorsView.java @@ -209,7 +209,7 @@ public class EditorsView extends ViewPart { tableViewer.setContentProvider(ArrayContentProvider.getInstance()); tableViewer.setLabelProvider(new EditorsLabelProvider()); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(tableViewer.getControl(), IHelpContextIds.CVS_EDITORS_VIEW); + PlatformUI.getWorkbench().getHelpSystem().setHelp(tableViewer.getControl(), IHelpContextIds.CVS_EDITORS_VIEW); } public void setInput(EditorsInfo[] infos) { tableViewer.setInput(infos); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ExtMethodPreferencePage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ExtMethodPreferencePage.java index 5c1a2afa1..2ee5879ef 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ExtMethodPreferencePage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ExtMethodPreferencePage.java @@ -105,7 +105,7 @@ public class ExtMethodPreferencePage extends PreferencePage implements IWorkbenc ssh2Link.getControl().setLayoutData(data); initializeDefaults(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.EXT_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.EXT_PREFERENCE_PAGE); Dialog.applyDialogFont(parent); return composite; } @@ -192,9 +192,9 @@ public class ExtMethodPreferencePage extends PreferencePage implements IWorkbenc data.horizontalAlignment = GridData.FILL; cvsServer.setLayoutData(data); - PlatformUI.getWorkbench().getHelpSystem().setHelp(cvsRsh, IHelpContextIds.EXT_PREFERENCE_RSH); - PlatformUI.getWorkbench().getHelpSystem().setHelp(cvsRshParameters, IHelpContextIds.EXT_PREFERENCE_PARAM); - PlatformUI.getWorkbench().getHelpSystem().setHelp(cvsServer, IHelpContextIds.EXT_PREFERENCE_SERVER); + PlatformUI.getWorkbench().getHelpSystem().setHelp(cvsRsh, IHelpContextIds.EXT_PREFERENCE_RSH); + PlatformUI.getWorkbench().getHelpSystem().setHelp(cvsRshParameters, IHelpContextIds.EXT_PREFERENCE_PARAM); + PlatformUI.getWorkbench().getHelpSystem().setHelp(cvsServer, IHelpContextIds.EXT_PREFERENCE_SERVER); return composite; } @@ -210,9 +210,9 @@ public class ExtMethodPreferencePage extends PreferencePage implements IWorkbenc /* * Set CVS_RSH program */ - protected void setCvsRshText(String s) { - cvsRsh.setText(s); - } + protected void setCvsRshText(String s) { + cvsRsh.setText(s); + } @Override public void init(IWorkbench workbench) { @@ -238,19 +238,19 @@ public class ExtMethodPreferencePage extends PreferencePage implements IWorkbenc CVSUIPlugin.getPlugin().savePluginPreferences(); return super.performOk(); } - - @Override + + @Override protected void performDefaults() { - IPreferenceStore store = getPreferenceStore(); + IPreferenceStore store = getPreferenceStore(); String rsh = store.getDefaultString(ICVSUIConstants.PREF_CVS_RSH); String parameter = store.getDefaultString(ICVSUIConstants.PREF_CVS_RSH_PARAMETERS); String server = store.getDefaultString(ICVSUIConstants.PREF_CVS_SERVER); String method = store.getDefaultString(ICVSUIConstants.PREF_EXT_CONNECTION_METHOD_PROXY); initializeDefaults(rsh, parameter, server, method); - super.performDefaults(); - } - - private void initializeDefaults(String rsh, String parameters, String server, String method) { + super.performDefaults(); + } + + private void initializeDefaults(String rsh, String parameters, String server, String method) { cvsRsh.setText(rsh); cvsRshParameters.setText(parameters); cvsServer.setText(server); @@ -269,8 +269,8 @@ public class ExtMethodPreferencePage extends PreferencePage implements IWorkbenc useExternal.setSelection(method.equals("ext")); //$NON-NLS-1$ useInternal.setSelection(!method.equals("ext")); //$NON-NLS-1$ updateEnablements(); - } - + } + @Override protected IPreferenceStore doGetPreferenceStore() { return CVSUIPlugin.getPlugin().getPreferenceStore(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/FileModificationValidator.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/FileModificationValidator.java index 1dc8cb7b5..3941ece06 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/FileModificationValidator.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/FileModificationValidator.java @@ -45,11 +45,11 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator public FileModificationValidator() { } - @Override + @Override protected IStatus edit(IFile[] readOnlyFiles, FileModificationValidationContext context) { - return edit(readOnlyFiles, getShell(context)); - } - + return edit(readOnlyFiles, getShell(context)); + } + private Shell getShell(FileModificationValidationContext context) { if (context == null) return null; @@ -77,24 +77,24 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator throw new InterruptedException(); } - // see if the file is up to date - if (shell != null && promptToUpdateFiles(files, shell)) { - // The user wants to update the file - // Run the update in a runnable in order to get a busy cursor. - // This runnable is syncExeced in order to get a busy cursor + // see if the file is up to date + if (shell != null && promptToUpdateFiles(files, shell)) { + // The user wants to update the file + // Run the update in a runnable in order to get a busy cursor. + // This runnable is syncExeced in order to get a busy cursor IRunnableWithProgress updateRunnable = monitor -> performUpdate(files, monitor); - if (isRunningInUIThread()) { - // Only show a busy cursor if validate edit is blocking the UI - CVSUIPlugin.runWithProgress(shell, false, updateRunnable); - } else { - // We can't show a busy cursor (i.e., run in the UI thread) - // since this thread may hold locks and - // running an edit in the UI thread could try to obtain the - // same locks, resulting in a deadlock. - updateRunnable.run(new NullProgressMonitor()); - } - } - + if (isRunningInUIThread()) { + // Only show a busy cursor if validate edit is blocking the UI + CVSUIPlugin.runWithProgress(shell, false, updateRunnable); + } else { + // We can't show a busy cursor (i.e., run in the UI thread) + // since this thread may hold locks and + // running an edit in the UI thread could try to obtain the + // same locks, resulting in a deadlock. + updateRunnable.run(new NullProgressMonitor()); + } + } + // Run the edit in a runnable in order to get a busy cursor. // This runnable is syncExeced in order to get a busy cursor IRunnableWithProgress editRunnable = monitor -> { @@ -105,14 +105,14 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator } }; if (isRunningInUIThread()) { - // Only show a busy cursor if validate edit is blocking the UI - CVSUIPlugin.runWithProgress(shell, false, editRunnable); + // Only show a busy cursor if validate edit is blocking the UI + CVSUIPlugin.runWithProgress(shell, false, editRunnable); } else { - // We can't show a busy cursor (i.e., run in the UI thread) - // since this thread may hold locks and - // running an edit in the UI thread could try to obtain the - // same locks, resulting in a deadlock. - editRunnable.run(new NullProgressMonitor()); + // We can't show a busy cursor (i.e., run in the UI thread) + // since this thread may hold locks and + // running an edit in the UI thread could try to obtain the + // same locks, resulting in a deadlock. + editRunnable.run(new NullProgressMonitor()); } } catch (InvocationTargetException e) { return getStatus(e); @@ -120,11 +120,11 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator // Must return an error to indicate that it is not OK to edit the files return new Status(IStatus.CANCEL, CVSUIPlugin.ID, 0, CVSUIMessages.FileModificationValidator_vetoMessage, null); //; } - } else if (isPerformEditInBackground()) { - IStatus status = setWritable(files); - if (status.isOK()) - performEdit(files); - return status; + } else if (isPerformEditInBackground()) { + IStatus status = setWritable(files); + if (status.isOK()) + performEdit(files); + return status; } else { // Allow the files to be edited without notifying the server return setWritable(files); @@ -133,23 +133,23 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator return Status.OK_STATUS; } - - @Override + + @Override protected void scheduleEditJob(Job job) { - job.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); - job.setProperty(IProgressConstants.ICON_PROPERTY, getOperationIcon()); - super.scheduleEditJob(job); - } - - private URL getOperationIcon() { - return FileLocator.find(CVSUIPlugin.getPlugin().getBundle(), new Path(ICVSUIConstants.ICON_PATH + ICVSUIConstants.IMG_CVS_PERSPECTIVE), null); - } - - private boolean isRunningInUIThread() { - return Display.getCurrent() != null; - } + job.setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); + job.setProperty(IProgressConstants.ICON_PROPERTY, getOperationIcon()); + super.scheduleEditJob(job); + } + + private URL getOperationIcon() { + return FileLocator.find(CVSUIPlugin.getPlugin().getBundle(), new Path(ICVSUIConstants.ICON_PATH + ICVSUIConstants.IMG_CVS_PERSPECTIVE), null); + } + + private boolean isRunningInUIThread() { + return Display.getCurrent() != null; + } - private boolean promptToEditFiles(IFile[] files, Shell shell) throws InvocationTargetException, InterruptedException { + private boolean promptToEditFiles(IFile[] files, Shell shell) throws InvocationTargetException, InterruptedException { if (files.length == 0) return true; @@ -167,22 +167,22 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator } } - private boolean promptToUpdateFiles(IFile[] files, Shell shell) throws InvocationTargetException, InterruptedException { - if (files.length == 0) - return false; - - if (isNeverUpdate()) - return false; - - // Contact the server to see if the files are up-to-date - if (needsUpdate(files, new NullProgressMonitor())) { - if (isPromptUpdate()) - return (promptUpdate(shell)); - return true; // auto update - } - - return false; - } + private boolean promptToUpdateFiles(IFile[] files, Shell shell) throws InvocationTargetException, InterruptedException { + if (files.length == 0) + return false; + + if (isNeverUpdate()) + return false; + + // Contact the server to see if the files are up-to-date + if (needsUpdate(files, new NullProgressMonitor())) { + if (isPromptUpdate()) + return (promptUpdate(shell)); + return true; // auto update + } + + return false; + } private boolean promptEdit(Shell shell) { // Open the dialog using a sync exec (there are no guarantees that we @@ -197,39 +197,39 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator return result[0]; } - private boolean promptUpdate(Shell shell) { - // Open the dialog using a sync exec (there are no guarantees that we - // were called from the UI thread - final boolean[] result = new boolean[] { false }; - int flags = isRunningInUIThread() ? 0 : CVSUIPlugin.PERFORM_SYNC_EXEC; + private boolean promptUpdate(Shell shell) { + // Open the dialog using a sync exec (there are no guarantees that we + // were called from the UI thread + final boolean[] result = new boolean[] { false }; + int flags = isRunningInUIThread() ? 0 : CVSUIPlugin.PERFORM_SYNC_EXEC; CVSUIPlugin .openDialog(shell, shell1 -> result[0] = MessageDialog.openQuestion(shell1, CVSUIMessages.FileModificationValidator_5, CVSUIMessages.FileModificationValidator_6), flags); - return result[0]; - } + return result[0]; + } private boolean isPerformEdit() { return ICVSUIConstants.PREF_EDIT_PROMPT_EDIT.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_EDIT_ACTION)); } - - private boolean isPerformEditInBackground() { - return ICVSUIConstants.PREF_EDIT_IN_BACKGROUND.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_EDIT_ACTION)); - } + + private boolean isPerformEditInBackground() { + return ICVSUIConstants.PREF_EDIT_IN_BACKGROUND.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_EDIT_ACTION)); + } private EditorsAction fetchEditors(IFile[] files, Shell shell) throws InvocationTargetException, InterruptedException { final EditorsAction editors = new EditorsAction(getProvider(files), files); IRunnableWithProgress runnable = monitor -> editors.run(monitor); if (isRunningInUIThread()) { - // Show a busy cursor if we are running in the UI thread - CVSUIPlugin.runWithProgress(shell, false, runnable); + // Show a busy cursor if we are running in the UI thread + CVSUIPlugin.runWithProgress(shell, false, runnable); } else { - // We can't show a busy cursor (i.e., run in the UI thread) - // since this thread may hold locks and - // running a CVS operation in the UI thread could try to obtain the - // same locks, resulting in a deadlock. - runnable.run(new NullProgressMonitor()); + // We can't show a busy cursor (i.e., run in the UI thread) + // since this thread may hold locks and + // running a CVS operation in the UI thread could try to obtain the + // same locks, resulting in a deadlock. + runnable.run(new NullProgressMonitor()); } return editors; } @@ -241,51 +241,51 @@ public class FileModificationValidator extends CVSCoreFileModificationValidator private boolean isAlwaysPrompt() { return ICVSUIConstants.PREF_EDIT_PROMPT_ALWAYS.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_EDIT_PROMPT)); } - - private boolean needsUpdate(IFile[] files, IProgressMonitor monitor) { - try { - CVSWorkspaceSubscriber subscriber = CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); - subscriber.refresh(files, IResource.DEPTH_ZERO, monitor); - for (int i = 0; i < files.length; i++) { - IFile file = files[i]; - SyncInfo info = subscriber.getSyncInfo(file); - int direction = info.getKind() & SyncInfo.DIRECTION_MASK; - if (direction == SyncInfo.CONFLICTING || direction == SyncInfo.INCOMING) { - return true; - } - } - } catch (TeamException e) { - // Log the exception and assume we don't need to update it - CVSProviderPlugin.log(e); - } - return false; - } - - private void performUpdate(IFile[] files, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - // TODO: This obtains the project rule which can cause a rule violation - new UpdateOperation(null /* no target part */, files, Command.NO_LOCAL_OPTIONS, null /* no tag */).run(monitor); - } - - private boolean isPromptUpdate() { - return ICVSUIConstants.PREF_UPDATE_PROMPT_IF_OUTDATED.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_UPDATE_PROMPT)); - } - - private boolean isNeverUpdate() { - return ICVSUIConstants.PREF_UPDATE_PROMPT_NEVER.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_UPDATE_PROMPT)); - } - - @Override + + private boolean needsUpdate(IFile[] files, IProgressMonitor monitor) { + try { + CVSWorkspaceSubscriber subscriber = CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); + subscriber.refresh(files, IResource.DEPTH_ZERO, monitor); + for (int i = 0; i < files.length; i++) { + IFile file = files[i]; + SyncInfo info = subscriber.getSyncInfo(file); + int direction = info.getKind() & SyncInfo.DIRECTION_MASK; + if (direction == SyncInfo.CONFLICTING || direction == SyncInfo.INCOMING) { + return true; + } + } + } catch (TeamException e) { + // Log the exception and assume we don't need to update it + CVSProviderPlugin.log(e); + } + return false; + } + + private void performUpdate(IFile[] files, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + // TODO: This obtains the project rule which can cause a rule violation + new UpdateOperation(null /* no target part */, files, Command.NO_LOCAL_OPTIONS, null /* no tag */).run(monitor); + } + + private boolean isPromptUpdate() { + return ICVSUIConstants.PREF_UPDATE_PROMPT_IF_OUTDATED.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_UPDATE_PROMPT)); + } + + private boolean isNeverUpdate() { + return ICVSUIConstants.PREF_UPDATE_PROMPT_NEVER.equals(CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_UPDATE_PROMPT)); + } + + @Override public ISchedulingRule validateEditRule(CVSResourceRuleFactory factory, IResource[] resources) { - if (!isNeverUpdate()) { - // We may need to perform an update so we need to obtain the lock on each project - Set projects = new HashSet(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - if (isReadOnly(resource)) - projects.add(resource.getProject()); - } - return createSchedulingRule(projects); - } - return internalValidateEditRule(factory, resources); - } + if (!isNeverUpdate()) { + // We may need to perform an update so we need to obtain the lock on each project + Set projects = new HashSet(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + if (isReadOnly(resource)) + projects.add(resource.getProject()); + } + return createSchedulingRule(projects); + } + return internalValidateEditRule(factory, resources); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/HistoryTableProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/HistoryTableProvider.java index 3e43a48e4..30334fc91 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/HistoryTableProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/HistoryTableProvider.java @@ -409,7 +409,7 @@ public class HistoryTableProvider { */ private SelectionListener getColumnListener(final TableViewer tableViewer) { /** - * This class handles selections of the column headers. + * This class handles selections of the column headers. * Selection of the column header will cause resorting * of the shown tasks using that column's sorter. * Repeated selection of the header will toggle diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ICVSUIConstants.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ICVSUIConstants.java index 0a3551b83..1d64b5945 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ICVSUIConstants.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ICVSUIConstants.java @@ -48,8 +48,8 @@ public interface ICVSUIConstants { public final String IMG_CHANGELOG = "obj16/changelog_obj.gif"; //$NON-NLS-1$ public final String IMG_LOCALREVISION_TABLE = "obj16/local_entry_tbl.gif"; //$NON-NLS-1$ - public final String IMG_REMOTEREVISION_TABLE = "obj16/remote_entry_tbl.gif"; //$NON-NLS-1$ - + public final String IMG_REMOTEREVISION_TABLE = "obj16/remote_entry_tbl.gif"; //$NON-NLS-1$ + // toolbar public final String IMG_REFRESH = "elcl16/refresh.gif"; //$NON-NLS-1$ public final String IMG_CLEAR = "elcl16/clear_co.gif"; //$NON-NLS-1$ @@ -119,17 +119,17 @@ public interface ICVSUIConstants { public final String PREF_SHOW_AUTHOR_IN_EDITOR = "pref_show_author_in_editor"; //$NON-NLS-1$ public final String PREF_COMMIT_SET_DEFAULT_ENABLEMENT = "pref_enable_commit_sets"; //$NON-NLS-1$ public final String PREF_AUTO_REFRESH_TAGS_IN_TAG_SELECTION_DIALOG = "pref_auto_refresh_tags_in_tag_selection_dialog"; //$NON-NLS-1$ - public final String PREF_COMMIT_FILES_DISPLAY_THRESHOLD = "pref_commit_files_display_threshold"; //$NON-NLS-1$ - public final String PREF_COMMIT_COMMENTS_MAX_HISTORY = "pref_commit_comments_max_history"; //$NON-NLS-1$ - public final String PREF_AUTO_SHARE_ON_IMPORT = "pref_auto_share_on_import"; //$NON-NLS-1$ + public final String PREF_COMMIT_FILES_DISPLAY_THRESHOLD = "pref_commit_files_display_threshold"; //$NON-NLS-1$ + public final String PREF_COMMIT_COMMENTS_MAX_HISTORY = "pref_commit_comments_max_history"; //$NON-NLS-1$ + public final String PREF_AUTO_SHARE_ON_IMPORT = "pref_auto_share_on_import"; //$NON-NLS-1$ public final String PREF_ENABLE_WATCH_ON_EDIT = "pref_enable_watch_on_edit"; //$NON-NLS-1$ - public final String PREF_USE_PROJECT_NAME_ON_CHECKOUT = "pref_use_project_name_on_checkout"; //$NON-NLS-1$ - public final String PREF_INCLUDE_CHANGE_SETS_IN_COMMIT = "pref_include_change_sets"; //$NON-NLS-1$ - public final String PREF_ANNOTATE_PROMPTFORBINARY = "pref_annotate_promptforbinary"; //$NON-NLS-1$ - public final String PREF_ALLOW_COMMIT_WITH_WARNINGS = "pref_commit_with_warning"; //$NON-NLS-1$ - public final String PREF_ALLOW_COMMIT_WITH_ERRORS = "pref_commit_with_errors"; //$NON-NLS-1$ - - + public final String PREF_USE_PROJECT_NAME_ON_CHECKOUT = "pref_use_project_name_on_checkout"; //$NON-NLS-1$ + public final String PREF_INCLUDE_CHANGE_SETS_IN_COMMIT = "pref_include_change_sets"; //$NON-NLS-1$ + public final String PREF_ANNOTATE_PROMPTFORBINARY = "pref_annotate_promptforbinary"; //$NON-NLS-1$ + public final String PREF_ALLOW_COMMIT_WITH_WARNINGS = "pref_commit_with_warning"; //$NON-NLS-1$ + public final String PREF_ALLOW_COMMIT_WITH_ERRORS = "pref_commit_with_errors"; //$NON-NLS-1$ + + // console preferences public final String PREF_CONSOLE_COMMAND_COLOR = "pref_console_command_color"; //$NON-NLS-1$ public final String PREF_CONSOLE_MESSAGE_COLOR = "pref_console_message_color"; //$NON-NLS-1$ @@ -162,17 +162,17 @@ public interface ICVSUIConstants { public final String PREF_EDIT_ACTION = "pref_edit_action"; //$NON-NLS-1$ public final String PREF_EDIT_PROMPT_EDIT = "edit"; //$NON-NLS-1$ public final String PREF_EDIT_PROMPT_HIGHJACK = "highjack"; //$NON-NLS-1$ - public final String PREF_EDIT_IN_BACKGROUND = "editInBackground"; //$NON-NLS-1$ + public final String PREF_EDIT_IN_BACKGROUND = "editInBackground"; //$NON-NLS-1$ public final String PREF_EDIT_PROMPT = "pref_edit_prompt"; //$NON-NLS-1$ public final String PREF_EDIT_PROMPT_NEVER = "never"; //$NON-NLS-1$ public final String PREF_EDIT_PROMPT_ALWAYS = "always"; //$NON-NLS-1$ public final String PREF_EDIT_PROMPT_IF_EDITORS = "only"; //$NON-NLS-1$ - - // update preferences - public final String PREF_UPDATE_PROMPT = "pref_update_prompt"; //$NON-NLS-1$ - public final String PREF_UPDATE_PROMPT_NEVER = "never"; //$NON-NLS-1$ - public final String PREF_UPDATE_PROMPT_AUTO = "auto"; //$NON-NLS-1$ - public final String PREF_UPDATE_PROMPT_IF_OUTDATED = "only"; //$NON-NLS-1$ + + // update preferences + public final String PREF_UPDATE_PROMPT = "pref_update_prompt"; //$NON-NLS-1$ + public final String PREF_UPDATE_PROMPT_NEVER = "never"; //$NON-NLS-1$ + public final String PREF_UPDATE_PROMPT_AUTO = "auto"; //$NON-NLS-1$ + public final String PREF_UPDATE_PROMPT_IF_OUTDATED = "only"; //$NON-NLS-1$ // Repositories view preferences public final String PREF_GROUP_VERSIONS_BY_PROJECT = "pref_group_versions_by_project"; //$NON-NLS-1$ @@ -192,7 +192,7 @@ public interface ICVSUIConstants { public final String PREF_ENABLE_MODEL_SYNC = "enableModelSync"; //$NON-NLS-1$ public final String PREF_OPEN_COMPARE_EDITOR_FOR_SINGLE_FILE = "openCompareEditorForSingleFile"; //$NON-NLS-1$ - + // Wizard banners public final String IMG_WIZBAN_SHARE = "wizban/newconnect_wizban.png"; //$NON-NLS-1$ public final String IMG_WIZBAN_MERGE = "wizban/mergestream_wizban.png"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IHelpContextIds.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IHelpContextIds.java index 5d97decff..019345df0 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IHelpContextIds.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IHelpContextIds.java @@ -35,9 +35,9 @@ public interface IHelpContextIds { public static final String DATE_TAG_DIALOG = PREFIX + "date_tag_dialog_context"; //$NON-NLS-1$ public static final String KEYBOARD_INTERACTIVE_DIALOG = PREFIX + "keyboard_interactive_dialog_context"; //$NON-NLS-1$ public static final String COMMIT_SET_DIALOG = PREFIX + "commit_set_dialog_context"; //$NON-NLS-1$ - public static final String TAG_UNCOMMITED_PROMPT = PREFIX + "tag_uncommmited_dialog_context"; //$NON-NLS-1$ - public static final String ALTERNATIVE_REPOSITORY_DIALOG = PREFIX + "alternative_repository_dialog_context"; //$NON-NLS-1$ - public static final String REPOSITORY_FILTER_DIALOG = PREFIX + "repository_filter_dialog_context"; //$NON-NLS-1$ + public static final String TAG_UNCOMMITED_PROMPT = PREFIX + "tag_uncommmited_dialog_context"; //$NON-NLS-1$ + public static final String ALTERNATIVE_REPOSITORY_DIALOG = PREFIX + "alternative_repository_dialog_context"; //$NON-NLS-1$ + public static final String REPOSITORY_FILTER_DIALOG = PREFIX + "repository_filter_dialog_context"; //$NON-NLS-1$ // Different uses of the TagSelectionDialog public static final String REPLACE_TAG_SELECTION_DIALOG = PREFIX + "replace_tag_selection_dialog_context"; //$NON-NLS-1$ @@ -64,7 +64,7 @@ public interface IHelpContextIds { public static final String KEYWORD_SUBSTITUTION_PAGE = PREFIX + "keyword_substitution_page_context"; //$NON-NLS-1$ - public static final String MERGE_WIZARD_PAGE = PREFIX + "merge_wizard_page_context"; //$NON-NLS-1$ + public static final String MERGE_WIZARD_PAGE = PREFIX + "merge_wizard_page_context"; //$NON-NLS-1$ public static final String MERGE_START_PAGE = PREFIX + "merge_start_page_context"; //$NON-NLS-1$ public static final String MERGE_END_PAGE = PREFIX + "merge_end_page_context"; //$NON-NLS-1$ @@ -79,9 +79,9 @@ public interface IHelpContextIds { public static final String RESTORE_FROM_REPOSITORY_FILE_SELECTION_PAGE = PREFIX + "restore_from_repository_file_selection_page_context"; //$NON-NLS-1$ public static final String REFRESH_REMOTE_PROJECT_SELECTION_PAGE = PREFIX + "refresh_remote_project_selection_page_context"; //$NON-NLS-1$ - public static final String COMMIT_FILE_TYPES_PAGE = PREFIX + "commit_file_types_page_context"; //$NON-NLS-1$ - public static final String COMMIT_COMMENT_PAGE = PREFIX + "commit_comment_page_context"; //$NON-NLS-1$ - + public static final String COMMIT_FILE_TYPES_PAGE = PREFIX + "commit_file_types_page_context"; //$NON-NLS-1$ + public static final String COMMIT_COMMENT_PAGE = PREFIX + "commit_comment_page_context"; //$NON-NLS-1$ + public static final String CVS_SCM_URL_IMPORT_PAGE = PREFIX + "cvs_scm_url_import_page"; //$NON-NLS-1$ // Preference Pages @@ -104,10 +104,10 @@ public interface IHelpContextIds { public static final String PREF_CONFIRM_MOVE_TAG = PREFIX + "confirm_move_tag"; //$NON-NLS-1$ public static final String PREF_AUTOREFRESH_TAG = PREFIX + "auto_refresh_tag"; //$NON-NLS-1$ - public static final String GENERAL_PREFERENCE_PAGE = PREFIX + "general_preference_page_context"; //$NON-NLS-1$ + public static final String GENERAL_PREFERENCE_PAGE = PREFIX + "general_preference_page_context"; //$NON-NLS-1$ public static final String CONSOLE_PREFERENCE_PAGE = PREFIX + "console_preference_page_context"; //$NON-NLS-1$ public static final String EXT_PREFERENCE_PAGE = PREFIX + "ext_preference_page_context"; //$NON-NLS-1$ - public static final String SSH2_PREFERENCE_PAGE = PREFIX + "ssh2_preference_page_context"; //$NON-NLS-1$ + public static final String SSH2_PREFERENCE_PAGE = PREFIX + "ssh2_preference_page_context"; //$NON-NLS-1$ public static final String EXT_PREFERENCE_RSH = PREFIX + "ext_preference_rsh_context"; //$NON-NLS-1$ public static final String EXT_PREFERENCE_PARAM = PREFIX + "ext_preference_param_context"; //$NON-NLS-1$ public static final String EXT_PREFERENCE_SERVER = PREFIX + "ext_preference_server_context"; //$NON-NLS-1$ @@ -115,9 +115,9 @@ public interface IHelpContextIds { public static final String WATCH_EDIT_PREFERENCE_PAGE = PREFIX + "watch_edit_preference_page_context"; //$NON-NLS-1$ public static final String PASSWORD_MANAGEMENT_PAGE = PREFIX + "password_management_preference_page_context"; //$NON-NLS-1$ public static final String COMPARE_PREFERENCE_PAGE = PREFIX + "cvs_compare_preference_page_context"; //$NON-NLS-1$ - public static final String PROXY_PREFERENCE_PAGE = PREFIX + "proxy_preference_page_context"; //$NON-NLS-1$ - public static final String COMMENT_TEMPLATE_PREFERENCE_PAGE = PREFIX + "comment_template_preference_page_context"; //$NON-NLS-1$ - public static final String UPDATE_MERGE_PREFERENCE_PAGE = PREFIX + "update_merge_preference_page_context"; //$NON-NLS-1$ + public static final String PROXY_PREFERENCE_PAGE = PREFIX + "proxy_preference_page_context"; //$NON-NLS-1$ + public static final String COMMENT_TEMPLATE_PREFERENCE_PAGE = PREFIX + "comment_template_preference_page_context"; //$NON-NLS-1$ + public static final String UPDATE_MERGE_PREFERENCE_PAGE = PREFIX + "update_merge_preference_page_context"; //$NON-NLS-1$ // Views public static final String CONSOLE_VIEW = PREFIX + "console_view_context"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IgnoreResourcesDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IgnoreResourcesDialog.java index d82a0d188..cdc1748cc 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IgnoreResourcesDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/IgnoreResourcesDialog.java @@ -50,14 +50,14 @@ public class IgnoreResourcesDialog extends TitleAreaDialog { // layout controls private static final int LABEL_INDENT_WIDTH = 32; - /** - * Image for title area - */ - private Image dlgTitleImage = null; - - // to avoid an error/warning message at startup default values are as below - private boolean resourceWithSpaces = false; - private boolean allResourecesHaveExtensions = true; + /** + * Image for title area + */ + private Image dlgTitleImage = null; + + // to avoid an error/warning message at startup default values are as below + private boolean resourceWithSpaces = false; + private boolean allResourecesHaveExtensions = true; private boolean allResourcesWithSpacesHaveExtensions = true; /** @@ -143,7 +143,7 @@ public class IgnoreResourcesDialog extends TitleAreaDialog { top.setLayout(layout); top.setLayoutData(new GridData(GridData.FILL_BOTH)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(top, IHelpContextIds.ADD_TO_CVSIGNORE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(top, IHelpContextIds.ADD_TO_CVSIGNORE); Listener selectionListener = event -> updateEnablements(); Listener modifyListener = event -> validate(); @@ -202,7 +202,7 @@ public class IgnoreResourcesDialog extends TitleAreaDialog { addCustomEntryButton.setSelection(true); selectedAction = ADD_CUSTOM_ENTRY; } - + } else { customEntryText = createIndentedText(top, resources[0].getName(), LABEL_INDENT_WIDTH); @@ -353,11 +353,11 @@ public class IgnoreResourcesDialog extends TitleAreaDialog { return false; } - @Override + @Override public boolean close() { - if (dlgTitleImage != null) { + if (dlgTitleImage != null) { dlgTitleImage.dispose(); } - return super.close(); - } + return super.close(); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/KeyboardInteractiveDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/KeyboardInteractiveDialog.java index ecd1ecc1d..b9c3d6c69 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/KeyboardInteractiveDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/KeyboardInteractiveDialog.java @@ -33,65 +33,65 @@ import org.eclipse.ui.PlatformUI; * A dialog for keyboard-interactive authentication for the ssh2 connection. */ public class KeyboardInteractiveDialog extends TrayDialog { - // widgets - private Text[] texts; - protected Image keyLockImage; - protected Button allowCachingButton; - protected Text usernameField; + // widgets + private Text[] texts; + protected Image keyLockImage; + protected Button allowCachingButton; + protected Text usernameField; - protected String userName; - protected String domain; - protected String destination; - protected String name; - protected String instruction; - protected String lang; - protected String[] prompt; - protected boolean[] echo; - private String message; - private String[] result; - protected boolean allowCaching=false; - private boolean cachingDialog=false; - - private boolean isPasswordAuth=false; + protected String userName; + protected String domain; + protected String destination; + protected String name; + protected String instruction; + protected String lang; + protected String[] prompt; + protected boolean[] echo; + private String message; + private String[] result; + protected boolean allowCaching=false; + private boolean cachingDialog=false; + + private boolean isPasswordAuth=false; - /** - * Creates a new KeyboardInteractiveDialog. - * - * @param parentShell the parent shell - * @param destication the location - * @param name the name - * @param instruction the instruction - * @param prompt the titles for text fields - * @param echo '*' should be used or not - */ - public KeyboardInteractiveDialog(Shell parentShell, - String location, - String destination, - String name, - String userName, - String instruction, - String[] prompt, - boolean[] echo, - boolean cachingDialog){ - super(parentShell); - this.domain=location; - this.destination=destination; - this.name=name; - this.userName=userName; - this.instruction=instruction; - this.prompt=prompt; - this.echo=echo; - this.cachingDialog=cachingDialog; - - this.message=NLS.bind(CVSUIMessages.KeyboradInteractiveDialog_message, new String[] { destination+(name!=null && name.length()>0 ? ": "+name : "") }); //NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-2$ - - if(KeyboardInteractiveDialog.isPasswordAuth(prompt)){ - isPasswordAuth=true; - } - } + /** + * Creates a new KeyboardInteractiveDialog. + * + * @param parentShell the parent shell + * @param destication the location + * @param name the name + * @param instruction the instruction + * @param prompt the titles for text fields + * @param echo '*' should be used or not + */ + public KeyboardInteractiveDialog(Shell parentShell, + String location, + String destination, + String name, + String userName, + String instruction, + String[] prompt, + boolean[] echo, + boolean cachingDialog){ + super(parentShell); + this.domain=location; + this.destination=destination; + this.name=name; + this.userName=userName; + this.instruction=instruction; + this.prompt=prompt; + this.echo=echo; + this.cachingDialog=cachingDialog; + + this.message=NLS.bind(CVSUIMessages.KeyboradInteractiveDialog_message, new String[] { destination+(name!=null && name.length()>0 ? ": "+name : "") }); //NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-2$ + + if(KeyboardInteractiveDialog.isPasswordAuth(prompt)){ + isPasswordAuth=true; + } + } - @Override + @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); if (isPasswordAuth) { @@ -105,7 +105,7 @@ protected void configureShell(Shell newShell) { IHelpContextIds.KEYBOARD_INTERACTIVE_DIALOG); } - @Override + @Override public void create() { super.create(); @@ -119,7 +119,7 @@ public void create() { } } - @Override + @Override protected Control createDialogArea(Composite parent) { Composite top = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); @@ -209,106 +209,106 @@ protected Control createDialogArea(Composite parent) { Dialog.applyDialogFont(parent); return main; } - - /** - * Creates the three widgets that represent the user name entry area. - * - * @param parent the parent of the widgets - */ - protected void createUsernameFields(Composite parent){ - new Label(parent, SWT.NONE).setText(CVSUIMessages.UserValidationDialog_user); + + /** + * Creates the three widgets that represent the user name entry area. + * + * @param parent the parent of the widgets + */ + protected void createUsernameFields(Composite parent){ + new Label(parent, SWT.NONE).setText(CVSUIMessages.UserValidationDialog_user); - usernameField=new Text(parent, SWT.BORDER); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - usernameField.setLayoutData(data); - } - - /** + usernameField=new Text(parent, SWT.BORDER); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + usernameField.setLayoutData(data); + } + + /** * Creates the widgets that represent the entry area. * * @param parent * the parent of the widgets */ - protected void createPasswordFields(Composite parent) { - texts=new Text[prompt.length]; + protected void createPasswordFields(Composite parent) { + texts=new Text[prompt.length]; - for(int i=0; i<prompt.length; i++){ - new Label(parent, SWT.NONE).setText(prompt[i]); - texts[i]=new Text(parent, SWT.BORDER|SWT.PASSWORD); - GridData data=new GridData(GridData.FILL_HORIZONTAL); - data.horizontalSpan=2; - data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); - texts[i].setLayoutData(data); - if(!echo[i]){ - texts[i].setEchoChar('*'); - } - } - } - /** - * Returns the entered values, or null - * if the user canceled. - * - * @return the entered values - */ - public String[] getResult() { - return result; - } - - /** - * Returns <code>true</code> if the save password checkbox was selected. - * @return <code>true</code> if the save password checkbox was selected and <code>false</code> - * otherwise. - */ - public boolean getAllowCaching(){ - return allowCaching; - } - - /** - * Notifies that the ok button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets - * this dialog's return code to <code>Window.OK</code> - * and closes the dialog. Subclasses may override. - * </p> - */ - @Override + for(int i=0; i<prompt.length; i++){ + new Label(parent, SWT.NONE).setText(prompt[i]); + texts[i]=new Text(parent, SWT.BORDER|SWT.PASSWORD); + GridData data=new GridData(GridData.FILL_HORIZONTAL); + data.horizontalSpan=2; + data.widthHint=convertHorizontalDLUsToPixels(IDialogConstants.ENTRY_FIELD_WIDTH); + texts[i].setLayoutData(data); + if(!echo[i]){ + texts[i].setEchoChar('*'); + } + } + } + /** + * Returns the entered values, or null + * if the user canceled. + * + * @return the entered values + */ + public String[] getResult() { + return result; + } + + /** + * Returns <code>true</code> if the save password checkbox was selected. + * @return <code>true</code> if the save password checkbox was selected and <code>false</code> + * otherwise. + */ + public boolean getAllowCaching(){ + return allowCaching; + } + + /** + * Notifies that the ok button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets + * this dialog's return code to <code>Window.OK</code> + * and closes the dialog. Subclasses may override. + * </p> + */ + @Override protected void okPressed() { - result=new String[prompt.length]; - for(int i=0; i<texts.length; i++){ - result[i]=texts[i].getText(); - } - super.okPressed(); - } - /** - * Notifies that the cancel button of this dialog has been pressed. - * <p> - * The default implementation of this framework method sets - * this dialog's return code to <code>Window.CANCEL</code> - * and closes the dialog. Subclasses may override. - * </p> - */ - @Override + result=new String[prompt.length]; + for(int i=0; i<texts.length; i++){ + result[i]=texts[i].getText(); + } + super.okPressed(); + } + /** + * Notifies that the cancel button of this dialog has been pressed. + * <p> + * The default implementation of this framework method sets + * this dialog's return code to <code>Window.CANCEL</code> + * and closes the dialog. Subclasses may override. + * </p> + */ + @Override protected void cancelPressed() { - result=null; - super.cancelPressed(); - } - + result=null; + super.cancelPressed(); + } + @Override - public boolean close(){ - if(keyLockImage!=null){ - keyLockImage.dispose(); - } - return super.close(); - } - - /** - * Guesses if this dialog is used for password authentication. - * @param prompt prompts for keyboard-interactive authentication method. - * @return <code>true</code> if this dialog is used for password authentication. - */ - static boolean isPasswordAuth(String[] prompt) { + public boolean close(){ + if(keyLockImage!=null){ + keyLockImage.dispose(); + } + return super.close(); + } + + /** + * Guesses if this dialog is used for password authentication. + * @param prompt prompts for keyboard-interactive authentication method. + * @return <code>true</code> if this dialog is used for password authentication. + */ + static boolean isPasswordAuth(String[] prompt) { return prompt != null && prompt.length == 1 && prompt[0].trim().equalsIgnoreCase("password:"); //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ListSelectionArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ListSelectionArea.java index 78b7e90e6..34cbb7403 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ListSelectionArea.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ListSelectionArea.java @@ -63,10 +63,10 @@ public class ListSelectionArea extends DialogArea { @Override public void createArea(Composite parent) { - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); - final Composite composite = createComposite(parent, 1, true); - + final Composite composite = createComposite(parent, 1, true); + initializeDialogUnits(composite); if (message != null) @@ -156,7 +156,7 @@ public class ListSelectionArea extends DialogArea { protected List getInitialElementSelections(){ return initialSelections; } - + /** * Returns the listViewer. * @return CheckboxTableViewer diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/Policy.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/Policy.java index 08ac28e5e..2a40ba598 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/Policy.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/Policy.java @@ -21,10 +21,10 @@ import org.eclipse.osgi.service.debug.DebugOptionsListener; import org.eclipse.team.internal.core.InfiniteSubProgressMonitor; public class Policy { - - private static String ACTION_BUNDLE = "org.eclipse.team.internal.ccvs.ui.actions.actions"; //$NON-NLS-1$ - private static ResourceBundle actionBundle = null; - + + private static String ACTION_BUNDLE = "org.eclipse.team.internal.ccvs.ui.actions.actions"; //$NON-NLS-1$ + private static ResourceBundle actionBundle = null; + public static boolean DEBUG_CONSOLE_BUFFERING = false; public static boolean DEBUG_HISTORY = false; @@ -68,9 +68,9 @@ public class Policy { } public static ResourceBundle getActionBundle() { - ResourceBundle tmpBundle = actionBundle; - if (tmpBundle != null) - return tmpBundle; - return actionBundle = ResourceBundle.getBundle(ACTION_BUNDLE); + ResourceBundle tmpBundle = actionBundle; + if (tmpBundle != null) + return tmpBundle; + return actionBundle = ResourceBundle.getBundle(ACTION_BUNDLE); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ReleaseCommentDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ReleaseCommentDialog.java index 885fa480b..6a58398b4 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ReleaseCommentDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ReleaseCommentDialog.java @@ -35,7 +35,7 @@ public class ReleaseCommentDialog extends DetailsDialog { // dialogs settings that are persistent between workbench sessions private IDialogSettings settings; - private static final int DEFAULT_WIDTH_IN_CHARS= 80; + private static final int DEFAULT_WIDTH_IN_CHARS= 80; private static final String HEIGHT_KEY = "width-key"; //$NON-NLS-1$ private static final String WIDTH_KEY = "height-key"; //$NON-NLS-1$ @@ -89,23 +89,23 @@ public class ReleaseCommentDialog extends DetailsDialog { } }); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } @Override - protected String getHelpContextId() { - return IHelpContextIds.RELEASE_COMMENT_DIALOG; - } - + protected String getHelpContextId() { + return IHelpContextIds.RELEASE_COMMENT_DIALOG; + } + @Override protected Point getInitialSize() { try { - return new Point(settings.getInt(WIDTH_KEY), settings.getInt(HEIGHT_KEY)); + return new Point(settings.getInt(WIDTH_KEY), settings.getInt(HEIGHT_KEY)); } catch(NumberFormatException e) { - final Point size= super.getInitialSize(); - size.x= convertWidthInCharsToPixels(DEFAULT_WIDTH_IN_CHARS); - size.y += convertHeightInCharsToPixels(8); - return size; + final Point size= super.getInitialSize(); + size.x= convertWidthInCharsToPixels(DEFAULT_WIDTH_IN_CHARS); + size.y += convertHeightInCharsToPixels(8); + return size; } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/RemoteRevisionQuickDiffProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/RemoteRevisionQuickDiffProvider.java index 941fe1058..2a82e1676 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/RemoteRevisionQuickDiffProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/RemoteRevisionQuickDiffProvider.java @@ -93,7 +93,7 @@ public class RemoteRevisionQuickDiffProvider implements IQuickDiffReferenceProvi ISubscriberChangeEvent delta = deltas[i]; IResource resource = delta.getResource(); if(resource.getType() == IResource.FILE && - fLastSyncState != null && resource.equals(fLastSyncState.getLocal())) { + fLastSyncState != null && resource.equals(fLastSyncState.getLocal())) { if(delta.getFlags() == ISubscriberChangeEvent.SYNC_CHANGED) { fetchContentsInJob(); } @@ -143,7 +143,7 @@ public class RemoteRevisionQuickDiffProvider implements IQuickDiffReferenceProvi @Override public void setActiveEditor(ITextEditor targetEditor) { IEditorInput editorInput = targetEditor.getEditorInput(); - if (editorInput == null || ResourceUtil.getFile(editorInput) == null) return; + if (editorInput == null || ResourceUtil.getFile(editorInput) == null) return; fEditor = targetEditor; fDocumentProvider= fEditor.getDocumentProvider(); @@ -318,10 +318,10 @@ public class RemoteRevisionQuickDiffProvider implements IQuickDiffReferenceProvi private IFile getFileFromEditor() { if(fEditor != null) { IEditorInput input= fEditor.getEditorInput(); - if (input != null) { - IFile file = ResourceUtil.getFile(input); - return file; - } + if (input != null) { + IFile file = ResourceUtil.getFile(input); + return file; + } } return null; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ResourcePropertiesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ResourcePropertiesPage.java index f1cf28e85..ab46aa943 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ResourcePropertiesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/ResourcePropertiesPage.java @@ -67,7 +67,7 @@ public class ResourcePropertiesPage extends PropertyPage { } catch (TeamException e) { createPair(composite, CVSUIMessages.ResourcePropertiesPage_error, e.getMessage()); } - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); return composite; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/UserValidationDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/UserValidationDialog.java index b7696be26..8f5e319db 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/UserValidationDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/UserValidationDialog.java @@ -73,7 +73,7 @@ public class UserValidationDialog extends TrayDialog { */ public UserValidationDialog(Shell parentShell, String location, String defaultName, String message, boolean cachingCheckbox) { super(parentShell); - setShellStyle(getShellStyle() | SWT.RESIZE); + setShellStyle(getShellStyle() | SWT.RESIZE); this.defaultUsername = defaultName; this.domain = location; this.message = message; @@ -85,7 +85,7 @@ public class UserValidationDialog extends TrayDialog { super.configureShell(newShell); newShell.setText(CVSUIMessages.UserValidationDialog_required); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IHelpContextIds.USER_VALIDATION_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IHelpContextIds.USER_VALIDATION_DIALOG); } @Override @@ -171,8 +171,8 @@ public class UserValidationDialog extends TrayDialog { }); } - Dialog.applyDialogFont(parent); - + Dialog.applyDialogFont(parent); + return main; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WatchEditPreferencePage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WatchEditPreferencePage.java index d7ae00144..24c24657b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WatchEditPreferencePage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WatchEditPreferencePage.java @@ -24,7 +24,7 @@ import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin; public class WatchEditPreferencePage extends CVSFieldEditorPreferencePage { private RadioGroupFieldEditor promptEditor; - private RadioGroupFieldEditor updateEditor; + private RadioGroupFieldEditor updateEditor; private RadioGroupFieldEditor actionEditor; private IPreferenceStore store; @@ -56,7 +56,7 @@ public class WatchEditPreferencePage extends CVSFieldEditorPreferencePage { CVSUIMessages.WatchEditPreferencePage_validateEditSaveAction, 1, new String[][] {{CVSUIMessages.WatchEditPreferencePage_edit, ICVSUIConstants.PREF_EDIT_PROMPT_EDIT}, - {CVSUIMessages.WatchEditPreferencePage_editInBackground, ICVSUIConstants.PREF_EDIT_IN_BACKGROUND}, + {CVSUIMessages.WatchEditPreferencePage_editInBackground, ICVSUIConstants.PREF_EDIT_IN_BACKGROUND}, {CVSUIMessages.WatchEditPreferencePage_highjack, ICVSUIConstants.PREF_EDIT_PROMPT_HIGHJACK}, }, // getFieldEditorParent(), true); @@ -71,20 +71,20 @@ public class WatchEditPreferencePage extends CVSFieldEditorPreferencePage { {CVSUIMessages.WatchEditPreferencePage_neverPrompt, ICVSUIConstants.PREF_EDIT_PROMPT_NEVER}, }, // getFieldEditorParent(), true); - - updateEditor = new RadioGroupFieldEditor( - ICVSUIConstants.PREF_UPDATE_PROMPT, - CVSUIMessages.WatchEditPreferencePage_updatePrompt, - 1, - new String[][] {{CVSUIMessages.WatchEditPreferencePage_autoUpdate, ICVSUIConstants.PREF_UPDATE_PROMPT_AUTO}, - {CVSUIMessages.WatchEditPreferencePage_promptUpdate, ICVSUIConstants.PREF_UPDATE_PROMPT_IF_OUTDATED}, - {CVSUIMessages.WatchEditPreferencePage_neverUpdate, ICVSUIConstants.PREF_UPDATE_PROMPT_NEVER}, - }, // - getFieldEditorParent(), true); - + + updateEditor = new RadioGroupFieldEditor( + ICVSUIConstants.PREF_UPDATE_PROMPT, + CVSUIMessages.WatchEditPreferencePage_updatePrompt, + 1, + new String[][] {{CVSUIMessages.WatchEditPreferencePage_autoUpdate, ICVSUIConstants.PREF_UPDATE_PROMPT_AUTO}, + {CVSUIMessages.WatchEditPreferencePage_promptUpdate, ICVSUIConstants.PREF_UPDATE_PROMPT_IF_OUTDATED}, + {CVSUIMessages.WatchEditPreferencePage_neverUpdate, ICVSUIConstants.PREF_UPDATE_PROMPT_NEVER}, + }, // + getFieldEditorParent(), true); + store = getCVSPreferenceStore(); addField(promptEditor); - addField(updateEditor); + addField(updateEditor); } private boolean isEditEnabled() { @@ -106,10 +106,10 @@ public class WatchEditPreferencePage extends CVSFieldEditorPreferencePage { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getSource() == actionEditor) { - boolean enabled = event.getNewValue().equals(ICVSUIConstants.PREF_EDIT_PROMPT_EDIT); + boolean enabled = event.getNewValue().equals(ICVSUIConstants.PREF_EDIT_PROMPT_EDIT); promptEditor.setEnabled(enabled, getFieldEditorParent()); - updateEditor.setEnabled(enabled, getFieldEditorParent()); - } + updateEditor.setEnabled(enabled, getFieldEditorParent()); + } super.propertyChange(event); } @@ -117,6 +117,6 @@ public class WatchEditPreferencePage extends CVSFieldEditorPreferencePage { protected void initialize() { super.initialize(); promptEditor.setEnabled(isEditEnabled(), getFieldEditorParent()); - updateEditor.setEnabled(isEditEnabled(), getFieldEditorParent()); + updateEditor.setEnabled(isEditEnabled(), getFieldEditorParent()); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkbenchUserAuthenticator.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkbenchUserAuthenticator.java index 03dc364f9..00943a978 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkbenchUserAuthenticator.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkbenchUserAuthenticator.java @@ -166,24 +166,24 @@ public class WorkbenchUserAuthenticator implements IUserAuthenticator { */ @Override public String[] promptForKeyboradInteractive(final ICVSRepositoryLocation location, - final String destination, - final String name, - final String instruction, - final String[] prompt, - final boolean[] echo) throws CVSException { - final String[][] result = new String[1][]; - final boolean[] allowCaching=new boolean[1]; - Display display = Display.getCurrent(); - if (display != null) { + final String destination, + final String name, + final String instruction, + final String[] prompt, + final boolean[] echo) throws CVSException { + final String[][] result = new String[1][]; + final boolean[] allowCaching=new boolean[1]; + Display display = Display.getCurrent(); + if (display != null) { result[0]=_promptForUserInteractive(location, destination, name, instruction, prompt, echo, allowCaching); - } - else { - // sync exec in default thread + } + else { + // sync exec in default thread Display.getDefault().syncExec(() -> result[0] = _promptForUserInteractive(location, destination, name, instruction, prompt, echo, allowCaching)); - } - if (result[0] != null && location != null && - KeyboardInteractiveDialog.isPasswordAuth(prompt)) { + } + if (result[0] != null && location != null && + KeyboardInteractiveDialog.isPasswordAuth(prompt)) { location.setPassword(result[0][0]); location.setAllowCaching(allowCaching[0]); } @@ -191,12 +191,12 @@ public class WorkbenchUserAuthenticator implements IUserAuthenticator { } private String[] _promptForUserInteractive(final ICVSRepositoryLocation location, - final String destination, - final String name, - final String instruction, - final String[] prompt, - final boolean[] echo, - final boolean[] allowCaching) { + final String destination, + final String name, + final String instruction, + final String[] prompt, + final boolean[] echo, + final boolean[] allowCaching) { String domain = location == null ? null : location.getLocation(true); String userName = location == null ? null : location.getUsername(); @@ -233,10 +233,10 @@ public class WorkbenchUserAuthenticator implements IUserAuthenticator { echo, cachingCheckbox); dialog.open(); - String[] _result=dialog.getResult(); - if(_result!=null) - allowCaching[0]=dialog.getAllowCaching(); - return _result; + String[] _result=dialog.getResult(); + if(_result!=null) + allowCaching[0]=dialog.getAllowCaching(); + return _result; } /** @@ -294,20 +294,20 @@ public class WorkbenchUserAuthenticator implements IUserAuthenticator { }); return retval[0]; } - - @Override + + @Override public boolean promptForHostKeyChange(final ICVSRepositoryLocation location) { - final boolean[] openConfirm = new boolean[] { false }; - final Display display = CVSUIPlugin.getStandardDisplay(); + final boolean[] openConfirm = new boolean[] { false }; + final Display display = CVSUIPlugin.getStandardDisplay(); display.syncExec( () -> openConfirm[0] = MessageDialog.openConfirm(null, CVSUIMessages.WorkbenchUserAuthenticator_1, NLS.bind(CVSUIMessages.WorkbenchUserAuthenticator_2, new String[] { location.getHost() }))); - if (!openConfirm[0]) { - throw new OperationCanceledException(); - } - return openConfirm[0]; - } - + if (!openConfirm[0]) { + throw new OperationCanceledException(); + } + return openConfirm[0]; + } + @Override public Map promptToConfigureRepositoryLocations(final Map alternativeMap) { final Map[] result = new Map[1]; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkingSetSelectionArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkingSetSelectionArea.java index 680c2efc1..29a699e29 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkingSetSelectionArea.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/WorkingSetSelectionArea.java @@ -81,19 +81,19 @@ public class WorkingSetSelectionArea extends DialogArea { } } }; - private final IDialogSettings settings; - private final Shell shell; + private final IDialogSettings settings; + private final Shell shell; public WorkingSetSelectionArea(Shell shell, String noWorkingSetText, String workingSetText, IDialogSettings settings) { this.shell = shell; - this.noWorkingSetText = noWorkingSetText; + this.noWorkingSetText = noWorkingSetText; this.workingSetText = workingSetText; - this.settings = settings; + this.settings = settings; } @Override public void createArea(Composite parent) { - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); final Composite composite = createComposite(parent, 2, false); initializeDialogUnits(composite); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/AddAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/AddAction.java index 9625232ce..994318bf7 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/AddAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/AddAction.java @@ -30,19 +30,19 @@ import org.eclipse.team.internal.ccvs.ui.wizards.AddWizard; * container is selected, its children are recursively added. */ public class AddAction extends WorkspaceTraversalAction { - + @Override public void execute(IAction action) throws InterruptedException, InvocationTargetException { - if (!promptForAddOfIgnored()) return; - if (!promptForAdd()) return; - AddOperation op = new AddOperation(getTargetPart(), getCVSResourceMappings()); - AddWizard.run(getShell(), op); + if (!promptForAddOfIgnored()) return; + if (!promptForAdd()) return; + AddOperation op = new AddOperation(getTargetPart(), getCVSResourceMappings()); + AddWizard.run(getShell(), op); } /* * Prompt the user to avoid accidental adding a resource to version control */ - private boolean promptForAdd() { + private boolean promptForAdd() { return MessageDialog.openQuestion(getShell(), CVSUIMessages.AddAction_confirmAddingResourcesTitle, CVSUIMessages.AddAction_confirmAddingResourcesMessage); @@ -52,8 +52,8 @@ public class AddAction extends WorkspaceTraversalAction { * Prompt whether explicitly selected ignored resources should be added */ private boolean promptForAddOfIgnored() { - // Prompt if any of the traversal roots are ignored - // TODO: What about non-root resources that are part of the model but would be ignored? + // Prompt if any of the traversal roots are ignored + // TODO: What about non-root resources that are part of the model but would be ignored? IResource[] resources = getSelectedResourcesWithOverlap(); boolean prompt = false; for (int i = 0; i < resources.length; i++) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/BranchAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/BranchAction.java index 01f7cba49..18d5ae8e3 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/BranchAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/BranchAction.java @@ -32,30 +32,30 @@ public class BranchAction extends WorkspaceTraversalAction { @Override public void execute(IAction action) throws InvocationTargetException, InterruptedException { ResourceMapping[] resourceMappings = getCVSResourceMappings(); - if (resourceMappings == null || resourceMappings.length == 0) { - // Could be a sync element tat is selected - IResource[] resources = getSelectedResources(); - resourceMappings = getResourceMappings(resources); - } - if (resourceMappings == null || resourceMappings.length == 0) { - // Nothing is select so just return - return; - } - new BranchOperation(getTargetPart(), resourceMappings).run(); + if (resourceMappings == null || resourceMappings.length == 0) { + // Could be a sync element tat is selected + IResource[] resources = getSelectedResources(); + resourceMappings = getResourceMappings(resources); + } + if (resourceMappings == null || resourceMappings.length == 0) { + // Nothing is select so just return + return; + } + new BranchOperation(getTargetPart(), resourceMappings).run(); } private ResourceMapping[] getResourceMappings(IResource[] resources) { List<ResourceMapping> mappings = new ArrayList<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - Object o = getAdapter(resource, ResourceMapping.class); - if (o instanceof ResourceMapping) { - ResourceMapping mapping = (ResourceMapping) o; - mappings.add(mapping); - } - } - return mappings.toArray(new ResourceMapping[mappings.size()]); - } + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + Object o = getAdapter(resource, ResourceMapping.class); + if (o instanceof ResourceMapping) { + ResourceMapping mapping = (ResourceMapping) o; + mappings.add(mapping); + } + } + return mappings.toArray(new ResourceMapping[mappings.size()]); + } @Override public String getId() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSAction.java index 525167a46..4b1d51fe8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSAction.java @@ -166,17 +166,17 @@ abstract public class CVSAction extends TeamAction implements IEditorActionDeleg @Override public void dispose() { super.dispose(); - IWorkbenchWindow window = getWindow(); - if (window != null) { - IPartService partService = window.getPartService(); - if (partService != null) - partService.removePartListener(retargetAction); - } - - if(retargetAction != null) { - retargetAction.dispose(); - retargetAction = null; - } + IWorkbenchWindow window = getWindow(); + if (window != null) { + IPartService partService = window.getPartService(); + if (partService != null) + partService.removePartListener(retargetAction); + } + + if(retargetAction != null) { + retargetAction.dispose(); + retargetAction = null; + } } @Override @@ -593,23 +593,23 @@ abstract public class CVSAction extends TeamAction implements IEditorActionDeleg /* * @see org.eclipse.team.internal.ui.actions.TeamAction#getSelectedResources() */ - protected final IResource[] getSelectedResourcesWithOverlap() { - IStructuredSelection selection = getSelection(); - CVSActionSelectionProperties props = CVSActionSelectionProperties.getProperties(getSelection()); - if (props == null) { - return Utils.getContributedResources(selection.toArray()); - } - return props.getAllSelectedResources(); - } - + protected final IResource[] getSelectedResourcesWithOverlap() { + IStructuredSelection selection = getSelection(); + CVSActionSelectionProperties props = CVSActionSelectionProperties.getProperties(getSelection()); + if (props == null) { + return Utils.getContributedResources(selection.toArray()); + } + return props.getAllSelectedResources(); + } + @Override protected final IResource[] getSelectedResources() { IStructuredSelection selection = getSelection(); - CVSActionSelectionProperties props = CVSActionSelectionProperties.getProperties(getSelection()); - if (props == null) { - return CVSActionSelectionProperties.getNonOverlapping(Utils.getContributedResources(selection.toArray())); - } - return props.getNonoverlappingSelectedResources(); + CVSActionSelectionProperties props = CVSActionSelectionProperties.getProperties(getSelection()); + if (props == null) { + return CVSActionSelectionProperties.getNonOverlapping(Utils.getContributedResources(selection.toArray())); + } + return props.getNonoverlappingSelectedResources(); } @Override @@ -633,16 +633,16 @@ abstract public class CVSAction extends TeamAction implements IEditorActionDeleg public boolean isHandled() { return true; } - - protected final ICVSResource getCVSResourceFor(IResource resource) { - CVSActionSelectionProperties props = CVSActionSelectionProperties.getProperties(getSelection()); - if (props == null) { - return CVSWorkspaceRoot.getCVSResourceFor(resource); - } - return props.getCVSResourceFor(resource); - } + + protected final ICVSResource getCVSResourceFor(IResource resource) { + CVSActionSelectionProperties props = CVSActionSelectionProperties.getProperties(getSelection()); + if (props == null) { + return CVSWorkspaceRoot.getCVSResourceFor(resource); + } + return props.getCVSResourceFor(resource); + } - public static CVSTag getAccurateFileTag(ICVSResource cvsResource) throws CVSException { + public static CVSTag getAccurateFileTag(ICVSResource cvsResource) throws CVSException { CVSTag tag = null; if (cvsResource != null) { return Util.getAccurateFileTag(cvsResource, getTags(cvsResource)); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSActionSelectionProperties.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSActionSelectionProperties.java index efb33606d..15d44ad51 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSActionSelectionProperties.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CVSActionSelectionProperties.java @@ -26,127 +26,127 @@ import org.eclipse.team.internal.ui.Utils; * This class represents a selection for a set of CVS actions. */ public class CVSActionSelectionProperties { - - // Use a weak hash map so that the properties ae collected when the selection is no longer referenced + + // Use a weak hash map so that the properties ae collected when the selection is no longer referenced private static Map<IStructuredSelection, CVSActionSelectionProperties> selectionProperties = new WeakHashMap<>(); - - private Object[] selection; + + private Object[] selection; private Map<String, Object> properties = new HashMap<>(); - - private static final String SELECTED_RESOURCES = "selectedResources"; //$NON-NLS-1$ - private static final String NONOVERLAPPING_SELECTED_RESOURCES = "nonoverlappingSelectedResources"; //$NON-NLS-1$ - private static final String CVS_RESOURCE_MAP = "cvsResourceMap"; //$NON-NLS-1$ - - public static CVSActionSelectionProperties getProperties(IStructuredSelection selection) { - if (selection == null) return null; - CVSActionSelectionProperties props = selectionProperties.get(selection); - if (props == null) { - props = new CVSActionSelectionProperties(selection); - selectionProperties.put(selection, props); - } - return props; - } - - public CVSActionSelectionProperties(IStructuredSelection selection) { - // Copy the selection so that the WeakHashMap will not think the seleciton used for the key is still in use - this.selection = selection.toArray(); - } + + private static final String SELECTED_RESOURCES = "selectedResources"; //$NON-NLS-1$ + private static final String NONOVERLAPPING_SELECTED_RESOURCES = "nonoverlappingSelectedResources"; //$NON-NLS-1$ + private static final String CVS_RESOURCE_MAP = "cvsResourceMap"; //$NON-NLS-1$ + + public static CVSActionSelectionProperties getProperties(IStructuredSelection selection) { + if (selection == null) return null; + CVSActionSelectionProperties props = selectionProperties.get(selection); + if (props == null) { + props = new CVSActionSelectionProperties(selection); + selectionProperties.put(selection, props); + } + return props; + } + + public CVSActionSelectionProperties(IStructuredSelection selection) { + // Copy the selection so that the WeakHashMap will not think the seleciton used for the key is still in use + this.selection = selection.toArray(); + } - public void put(String key, Object value) { - properties.put(key, value); - } - - public Object get(String key) { - return properties.get(key); - } - - public IResource[] getAllSelectedResources() { - IResource[] resources = (IResource[])get(SELECTED_RESOURCES); - if (resources == null) { - resources = getResources(selection); - put(SELECTED_RESOURCES, resources); - } - return resources; - } + public void put(String key, Object value) { + properties.put(key, value); + } + + public Object get(String key) { + return properties.get(key); + } + + public IResource[] getAllSelectedResources() { + IResource[] resources = (IResource[])get(SELECTED_RESOURCES); + if (resources == null) { + resources = getResources(selection); + put(SELECTED_RESOURCES, resources); + } + return resources; + } - /* - * This method gets the resources from the given objects. - * It does so in a manner that is consistent with how the workbench does it. - * Tha is, it first uses IContributionResourceAdapter, then IResource, - * then ResourceMapping. - */ - private IResource[] getResources(Object[] objects) { - return Utils.getContributedResources(objects); - } - - public IResource[] getNonoverlappingSelectedResources() { - IResource[] resources = (IResource[])get(NONOVERLAPPING_SELECTED_RESOURCES); - if (resources == null) { - resources = getNonOverlapping(getAllSelectedResources()); - put (NONOVERLAPPING_SELECTED_RESOURCES, resources); - } - return resources; - } - - public ICVSResource getCVSResourceFor(IResource resource) { - Map map = (Map)get(CVS_RESOURCE_MAP); - if (map == null) { - map = new HashMap(); - put(CVS_RESOURCE_MAP, map); - } - ICVSResource cvsResource = (ICVSResource)map.get(resource); - if (cvsResource == null) { - cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource); - map.put(resource, cvsResource); - } - return cvsResource; - } - - /** - * Method getNonOverlapping ensures that a resource is not covered more than once. - * @param resources - * @return IResource[] - */ - public static IResource[] getNonOverlapping(IResource[] resources) { - if (resources == null || resources.length == 0 || resources.length == 1) { - return resources; - } - // Sort the resources so the shortest paths are first + /* + * This method gets the resources from the given objects. + * It does so in a manner that is consistent with how the workbench does it. + * Tha is, it first uses IContributionResourceAdapter, then IResource, + * then ResourceMapping. + */ + private IResource[] getResources(Object[] objects) { + return Utils.getContributedResources(objects); + } + + public IResource[] getNonoverlappingSelectedResources() { + IResource[] resources = (IResource[])get(NONOVERLAPPING_SELECTED_RESOURCES); + if (resources == null) { + resources = getNonOverlapping(getAllSelectedResources()); + put (NONOVERLAPPING_SELECTED_RESOURCES, resources); + } + return resources; + } + + public ICVSResource getCVSResourceFor(IResource resource) { + Map map = (Map)get(CVS_RESOURCE_MAP); + if (map == null) { + map = new HashMap(); + put(CVS_RESOURCE_MAP, map); + } + ICVSResource cvsResource = (ICVSResource)map.get(resource); + if (cvsResource == null) { + cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource); + map.put(resource, cvsResource); + } + return cvsResource; + } + + /** + * Method getNonOverlapping ensures that a resource is not covered more than once. + * @param resources + * @return IResource[] + */ + public static IResource[] getNonOverlapping(IResource[] resources) { + if (resources == null || resources.length == 0 || resources.length == 1) { + return resources; + } + // Sort the resources so the shortest paths are first List<IResource> sorted = new ArrayList<>(); - sorted.addAll(Arrays.asList(resources)); + sorted.addAll(Arrays.asList(resources)); Collections.sort(sorted, new Comparator<IResource>() { - @Override + @Override public int compare(IResource resource0, IResource resource1) { - return resource0.getFullPath().segmentCount() - resource1.getFullPath().segmentCount(); - } - @Override + return resource0.getFullPath().segmentCount() - resource1.getFullPath().segmentCount(); + } + @Override public boolean equals(Object arg0) { - return false; - } - }); - // Collect all non-overlapping resources + return false; + } + }); + // Collect all non-overlapping resources List<IPath> coveredPaths = new ArrayList<>(); - for (Iterator iter = sorted.iterator(); iter.hasNext();) { - IResource resource = (IResource) iter.next(); - IPath resourceFullPath = resource.getFullPath(); - boolean covered = false; - for (Iterator it = coveredPaths.iterator(); it.hasNext();) { - IPath path = (IPath) it.next(); - if(path.isPrefixOf(resourceFullPath)) { - covered = true; - } - } - if (covered) { - // if the resource is covered by a parent, remove it - iter.remove(); - } else { - // if the resource is a non-covered folder, add it to the covered paths - if (resource.getType() == IResource.FOLDER) { - coveredPaths.add(resource.getFullPath()); - } - } - } - return sorted.toArray(new IResource[sorted.size()]); - } - + for (Iterator iter = sorted.iterator(); iter.hasNext();) { + IResource resource = (IResource) iter.next(); + IPath resourceFullPath = resource.getFullPath(); + boolean covered = false; + for (Iterator it = coveredPaths.iterator(); it.hasNext();) { + IPath path = (IPath) it.next(); + if(path.isPrefixOf(resourceFullPath)) { + covered = true; + } + } + if (covered) { + // if the resource is covered by a parent, remove it + iter.remove(); + } else { + // if the resource is a non-covered folder, add it to the covered paths + if (resource.getType() == IResource.FOLDER) { + coveredPaths.add(resource.getFullPath()); + } + } + } + return sorted.toArray(new IResource[sorted.size()]); + } + } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CheckoutAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CheckoutAction.java index c24887c25..747e27a74 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CheckoutAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CheckoutAction.java @@ -36,19 +36,19 @@ public class CheckoutAction extends CVSAction { } @Override - public boolean isEnabled() { - ICVSRemoteFolder[] folders = getSelectedRemoteFolders(); - if (folders.length == 0) return false; - // only enabled when all folders are in the same repository - ICVSRepositoryLocation location = folders[0].getRepository(); - for (int i = 1; i < folders.length; i++) { - ICVSRemoteFolder folder = folders[i]; - if (!folder.getRepository().equals(location)) { - return false; - } - } - return true; - } + public boolean isEnabled() { + ICVSRemoteFolder[] folders = getSelectedRemoteFolders(); + if (folders.length == 0) return false; + // only enabled when all folders are in the same repository + ICVSRepositoryLocation location = folders[0].getRepository(); + for (int i = 1; i < folders.length; i++) { + ICVSRemoteFolder folder = folders[i]; + if (!folder.getRepository().equals(location)) { + return false; + } + } + return true; + } /** * Get selected CVS remote folders, and add Project Description diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CommitAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CommitAction.java index b1674e1a5..1ac1bf8b2 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CommitAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CommitAction.java @@ -73,7 +73,7 @@ public class CommitAction extends WorkspaceTraversalAction { } }, false, PROGRESS_BUSYCURSOR); } - + @Override protected String getErrorTitle() { return CVSUIMessages.CommitAction_commitFailed; @@ -110,7 +110,7 @@ public class CommitAction extends WorkspaceTraversalAction { if (option.equals(MessageDialogWithToggle.NEVER)) return false; // no, never switch - // Ask the user whether to switch + // Ask the user whether to switch final int[] result = new int[] { 0 }; Utils.syncExec((Runnable) () -> { final MessageDialogWithToggle m = MessageDialogWithToggle.openYesNoQuestion(shell, @@ -124,10 +124,10 @@ public class CommitAction extends WorkspaceTraversalAction { // yes case IDialogConstants.YES_ID: case IDialogConstants.OK_ID : - return true; + return true; // no case IDialogConstants.NO_ID : - return false; + return false; } return false; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CompareWithTagAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CompareWithTagAction.java index 2c8736cac..354a0b7c4 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CompareWithTagAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/CompareWithTagAction.java @@ -40,8 +40,8 @@ public class CompareWithTagAction extends WorkspaceTraversalAction { @Override public void execute(IAction action) throws InvocationTargetException, InterruptedException { - - // First, determine the tag to compare with + + // First, determine the tag to compare with IResource[] resources = getSelectedResources(); CVSTag tag = promptForTag(resources); if (tag == null) @@ -57,7 +57,7 @@ public class CompareWithTagAction extends WorkspaceTraversalAction { } } - // Create a subscriber that can cover all projects involved + // Create a subscriber that can cover all projects involved if (isShowModelSync()) { final CVSCompareSubscriber compareSubscriber = new CVSCompareSubscriber(getProjects(resources), tag); ResourceMapping[] mappings = getCVSResourceMappings(); @@ -80,12 +80,12 @@ public class CompareWithTagAction extends WorkspaceTraversalAction { participant.run(getTargetPart()); } else { CVSCompareSubscriber compareSubscriber = new CVSCompareSubscriber(getProjects(resources), tag); - ResourceMapping[] resourceMappings = getCVSResourceMappings(); + ResourceMapping[] resourceMappings = getCVSResourceMappings(); if (isLogicalModel(resourceMappings)) { - compareSubscriber = new CVSCompareSubscriber(getProjects(resources), tag); - resources = getResourcesToCompare(compareSubscriber); - compareSubscriber.dispose(); - } + compareSubscriber = new CVSCompareSubscriber(getProjects(resources), tag); + resources = getResourcesToCompare(compareSubscriber); + compareSubscriber.dispose(); + } // create a subscriber specifically for the resources for display to the user compareSubscriber = new CVSCompareSubscriber(resources, tag); try { @@ -104,11 +104,11 @@ public class CompareWithTagAction extends WorkspaceTraversalAction { } } - private boolean isShowModelSync() { + private boolean isShowModelSync() { return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_ENABLE_MODEL_SYNC); } - - protected CVSTag promptForTag(IResource[] resources) { + + protected CVSTag promptForTag(IResource[] resources) { CVSTag tag = TagSelectionDialog.getTagToCompareWith(getShell(), TagSource.create(resources), TagSelectionDialog.INCLUDE_ALL_TAGS); return tag; } @@ -116,5 +116,5 @@ public class CompareWithTagAction extends WorkspaceTraversalAction { @Override protected boolean isEnabledForNonExistantResources() { return true; - } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/GenerateDiffFileAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/GenerateDiffFileAction.java index cf28b19f1..839ada0e8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/GenerateDiffFileAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/GenerateDiffFileAction.java @@ -36,7 +36,7 @@ import org.eclipse.ui.PlatformUI; * by a create patch command in the compare viewer. */ public class GenerateDiffFileAction extends WorkspaceTraversalAction{ - + @Override public void execute(IAction action) { @@ -57,46 +57,46 @@ public class GenerateDiffFileAction extends WorkspaceTraversalAction{ } } - private IResource[] getDeepResourcesToPatch(IProgressMonitor monitor) throws CoreException { - ResourceMapping[] mappings = getCVSResourceMappings(); + private IResource[] getDeepResourcesToPatch(IProgressMonitor monitor) throws CoreException { + ResourceMapping[] mappings = getCVSResourceMappings(); List<IResource> roots = new ArrayList<>(); - for (int i = 0; i < mappings.length; i++) { - ResourceMapping mapping = mappings[i]; - ResourceTraversal[] traversals = mapping.getTraversals( - SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()), - monitor); - for (int j = 0; j < traversals.length; j++) { - ResourceTraversal traversal = traversals[j]; - IResource[] resources = traversal.getResources(); - if (traversal.getDepth() == IResource.DEPTH_INFINITE) { - roots.addAll(Arrays.asList(resources)); - } else if (traversal.getDepth() == IResource.DEPTH_ZERO) { - collectShallowFiles(resources, roots); - } else if (traversal.getDepth() == IResource.DEPTH_ONE) { - collectShallowFiles(resources, roots); - for (int k = 0; k < resources.length; k++) { - IResource resource = resources[k]; - if (resource.getType() != IResource.FILE) { - collectShallowFiles(members(resource), roots); - } - } - } - } - } - return roots.toArray(new IResource[roots.size()]); - } - + for (int i = 0; i < mappings.length; i++) { + ResourceMapping mapping = mappings[i]; + ResourceTraversal[] traversals = mapping.getTraversals( + SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()), + monitor); + for (int j = 0; j < traversals.length; j++) { + ResourceTraversal traversal = traversals[j]; + IResource[] resources = traversal.getResources(); + if (traversal.getDepth() == IResource.DEPTH_INFINITE) { + roots.addAll(Arrays.asList(resources)); + } else if (traversal.getDepth() == IResource.DEPTH_ZERO) { + collectShallowFiles(resources, roots); + } else if (traversal.getDepth() == IResource.DEPTH_ONE) { + collectShallowFiles(resources, roots); + for (int k = 0; k < resources.length; k++) { + IResource resource = resources[k]; + if (resource.getType() != IResource.FILE) { + collectShallowFiles(members(resource), roots); + } + } + } + } + } + return roots.toArray(new IResource[roots.size()]); + } + private void collectShallowFiles(IResource[] resources, List<IResource> roots) { - for (int k = 0; k < resources.length; k++) { - IResource resource = resources[k]; - if (resource.getType() == IResource.FILE) - roots.add(resource); - } - } - - private IResource[] members(IResource resource) throws CoreException { - return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().members(resource); - } + for (int k = 0; k < resources.length; k++) { + IResource resource = resources[k]; + if (resource.getType() == IResource.FILE) + roots.add(resource); + } + } + + private IResource[] members(IResource resource) throws CoreException { + return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().members(resource); + } @Override protected boolean isEnabledForMultipleResources() { return true; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/IgnoreAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/IgnoreAction.java index c05eec73e..7d6bf572f 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/IgnoreAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/IgnoreAction.java @@ -30,30 +30,30 @@ import org.eclipse.team.internal.ccvs.ui.operations.RepositoryProviderOperation; import org.eclipse.ui.IWorkbenchPart; public class IgnoreAction extends WorkspaceTraversalAction { - - /** - * Define an operation that can be run in the background. - * We divide the ignores by provider to obtain project - * locks while modifying the .cvsignore files - */ - class IgnoreOperation extends RepositoryProviderOperation { + + /** + * Define an operation that can be run in the background. + * We divide the ignores by provider to obtain project + * locks while modifying the .cvsignore files + */ + class IgnoreOperation extends RepositoryProviderOperation { - private final IgnoreResourcesDialog dialog; + private final IgnoreResourcesDialog dialog; - public IgnoreOperation(IWorkbenchPart part, IResource[] resources, IgnoreResourcesDialog dialog) { - super(part, resources); - this.dialog = dialog; - } + public IgnoreOperation(IWorkbenchPart part, IResource[] resources, IgnoreResourcesDialog dialog) { + super(part, resources); + this.dialog = dialog; + } - @Override + @Override protected String getTaskName(CVSTeamProvider provider) { - return NLS.bind(CVSUIMessages.IgnoreAction_0, new String[] { provider.getProject().getName() }); - } + return NLS.bind(CVSUIMessages.IgnoreAction_0, new String[] { provider.getProject().getName() }); + } - @Override + @Override protected void execute(CVSTeamProvider provider, IResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException { try { - monitor.beginTask(null, resources.length); + monitor.beginTask(null, resources.length); for (int i = 0; i < resources.length; i++) { IResource resource = resources[i]; String pattern = dialog.getIgnorePatternFor(resource); @@ -65,22 +65,22 @@ public class IgnoreAction extends WorkspaceTraversalAction { collectStatus(e.getStatus()); return; } finally { - monitor.done(); + monitor.done(); } collectStatus(Status.OK_STATUS); - } + } - @Override + @Override protected String getTaskName() { - return CVSUIMessages.IgnoreAction_1; - } - - @Override + return CVSUIMessages.IgnoreAction_1; + } + + @Override public boolean consultModelsForMappings() { - return false; - } - - } + return false; + } + + } @Override protected void execute(final IAction action) throws InvocationTargetException, InterruptedException { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/MoveRemoteTagAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/MoveRemoteTagAction.java index 6e598a1ba..69d8672d2 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/MoveRemoteTagAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/MoveRemoteTagAction.java @@ -48,13 +48,13 @@ public class MoveRemoteTagAction extends TagInRepositoryAction { return operation; } - private boolean isFolderSelected() { - ICVSResource[] resources = getSelectedCVSResources(); - for (int i = 0; i < resources.length; i++) { - ICVSResource resource = resources[i]; - if (resource.isFolder()) - return true; - } - return false; - } + private boolean isFolderSelected() { + ICVSResource[] resources = getSelectedCVSResources(); + for (int i = 0; i < resources.length; i++) { + ICVSResource resource = resources[i]; + if (resource.isFolder()) + return true; + } + return false; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/OutgoingChangesDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/OutgoingChangesDialog.java index adc81eeec..b77869aaf 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/OutgoingChangesDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/OutgoingChangesDialog.java @@ -126,16 +126,16 @@ public class OutgoingChangesDialog extends DetailsDialog { return false; } - @Override + @Override protected void updateEnablements() { - // Can always finish - setPageComplete(true); - } - - @Override + // Can always finish + setPageComplete(true); + } + + @Override protected boolean includeErrorMessage() { - return false; - } + return false; + } public void setHelpContextId(String helpContextId) { this.helpContextId = helpContextId; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithRemoteAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithRemoteAction.java index b2f3ceb76..f8e12c4c6 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithRemoteAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithRemoteAction.java @@ -23,7 +23,7 @@ import org.eclipse.team.internal.ccvs.ui.IHelpContextIds; import org.eclipse.team.internal.ccvs.ui.operations.ReplaceOperation; public class ReplaceWithRemoteAction extends WorkspaceTraversalAction { - + @Override public void execute(IAction action) throws InvocationTargetException, InterruptedException { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java index ab620823c..4bc233f26 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ReplaceWithTagAction.java @@ -28,7 +28,7 @@ import org.eclipse.team.internal.ccvs.ui.operations.ReplaceOperation; * Action for replace with tag. */ public abstract class ReplaceWithTagAction extends WorkspaceTraversalAction { - + @Override public void execute(IAction action) throws InterruptedException, InvocationTargetException { final ReplaceOperation replaceOperation= createReplaceOperation(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/RestoreFromRepositoryAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/RestoreFromRepositoryAction.java index 0186e7612..d450e4cd9 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/RestoreFromRepositoryAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/RestoreFromRepositoryAction.java @@ -70,51 +70,51 @@ public class RestoreFromRepositoryAction extends WorkspaceTraversalAction { // Extract the file name and path from the RCS path // String filePath = line.substring(index); - // Find all RCS file names that contain "Attic" - int start = line.lastIndexOf(Session.SERVER_SEPARATOR); - if (start != -1) { - String fileName = line.substring(start + 1); - if (fileName.endsWith(RCS_FILE_POSTFIX)) { - fileName = fileName.substring(0, fileName.length() - RCS_FILE_POSTFIX.length()); - } - if (currentFolder != null) { - try { - ICVSFile file = currentFolder.getFile(fileName); - if (!file.exists()) - atticFiles.add(file); - } catch (CVSException e) { - return e.getStatus(); - } - } else { - // Executed for every message line when in quiet mode. - // See bug 238334 - CVSRepositoryLocation repo = (CVSRepositoryLocation)location; - // If exists, remove root directory - if (line.startsWith(repo.getRootDirectory())) { - String repoPath = line.substring(repo.getRootDirectory().length()); - try { - String cmdRootRelativePath = commandRoot.getRepositoryRelativePath(); - // Remove command root path - String path = repoPath.substring(repoPath.indexOf(cmdRootRelativePath) + cmdRootRelativePath.length()); - // Remove filename at the end - String folderPath = path.substring(0, path.indexOf(fileName)); - // The "raw" folderPath contains CVS's 'Attic/' segment when a file has been deleted from cvs. - if (folderPath.endsWith(ATTIC)) { - folderPath = folderPath.substring(0, folderPath.length() - ATTIC_LENGTH); - } - // A separator means the same as "current folder" - if (folderPath.equals(Session.SERVER_SEPARATOR)) - folderPath = Session.CURRENT_LOCAL_FOLDER; - ICVSFolder folder = commandRoot.getFolder(folderPath); - ICVSFile file = folder.getFile(fileName); - if (!file.exists()) - atticFiles.add(file); - } catch (CVSException e) { - return e.getStatus(); - } - } - } - } + // Find all RCS file names that contain "Attic" + int start = line.lastIndexOf(Session.SERVER_SEPARATOR); + if (start != -1) { + String fileName = line.substring(start + 1); + if (fileName.endsWith(RCS_FILE_POSTFIX)) { + fileName = fileName.substring(0, fileName.length() - RCS_FILE_POSTFIX.length()); + } + if (currentFolder != null) { + try { + ICVSFile file = currentFolder.getFile(fileName); + if (!file.exists()) + atticFiles.add(file); + } catch (CVSException e) { + return e.getStatus(); + } + } else { + // Executed for every message line when in quiet mode. + // See bug 238334 + CVSRepositoryLocation repo = (CVSRepositoryLocation)location; + // If exists, remove root directory + if (line.startsWith(repo.getRootDirectory())) { + String repoPath = line.substring(repo.getRootDirectory().length()); + try { + String cmdRootRelativePath = commandRoot.getRepositoryRelativePath(); + // Remove command root path + String path = repoPath.substring(repoPath.indexOf(cmdRootRelativePath) + cmdRootRelativePath.length()); + // Remove filename at the end + String folderPath = path.substring(0, path.indexOf(fileName)); + // The "raw" folderPath contains CVS's 'Attic/' segment when a file has been deleted from cvs. + if (folderPath.endsWith(ATTIC)) { + folderPath = folderPath.substring(0, folderPath.length() - ATTIC_LENGTH); + } + // A separator means the same as "current folder" + if (folderPath.equals(Session.SERVER_SEPARATOR)) + folderPath = Session.CURRENT_LOCAL_FOLDER; + ICVSFolder folder = commandRoot.getFolder(folderPath); + ICVSFile file = folder.getFile(fileName); + if (!file.exists()) + atticFiles.add(file); + } catch (CVSException e) { + return e.getStatus(); + } + } + } + } return OK; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SetKeywordSubstitutionAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SetKeywordSubstitutionAction.java index 2ec2dbf3a..60b02bcaf 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SetKeywordSubstitutionAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SetKeywordSubstitutionAction.java @@ -24,7 +24,7 @@ public class SetKeywordSubstitutionAction extends WorkspaceTraversalAction { @Override public void execute(IAction action) { - ModeWizard.run(getShell(), getSelectedResources()); + ModeWizard.run(getShell(), getSelectedResources()); } @Override diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ShowAnnotationAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ShowAnnotationAction.java index 4d44ac5c3..c11210f0b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ShowAnnotationAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/ShowAnnotationAction.java @@ -34,9 +34,9 @@ public class ShowAnnotationAction extends WorkspaceAction { * Action to open a CVS Annotate View */ public void execute(IAction action) throws InvocationTargetException, InterruptedException { - final ICVSResource resource= getSingleSelectedCVSResource(); - if (resource == null) - return; + final ICVSResource resource= getSingleSelectedCVSResource(); + if (resource == null) + return; execute(resource); } @@ -52,9 +52,9 @@ public class ShowAnnotationAction extends WorkspaceAction { public void execute(final ICVSResource cvsResource) throws InvocationTargetException, InterruptedException { final String revision= getRevision(cvsResource); if (revision == null) - return; + return; boolean binary = isBinary(cvsResource); - if (binary) { + if (binary) { final IPreferenceStore store = CVSUIPlugin.getPlugin().getPreferenceStore(); final String option = store.getString(ICVSUIConstants.PREF_ANNOTATE_PROMPTFORBINARY); if (option.equals(MessageDialogWithToggle.PROMPT)) { @@ -67,24 +67,24 @@ public class ShowAnnotationAction extends WorkspaceAction { } else if (option.equals(MessageDialogWithToggle.NEVER)) return; } - + new ShowAnnotationOperation(getTargetPart(), cvsResource, revision, binary).run(); } - private boolean isBinary(ICVSResource cvsResource) { - if (cvsResource.isFolder()) return false; - - try { - byte[] syncBytes = ((ICVSFile)cvsResource).getSyncBytes(); - if (syncBytes == null) - return false; - return ResourceSyncInfo.isBinary(syncBytes); - } catch (CVSException e) { - return false; - } - } + private boolean isBinary(ICVSResource cvsResource) { + if (cvsResource.isFolder()) return false; + + try { + byte[] syncBytes = ((ICVSFile)cvsResource).getSyncBytes(); + if (syncBytes == null) + return false; + return ResourceSyncInfo.isBinary(syncBytes); + } catch (CVSException e) { + return false; + } + } - /** + /** * Only enabled for single resource selection */ public boolean isEnabled() { @@ -134,7 +134,7 @@ public class ShowAnnotationAction extends WorkspaceAction { return null; } - + /** * Get the revision for the CVS resource. Throws an InvocationTargetException * if the revision could not be determined. @@ -144,16 +144,16 @@ public class ShowAnnotationAction extends WorkspaceAction { * @throws InvocationTargetException */ private String getRevision(ICVSResource cvsResource) throws InvocationTargetException { - final ResourceSyncInfo info; - try { - info= cvsResource.getSyncInfo(); - if (info == null) - throw new CVSException(NLS.bind(CVSUIMessages.ShowAnnotationAction_noSyncInfo, new String[] { cvsResource.getName() })); - } catch (CVSException e) { - throw new InvocationTargetException(e); - } - return info.getRevision(); - } + final ResourceSyncInfo info; + try { + info= cvsResource.getSyncInfo(); + if (info == null) + throw new CVSException(NLS.bind(CVSUIMessages.ShowAnnotationAction_noSyncInfo, new String[] { cvsResource.getName() })); + } catch (CVSException e) { + throw new InvocationTargetException(e); + } + return info.getRevision(); + } public String getId() { return ICVSUIConstants.CMD_ANNOTATE; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SyncAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SyncAction.java index 8a78ab47b..d94b4948b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SyncAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/SyncAction.java @@ -65,24 +65,24 @@ public class SyncAction extends WorkspaceTraversalAction { TeamUI.getSynchronizeManager().addSynchronizeParticipants(new ISynchronizeParticipant[] {participant}); participant.run(getTargetPart()); } else { - IResource[] resources = getResourcesToCompare(getWorkspaceSubscriber()); + IResource[] resources = getResourcesToCompare(getWorkspaceSubscriber()); if (resources == null || resources.length == 0) return; // First check if there is an existing matching participant WorkspaceSynchronizeParticipant participant = (WorkspaceSynchronizeParticipant)SubscriberParticipant.getMatchingParticipant(WorkspaceSynchronizeParticipant.ID, resources); // If there isn't, create one and add to the manager if (participant == null) { - ISynchronizeScope scope; - if (includesAllCVSProjects(resources)) { - scope = new WorkspaceScope(); - } else { - IWorkingSet[] sets = getSelectedWorkingSets(); - if (sets != null) { - scope = new WorkingSetScope(sets); - } else { - scope = new ResourceScope(resources); - } - } - participant = new WorkspaceSynchronizeParticipant(scope); + ISynchronizeScope scope; + if (includesAllCVSProjects(resources)) { + scope = new WorkspaceScope(); + } else { + IWorkingSet[] sets = getSelectedWorkingSets(); + if (sets != null) { + scope = new WorkingSetScope(sets); + } else { + scope = new ResourceScope(resources); + } + } + participant = new WorkspaceSynchronizeParticipant(scope); TeamUI.getSynchronizeManager().addSynchronizeParticipants(new ISynchronizeParticipant[] {participant}); } participant.refresh(resources, getTargetPart().getSite()); @@ -98,53 +98,53 @@ public class SyncAction extends WorkspaceTraversalAction { } private IWorkingSet[] getSelectedWorkingSets() { - ResourceMapping[] mappings = getCVSResourceMappings(); + ResourceMapping[] mappings = getCVSResourceMappings(); List<IWorkingSet> sets = new ArrayList<>(); - for (int i = 0; i < mappings.length; i++) { - ResourceMapping mapping = mappings[i]; - if (mapping.getModelObject() instanceof IWorkingSet) { - IWorkingSet set = (IWorkingSet) mapping.getModelObject(); - sets.add(set); - } else { - return null; - } - } - if (sets.isEmpty()) - return null; - return sets.toArray(new IWorkingSet[sets.size()]); - } + for (int i = 0; i < mappings.length; i++) { + ResourceMapping mapping = mappings[i]; + if (mapping.getModelObject() instanceof IWorkingSet) { + IWorkingSet set = (IWorkingSet) mapping.getModelObject(); + sets.add(set); + } else { + return null; + } + } + if (sets.isEmpty()) + return null; + return sets.toArray(new IWorkingSet[sets.size()]); + } - private boolean includesAllCVSProjects(IResource[] resources) { - // First, make sure all the selected thinsg are projects - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - if (resource.getType() != IResource.PROJECT) - return false; - } - IProject[] cvsProjects = getAllCVSProjects(); - return cvsProjects.length == resources.length; - } + private boolean includesAllCVSProjects(IResource[] resources) { + // First, make sure all the selected thinsg are projects + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + if (resource.getType() != IResource.PROJECT) + return false; + } + IProject[] cvsProjects = getAllCVSProjects(); + return cvsProjects.length == resources.length; + } - private IProject[] getAllCVSProjects() { - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); + private IProject[] getAllCVSProjects() { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); Set<IProject> cvsProjects = new HashSet<>(); - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - if (RepositoryProvider.isShared(project) && RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()) != null) { - cvsProjects.add(project); - } - } - return cvsProjects.toArray(new IProject[cvsProjects.size()]); - } + for (int i = 0; i < projects.length; i++) { + IProject project = projects[i]; + if (RepositoryProvider.isShared(project) && RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()) != null) { + cvsProjects.add(project); + } + } + return cvsProjects.toArray(new IProject[cvsProjects.size()]); + } - /** - * Return whether it is OK to open the selected file directly in a compare editor. - * It is not OK to show the single file if the file is part of a logical model element - * that spans files. - * @param file the file - * @return whether it is OK to open the selected file directly in a compare editor - */ - public static boolean isOKToShowSingleFile(IFile file) { + /** + * Return whether it is OK to open the selected file directly in a compare editor. + * It is not OK to show the single file if the file is part of a logical model element + * that spans files. + * @param file the file + * @return whether it is OK to open the selected file directly in a compare editor + */ + public static boolean isOKToShowSingleFile(IFile file) { if (!isShowModelSync()) return true; IModelProviderDescriptor[] descriptors = ModelProvider.getModelProviderDescriptors(); @@ -178,8 +178,8 @@ public class SyncAction extends WorkspaceTraversalAction { } return true; } - - /** + + /** * Refresh the subscriber directly and show the resulting synchronization state in a compare editor. If there * is no difference the user is prompted. * diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagAction.java index 22bf5c49b..b6ee44b18 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagAction.java @@ -72,7 +72,7 @@ public abstract class TagAction extends WorkspaceTraversalAction { IPreferenceStore store = CVSUIPlugin.getPlugin().getPreferenceStore(); ITagOperation operation = createTagOperation(); if (operation.isEmpty()) { - return null; + return null; } if (!performPrompting(operation)) { return null; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagLocalAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagLocalAction.java index b9392b086..442065a13 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagLocalAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/TagLocalAction.java @@ -25,7 +25,7 @@ import org.eclipse.team.internal.ccvs.ui.operations.TagOperation; * Action that tags the local workspace with a version tag. */ public class TagLocalAction extends TagAction { - + @Override protected boolean performPrompting(ITagOperation operation) { if (operation instanceof TagOperation) { @@ -53,7 +53,7 @@ public class TagLocalAction extends TagAction { return false; } - @Override + @Override protected ITagOperation createTagOperation() { return new TagOperation(getTargetPart(), getCVSResourceMappings()); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UnmanageAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UnmanageAction.java index 5798096c1..4e0d77c11 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UnmanageAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UnmanageAction.java @@ -91,7 +91,7 @@ public class UnmanageAction extends WorkspaceAction { radio1.setSelection(deleteContent); radio2.setSelection(!deleteContent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.DISCONNECT_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.DISCONNECT_ACTION); return composite; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UpdateSilentAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UpdateSilentAction.java index 68699f7c2..2591555b1 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UpdateSilentAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/UpdateSilentAction.java @@ -29,24 +29,24 @@ import org.eclipse.team.internal.ccvs.ui.operations.UpdateOperation; * @since 3.1 */ public class UpdateSilentAction extends WorkspaceTraversalAction { - + @Override - protected boolean isEnabledForAddedResources() { - return false; - } + protected boolean isEnabledForAddedResources() { + return false; + } @Override - protected boolean isEnabledForNonExistantResources() { - return true; - } - + protected boolean isEnabledForNonExistantResources() { + return true; + } + @Override public void execute(IAction action) throws InterruptedException, InvocationTargetException { if (CVSUIPlugin.getPlugin().getPreferenceStore().getString(ICVSUIConstants.PREF_UPDATE_HANDLING).equals(ICVSUIConstants.PREF_UPDATE_HANDLING_TRADITIONAL)) { new UpdateOperation(getTargetPart(), getCVSResourceMappings(), Command.NO_LOCAL_OPTIONS, null /* no tag */).run(); } else { - new ModelUpdateOperation(getTargetPart(), getSelectedResourceMappings(CVSProviderPlugin.getTypeId())).run(); - } + new ModelUpdateOperation(getTargetPart(), getSelectedResourceMappings(CVSProviderPlugin.getTypeId())).run(); + } } @Override diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceAction.java index 7da395b4c..7f64b1dd0 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceAction.java @@ -353,7 +353,7 @@ public abstract class WorkspaceAction extends CVSAction { return true; } - /** + /** * Method isEnabledForCVSResource. * @param cvsResource * @return boolean diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceTraversalAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceTraversalAction.java index 9bdb8d460..31a978cd6 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceTraversalAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/actions/WorkspaceTraversalAction.java @@ -41,71 +41,71 @@ import org.eclipse.ui.PlatformUI; */ public abstract class WorkspaceTraversalAction extends WorkspaceAction { - /** - * Return the selected mappings that contain resources - * within a CVS managed project. - * @return the selected mappings that contain resources - * within a CVS managed project - */ - protected ResourceMapping[] getCVSResourceMappings() { - return getSelectedResourceMappings(CVSProviderPlugin.getTypeId()); - } + /** + * Return the selected mappings that contain resources + * within a CVS managed project. + * @return the selected mappings that contain resources + * within a CVS managed project + */ + protected ResourceMapping[] getCVSResourceMappings() { + return getSelectedResourceMappings(CVSProviderPlugin.getTypeId()); + } - private static ResourceTraversal[] getTraversals(IWorkbenchPart part, ISynchronizationScopeManager manager, IProgressMonitor monitor) throws CoreException { - try { - BuildScopeOperation op = new BuildScopeOperation(part, manager); - op.run(monitor); - return manager.getScope().getTraversals(); - } catch (InvocationTargetException e) { + private static ResourceTraversal[] getTraversals(IWorkbenchPart part, ISynchronizationScopeManager manager, IProgressMonitor monitor) throws CoreException { + try { + BuildScopeOperation op = new BuildScopeOperation(part, manager); + op.run(monitor); + return manager.getScope().getTraversals(); + } catch (InvocationTargetException e) { throw TeamException.asTeamException(e); } catch (InterruptedException e) { throw new OperationCanceledException(); } - } - - private static IResource[] getRootTraversalResources(ISynchronizationScopeManager manager, IProgressMonitor monitor) throws CoreException { + } + + private static IResource[] getRootTraversalResources(ISynchronizationScopeManager manager, IProgressMonitor monitor) throws CoreException { Set<IResource> result = new HashSet<>(); - ResourceTraversal[] traversals = getTraversals(null, manager, monitor); - for (int i = 0; i < traversals.length; i++) { + ResourceTraversal[] traversals = getTraversals(null, manager, monitor); + for (int i = 0; i < traversals.length; i++) { ResourceTraversal traversal = traversals[i]; - IResource[] resources = traversal.getResources(); - for (int k = 0; k < resources.length; k++) { - IResource resource = resources[k]; - if (RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()) != null) { - result.add(resource); - } - } - } - return result.toArray(new IResource[result.size()]); - } + IResource[] resources = traversal.getResources(); + for (int k = 0; k < resources.length; k++) { + IResource resource = resources[k]; + if (RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId()) != null) { + result.add(resource); + } + } + } + return result.toArray(new IResource[result.size()]); + } - protected Subscriber getWorkspaceSubscriber() { - return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); - } - + protected Subscriber getWorkspaceSubscriber() { + return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); + } + public static IResource[] getResourcesToCompare(ResourceMapping[] mappings, Subscriber subscriber) throws InvocationTargetException { - ISynchronizationScopeManager manager = new SynchronizationScopeManager("", //$NON-NLS-1$ - mappings, SubscriberResourceMappingContext.createContext(subscriber), true); - try { - return getResourcesToCompare(manager); - } finally { - manager.dispose(); - } + ISynchronizationScopeManager manager = new SynchronizationScopeManager("", //$NON-NLS-1$ + mappings, SubscriberResourceMappingContext.createContext(subscriber), true); + try { + return getResourcesToCompare(manager); + } finally { + manager.dispose(); + } + } + + protected IResource[] getResourcesToCompare(final Subscriber subscriber) throws InvocationTargetException { + return getResourcesToCompare(getCVSResourceMappings(), subscriber); } - protected IResource[] getResourcesToCompare(final Subscriber subscriber) throws InvocationTargetException { - return getResourcesToCompare(getCVSResourceMappings(), subscriber); - } - - protected ResourceMappingContext getResourceMappingContext() { + protected ResourceMappingContext getResourceMappingContext() { return SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); } public static IResource[] getResourcesToCompare(final ISynchronizationScopeManager manager) throws InvocationTargetException { - // Determine what resources need to be synchronized. - // Use a resource mapping context to include any relevant remote resources - final IResource[][] resources = new IResource[][] { null }; - try { + // Determine what resources need to be synchronized. + // Use a resource mapping context to include any relevant remote resources + final IResource[][] resources = new IResource[][] { null }; + try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { try { resources[0] = getRootTraversalResources(manager, monitor); @@ -113,50 +113,50 @@ public abstract class WorkspaceTraversalAction extends WorkspaceAction { throw new InvocationTargetException(e); } }); - } catch (InterruptedException e) { - // Canceled - return null; - } - return resources[0]; - } - - public static IResource[] getProjects(IResource[] resources) { + } catch (InterruptedException e) { + // Canceled + return null; + } + return resources[0]; + } + + public static IResource[] getProjects(IResource[] resources) { Set<IProject> projects = new HashSet<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - projects.add(resource.getProject()); - } - return projects.toArray(new IResource[projects.size()]); - } - - /** - * - * @param mappings - * @return - * - * @deprecated need to find a better way to do this - */ - @Deprecated + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + projects.add(resource.getProject()); + } + return projects.toArray(new IResource[projects.size()]); + } + + /** + * + * @param mappings + * @return + * + * @deprecated need to find a better way to do this + */ + @Deprecated public static boolean isLogicalModel(ResourceMapping[] mappings) { - for (int i = 0; i < mappings.length; i++) { - ResourceMapping mapping = mappings[i]; - if (! (mapping.getModelObject() instanceof IResource) ) { - return true; - } - } - return false; - } - - protected IFile getSelectedFile() { - ResourceMapping[] mappings = getCVSResourceMappings(); - if (mappings.length == 1) { - IResource resource = Utils.getResource(mappings[0].getModelObject()); - if (resource != null && resource.getType() == IResource.FILE) - return (IFile)resource; - } - return null; - } - + for (int i = 0; i < mappings.length; i++) { + ResourceMapping mapping = mappings[i]; + if (! (mapping.getModelObject() instanceof IResource) ) { + return true; + } + } + return false; + } + + protected IFile getSelectedFile() { + ResourceMapping[] mappings = getCVSResourceMappings(); + if (mappings.length == 1) { + IResource resource = Utils.getResource(mappings[0].getModelObject()); + if (resource != null && resource.getType() == IResource.FILE) + return (IFile)resource; + } + return null; + } + protected boolean hasOutgoingChanges(final RepositoryProviderOperation operation) throws InvocationTargetException, InterruptedException { final boolean[] hasChange = new boolean[] { false }; PlatformUI.getWorkbench().getProgressService().run(true, true, monitor -> { @@ -198,8 +198,8 @@ public abstract class WorkspaceTraversalAction extends WorkspaceAction { */ protected SynchronizationScopeManager getScopeManager() { return new SynchronizationScopeManager( - "", //$NON-NLS-1$ - getCVSResourceMappings(), - getResourceMappingContext(), true); + "", //$NON-NLS-1$ + getCVSResourceMappings(), + getResourceMappingContext(), true); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/CVSOutputConsole.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/CVSOutputConsole.java index 0ac823e15..0ee738a48 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/CVSOutputConsole.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/CVSOutputConsole.java @@ -66,17 +66,17 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener // format for timings printed to console private static final DateFormat TIME_FORMAT; - - static { - DateFormat format; - try { - format = new SimpleDateFormat(CVSUIMessages.Console_resultTimeFormat); - } catch (RuntimeException e) { - // This can happen if the bundle contains an invalid format - format = new SimpleDateFormat("'(took 'm:ss.SSS')')"); //$NON-NLS-1$ - } - TIME_FORMAT = format; - } + + static { + DateFormat format; + try { + format = new SimpleDateFormat(CVSUIMessages.Console_resultTimeFormat); + } catch (RuntimeException e) { + // This can happen if the bundle contains an invalid format + format = new SimpleDateFormat("'(took 'm:ss.SSS')')"); //$NON-NLS-1$ + } + TIME_FORMAT = format; + } // Indicates whether the console is visible in the Console view private boolean visible = false; @@ -86,7 +86,7 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener /* * Constant used for indenting error status printing */ - private static final String NESTING = " "; //$NON-NLS-1$ + private static final String NESTING = " "; //$NON-NLS-1$ /** * Used to notify this console of lifecycle methods <code>init()</code> @@ -220,7 +220,7 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener } } - private void showConsole() { + private void showConsole() { show(false); } @@ -255,7 +255,7 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener @Override public void commandInvoked(Session session, String line) { - if (!session.isOutputToConsole()) return; + if (!session.isOutputToConsole()) return; commandStarted = System.currentTimeMillis(); appendLine(ConsoleDocument.COMMAND, CVSUIMessages.Console_preExecutionDelimiter); appendLine(ConsoleDocument.COMMAND, line); @@ -263,21 +263,21 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener @Override public void messageLineReceived(Session session, String line, IStatus status) { - if (session.isOutputToConsole()) { - appendLine(ConsoleDocument.MESSAGE, " " + line); //$NON-NLS-1$ - } + if (session.isOutputToConsole()) { + appendLine(ConsoleDocument.MESSAGE, " " + line); //$NON-NLS-1$ + } } @Override public void errorLineReceived(Session session, String line, IStatus status) { - if (session.isOutputToConsole()) { - appendLine(ConsoleDocument.ERROR, " " + line); //$NON-NLS-1$ - } + if (session.isOutputToConsole()) { + appendLine(ConsoleDocument.ERROR, " " + line); //$NON-NLS-1$ + } } @Override public void commandCompleted(Session session, IStatus status, Exception exception) { - if (!session.isOutputToConsole()) return; + if (!session.isOutputToConsole()) return; long commandRuntime = System.currentTimeMillis() - commandStarted; String time; try { @@ -288,7 +288,7 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener } String statusText; if (status != null) { - boolean includeRoot = true; + boolean includeRoot = true; if (status.getCode() == CVSStatus.SERVER_ERROR) { statusText = NLS.bind(CVSUIMessages.Console_resultServerError, new String[] { status.getMessage(), time }); includeRoot = false; @@ -305,7 +305,7 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener } appendLine(ConsoleDocument.COMMAND, statusText); if (exception instanceof CoreException) { - outputStatus(((CoreException)exception).getStatus(), true, 1); + outputStatus(((CoreException)exception).getStatus(), true, 1); } } else { statusText = NLS.bind(CVSUIMessages.Console_resultOk, new String[] { time }); @@ -316,14 +316,14 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener private void outputStatus(IStatus status, boolean includeParent, int nestingLevel) { if (includeParent && !status.isOK()) { - outputStatusMessage(status, nestingLevel); - nestingLevel++; + outputStatusMessage(status, nestingLevel); + nestingLevel++; } // Include a CoreException in the status Throwable t = status.getException(); if (t instanceof CoreException) { - outputStatus(((CoreException)t).getStatus(), true, nestingLevel); + outputStatus(((CoreException)t).getStatus(), true, nestingLevel); } // Include child status @@ -333,14 +333,14 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener } } - private void outputStatusMessage(IStatus status, int nesting) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < nesting; i++) { - buffer.append(NESTING); - } - buffer.append(messageLineForStatus(status)); - appendLine(ConsoleDocument.COMMAND, buffer.toString()); - } + private void outputStatusMessage(IStatus status, int nesting) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < nesting; i++) { + buffer.append(NESTING); + } + buffer.append(messageLineForStatus(status)); + appendLine(ConsoleDocument.COMMAND, buffer.toString()); + } @Override public void propertyChange(PropertyChangeEvent event) { @@ -407,21 +407,21 @@ public class CVSOutputConsole extends MessageConsole implements IConsoleListener return new Color(display, rgb); } - /** - * Show the console. - * @param showNoMatterWhat ignore preferences if <code>true</code> - */ - public void show(boolean showNoMatterWhat) { + /** + * Show the console. + * @param showNoMatterWhat ignore preferences if <code>true</code> + */ + public void show(boolean showNoMatterWhat) { if(showNoMatterWhat || showOnMessage) { if(!visible) CVSConsoleFactory.showConsole(); else consoleManager.showConsoleView(this); } - } - - @Override + } + + @Override public String getHelpContextId() { - return IHelpContextIds.CONSOLE_VIEW; - } + return IHelpContextIds.CONSOLE_VIEW; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/ConsolePreferencesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/ConsolePreferencesPage.java index faefc5641..48a26f229 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/ConsolePreferencesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/console/ConsolePreferencesPage.java @@ -82,7 +82,7 @@ public class ConsolePreferencesPage extends FieldEditorPreferencePage implements addField(errorColorEditor); Dialog.applyDialogFont(composite); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.CONSOLE_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.CONSOLE_PREFERENCE_PAGE); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/AbstractCommitAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/AbstractCommitAction.java index 8cfbcd909..38d60aaeb 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/AbstractCommitAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/AbstractCommitAction.java @@ -42,7 +42,7 @@ public abstract class AbstractCommitAction extends CVSModelProviderAction { @Override public void execute() { - final List resources = new ArrayList(); + final List resources = new ArrayList(); try { final IStructuredSelection selection = getActualSelection(); PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { @@ -61,12 +61,12 @@ public abstract class AbstractCommitAction extends CVSModelProviderAction { Utils.handleError(getConfiguration().getSite().getShell(), e, null, null); } if (!resources.isEmpty() && ((IResource[])resources.get(0)).length > 0) { - Shell shell= getConfiguration().getSite().getShell(); - try { - CommitWizard.run(getConfiguration().getSite().getPart(), shell, ((IResource[])resources.get(0))); - } catch (CVSException e) { - CVSUIPlugin.log(e); - } + Shell shell= getConfiguration().getSite().getShell(); + try { + CommitWizard.run(getConfiguration().getSite().getPart(), shell, ((IResource[])resources.get(0))); + } catch (CVSException e) { + CVSUIPlugin.log(e); + } } } @@ -76,7 +76,7 @@ public abstract class AbstractCommitAction extends CVSModelProviderAction { protected abstract ResourceTraversal[] getCommitTraversals(IStructuredSelection selection, IProgressMonitor monitor) throws CoreException; - public static IResource[] getOutgoingChanges(final IResourceDiffTree tree, ResourceTraversal[] traversals, IProgressMonitor monitor) { + public static IResource[] getOutgoingChanges(final IResourceDiffTree tree, ResourceTraversal[] traversals, IProgressMonitor monitor) { final List<IResource> resources = new ArrayList<>(); IDiff[] diffs = tree.getDiffs(traversals); for (int i = 0; i < diffs.length; i++) { @@ -88,8 +88,8 @@ public abstract class AbstractCommitAction extends CVSModelProviderAction { } } return resources.toArray(new IResource[resources.size()]); - } - + } + public static boolean hasLocalChange(IDiff diff) { if (diff instanceof IThreeWayDiff) { IThreeWayDiff twd = (IThreeWayDiff) diff; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CVSModelSynchronizeParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CVSModelSynchronizeParticipant.java index 61169b735..21aebca24 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CVSModelSynchronizeParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CVSModelSynchronizeParticipant.java @@ -28,13 +28,13 @@ import org.eclipse.team.ui.synchronize.ModelSynchronizeParticipant; public abstract class CVSModelSynchronizeParticipant extends ModelSynchronizeParticipant { public static PreferencePage[] addCVSPreferencePages(PreferencePage[] inheritedPages) { - PreferencePage[] pages = new PreferencePage[inheritedPages.length + 1]; - for (int i = 0; i < inheritedPages.length; i++) { - pages[i] = inheritedPages[i]; - } - pages[pages.length - 1] = new ComparePreferencePage(); - pages[pages.length - 1].setTitle(CVSUIMessages.CVSParticipant_2); - return pages; + PreferencePage[] pages = new PreferencePage[inheritedPages.length + 1]; + for (int i = 0; i < inheritedPages.length; i++) { + pages[i] = inheritedPages[i]; + } + pages[pages.length - 1] = new ComparePreferencePage(); + pages[pages.length - 1].setTitle(CVSUIMessages.CVSParticipant_2); + return pages; } public CVSModelSynchronizeParticipant() { @@ -46,7 +46,7 @@ public abstract class CVSModelSynchronizeParticipant extends ModelSynchronizePar } public PreferencePage[] getPreferencePages() { - return addCVSPreferencePages(super.getPreferencePages()); + return addCVSPreferencePages(super.getPreferencePages()); } public ModelProvider[] getEnabledModelProviders() { @@ -71,7 +71,7 @@ public abstract class CVSModelSynchronizeParticipant extends ModelSynchronizePar } protected ILabelDecorator getLabelDecorator(ISynchronizePageConfiguration configuration) { - return new CVSParticipantLabelDecorator(configuration); + return new CVSParticipantLabelDecorator(configuration); } protected void initializeConfiguration(ISynchronizePageConfiguration configuration) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetActionProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetActionProvider.java index fcb025868..44f22d2d5 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetActionProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetActionProvider.java @@ -69,7 +69,7 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { } /* package */void createChangeSet(IDiff[] diffs) { - ActiveChangeSet set = getChangeSetCapability().createChangeSet(getConfiguration(), diffs); + ActiveChangeSet set = getChangeSetCapability().createChangeSet(getConfiguration(), diffs); if (set != null) { getActiveChangeSetManager().add(set); } @@ -110,8 +110,8 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { private final ActiveChangeSet set; - public AddToChangeSetAction(ISynchronizePageConfiguration configuration, ActiveChangeSet set, ISelection selection) { - super(set == null ? TeamUIMessages.ChangeSetActionGroup_2 : escapeActionText(set.getTitle()), configuration); + public AddToChangeSetAction(ISynchronizePageConfiguration configuration, ActiveChangeSet set, ISelection selection) { + super(set == null ? TeamUIMessages.ChangeSetActionGroup_2 : escapeActionText(set.getTitle()), configuration); this.set = set; selectionChanged(selection); } @@ -140,7 +140,7 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { private abstract class ChangeSetAction extends BaseSelectionListenerAction { - public ChangeSetAction(String title, ISynchronizePageConfiguration configuration) { + public ChangeSetAction(String title, ISynchronizePageConfiguration configuration) { super(title); } @@ -172,8 +172,8 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { @Override public void run() { ActiveChangeSet set = getSelectedSet(); - if (set == null) return; - getChangeSetCapability().editChangeSet(internalGetSynchronizePageConfiguration(), set); + if (set == null) return; + getChangeSetCapability().editChangeSet(internalGetSynchronizePageConfiguration(), set); } } @@ -246,7 +246,7 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { public void run() { int sortCriteria = getSortCriteria(internalGetSynchronizePageConfiguration()); if (isChecked() && sortCriteria != criteria) { - setSortCriteria(internalGetSynchronizePageConfiguration(), criteria); + setSortCriteria(internalGetSynchronizePageConfiguration(), criteria); update(); ((SynchronizePageConfiguration)internalGetSynchronizePageConfiguration()).getPage().getViewer().refresh(); } @@ -257,7 +257,7 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { } } - public static int getSortCriteria(ISynchronizePageConfiguration configuration) { + public static int getSortCriteria(ISynchronizePageConfiguration configuration) { int sortCriteria = ChangeSetSorter.DATE; if (configuration != null) { Object o = configuration.getProperty(P_LAST_COMMENTSORT); @@ -436,7 +436,7 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { } public ChangeSetCapability getChangeSetCapability() { - ISynchronizeParticipant participant = getSynchronizePageConfiguration().getParticipant(); + ISynchronizeParticipant participant = getSynchronizePageConfiguration().getParticipant(); if (participant instanceof IChangeSetProvider) { IChangeSetProvider provider = (IChangeSetProvider) participant; return provider.getChangeSetCapability(); @@ -602,11 +602,11 @@ public class ChangeSetActionProvider extends ResourceModelActionProvider { super.setContext(context); if (context != null) { if (editChangeSet != null) - editChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); + editChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); if (removeChangeSet != null) - removeChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); + removeChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); if (makeDefault != null) - makeDefault.selectionChanged((IStructuredSelection)getContext().getSelection()); + makeDefault.selectionChanged((IStructuredSelection)getContext().getSelection()); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetContentProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetContentProvider.java index 2149d4548..3f4d38414 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetContentProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetContentProvider.java @@ -136,21 +136,21 @@ public class ChangeSetContentProvider extends ResourceModelContentProvider imple private void handleSetChange(final ChangeSet set, final IPath[] paths) { try { getTheRest().beginInput(); - for (int i = 0; i < paths.length; i++) { + for (int i = 0; i < paths.length; i++) { IPath path = paths[i]; - boolean isContained = ((DiffChangeSet)set).contains(path); + boolean isContained = ((DiffChangeSet)set).contains(path); if (isContained) { IDiff diff = ((DiffChangeSet)set).getDiffTree().getDiff(path); if (diff != null) { getTheRest().remove(ResourceDiffTree.getResourceFor(diff)); } } else { - IDiff diff = getContext().getDiffTree().getDiff(path); - if (diff != null && !isContainedInSet(diff)) { - getTheRest().add(diff); - } - } - } + IDiff diff = getContext().getDiffTree().getDiff(path); + if (diff != null && !isContainedInSet(diff)) { + getTheRest().add(diff); + } + } + } } finally { getTheRest().endInput(null); } @@ -738,7 +738,7 @@ public class ChangeSetContentProvider extends ResourceModelContentProvider imple } - private ChangeSet[] getSetsShowingPropogatedStateFrom(IPath[] paths) { + private ChangeSet[] getSetsShowingPropogatedStateFrom(IPath[] paths) { Set result = new HashSet(); for (int i = 0; i < paths.length; i++) { IPath path = paths[i]; @@ -750,7 +750,7 @@ public class ChangeSetContentProvider extends ResourceModelContentProvider imple } return (ChangeSet[]) result.toArray(new ChangeSet[result.size()]); } - + protected DiffChangeSet[] getSetsShowingPropogatedStateFrom(IPath path) { List result = new ArrayList(); DiffChangeSet[] allSets = getAllSets(); @@ -764,13 +764,13 @@ public class ChangeSetContentProvider extends ResourceModelContentProvider imple } public ChangeSetCapability getChangeSetCapability() { - ISynchronizeParticipant participant = getConfiguration().getParticipant(); - if (participant instanceof IChangeSetProvider) { - IChangeSetProvider provider = (IChangeSetProvider) participant; - return provider.getChangeSetCapability(); - } - return null; - } + ISynchronizeParticipant participant = getConfiguration().getParticipant(); + if (participant instanceof IChangeSetProvider) { + IChangeSetProvider provider = (IChangeSetProvider) participant; + return provider.getChangeSetCapability(); + } + return null; + } private Set getVisibleSetsInViewer() { TreeViewer viewer = (TreeViewer)getViewer(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetLabelProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetLabelProvider.java index bed3157bc..a989ed50c 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetLabelProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetLabelProvider.java @@ -205,9 +205,9 @@ public class ChangeSetLabelProvider extends ResourceModelLabelProvider { public Font getFont(Object element) { element = internalGetElement(element); - if (element instanceof ActiveChangeSet && isDefaultActiveSet((ActiveChangeSet)element)) { + if (element instanceof ActiveChangeSet && isDefaultActiveSet((ActiveChangeSet)element)) { return JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT); - } + } return super.getFont(element); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetSorter.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetSorter.java index ebeb3c0f8..49f69c876 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetSorter.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ChangeSetSorter.java @@ -38,14 +38,14 @@ public class ChangeSetSorter extends ResourceModelSorter { //if one or both objects are not resources, returned a comparison //based on class. if (o1 instanceof ChangeSet && o2 instanceof ChangeSet) { - ChangeSet s1 = (ChangeSet) o1; - ChangeSet s2 = (ChangeSet) o2; - if (s1 instanceof ActiveChangeSet && s2 instanceof ActiveChangeSet) { - return compareNames(((ActiveChangeSet)s1).getTitle(), ((ActiveChangeSet)s2).getTitle()); - } - if (s1 instanceof CVSCheckedInChangeSet && s2 instanceof CVSCheckedInChangeSet) { - CVSCheckedInChangeSet r1 = (CVSCheckedInChangeSet)s1; - CVSCheckedInChangeSet r2 = (CVSCheckedInChangeSet)s2; + ChangeSet s1 = (ChangeSet) o1; + ChangeSet s2 = (ChangeSet) o2; + if (s1 instanceof ActiveChangeSet && s2 instanceof ActiveChangeSet) { + return compareNames(((ActiveChangeSet)s1).getTitle(), ((ActiveChangeSet)s2).getTitle()); + } + if (s1 instanceof CVSCheckedInChangeSet && s2 instanceof CVSCheckedInChangeSet) { + CVSCheckedInChangeSet r1 = (CVSCheckedInChangeSet)s1; + CVSCheckedInChangeSet r2 = (CVSCheckedInChangeSet)s2; if (getCommentCriteria() == DATE) return r1.getDate().compareTo(r2.getDate()); else if (getCommentCriteria() == COMMENT) @@ -54,17 +54,17 @@ public class ChangeSetSorter extends ResourceModelSorter { return compareNames(r1.getAuthor(), r2.getAuthor()); else return 0; - } - if (s1 instanceof ActiveChangeSet) { - return -1; - } else if (s2 instanceof ActiveChangeSet) { - return 1; - } - if (s1 instanceof CVSCheckedInChangeSet) { - return -1; - } else if (s2 instanceof CVSCheckedInChangeSet) { - return 1; - } + } + if (s1 instanceof ActiveChangeSet) { + return -1; + } else if (s2 instanceof ActiveChangeSet) { + return 1; + } + if (s1 instanceof CVSCheckedInChangeSet) { + return -1; + } else if (s2 instanceof CVSCheckedInChangeSet) { + return 1; + } } return super.compare(viewer, o1, o2); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CheckedInChangeSetCollector.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CheckedInChangeSetCollector.java index d5eadefe3..756524d24 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CheckedInChangeSetCollector.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CheckedInChangeSetCollector.java @@ -43,10 +43,10 @@ import org.eclipse.team.ui.synchronize.SynchronizePageActionGroup; public class CheckedInChangeSetCollector extends BatchingChangeSetManager implements ILogsFetchedListener { /* - * Constant used to store the log entry handler in the configuration so it can - * be kept around over layout changes - */ - private static final String LOG_ENTRY_HANDLER = CVSUIPlugin.ID + ".LogEntryHandler"; //$NON-NLS-1$ + * Constant used to store the log entry handler in the configuration so it can + * be kept around over layout changes + */ + private static final String LOG_ENTRY_HANDLER = CVSUIPlugin.ID + ".LogEntryHandler"; //$NON-NLS-1$ /* ***************************************************************************** * Special sync info that has its kind already calculated. @@ -71,17 +71,17 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem } @Override public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) { - if (event.getTree().isEmpty()) { - ChangeSet changeSet = getChangeSet(event.getTree()); - if (changeSet != null) { - remove(changeSet); - } - } else { - ChangeSet changeSet = getChangeSet(event.getTree()); - if (changeSet != null) { - fireResourcesChangedEvent(changeSet, getAffectedPaths(event)); - } - } + if (event.getTree().isEmpty()) { + ChangeSet changeSet = getChangeSet(event.getTree()); + if (changeSet != null) { + remove(changeSet); + } + } else { + ChangeSet changeSet = getChangeSet(event.getTree()); + if (changeSet != null) { + fireResourcesChangedEvent(changeSet, getAffectedPaths(event)); + } + } } private IPath[] getAffectedPaths(IDiffChangeEvent event) { Set<IPath> result = new HashSet<>(); @@ -110,115 +110,115 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem private final Subscriber subscriber; private HashSet<ChangeSet> updatedSets; - - public CheckedInChangeSetCollector(ISynchronizePageConfiguration configuration, Subscriber subscriber) { + + public CheckedInChangeSetCollector(ISynchronizePageConfiguration configuration, Subscriber subscriber) { this.configuration = configuration; this.subscriber = subscriber; } - - /** - * Return the configuration for the page that is displaying the model created - * using this collector. - * @return the configuration for the page that is displaying the model created - * using this collector - */ - public final ISynchronizePageConfiguration getConfiguration() { - return configuration; - } - - @Override + + /** + * Return the configuration for the page that is displaying the model created + * using this collector. + * @return the configuration for the page that is displaying the model created + * using this collector + */ + public final ISynchronizePageConfiguration getConfiguration() { + return configuration; + } + + @Override protected void handleSetAdded(ChangeSet set) { - ((DiffChangeSet)set).getDiffTree().addDiffChangeListener(diffTreeListener); - super.handleSetAdded(set); - if (updatedSets != null) { - updatedSets.add(set); - ((DiffTree)((DiffChangeSet)set).getDiffTree()).beginInput(); - } - } - - @Override + ((DiffChangeSet)set).getDiffTree().addDiffChangeListener(diffTreeListener); + super.handleSetAdded(set); + if (updatedSets != null) { + updatedSets.add(set); + ((DiffTree)((DiffChangeSet)set).getDiffTree()).beginInput(); + } + } + + @Override protected void handleSetRemoved(ChangeSet set) { - ((DiffChangeSet)set).getDiffTree().removeDiffChangeListener(diffTreeListener); - super.handleSetRemoved(set); - } - - protected ChangeSet getChangeSet(IDiffTree tree) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet changeSet = sets[i]; - if (((DiffChangeSet)changeSet).getDiffTree() == tree) { - return changeSet; - } - } - return null; - } - - public void handleChange(IDiffChangeEvent event) { + ((DiffChangeSet)set).getDiffTree().removeDiffChangeListener(diffTreeListener); + super.handleSetRemoved(set); + } + + protected ChangeSet getChangeSet(IDiffTree tree) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet changeSet = sets[i]; + if (((DiffChangeSet)changeSet).getDiffTree() == tree) { + return changeSet; + } + } + return null; + } + + public void handleChange(IDiffChangeEvent event) { List<IPath> removals = new ArrayList<>(); List<IDiff> additions = new ArrayList<>(); - removals.addAll(Arrays.asList(event.getRemovals())); - additions.addAll(Arrays.asList(event.getAdditions())); - IDiff[] changed = event.getChanges(); - for (int i = 0; i < changed.length; i++) { - IDiff diff = changed[i]; - additions.add(diff); - removals.add(diff.getPath()); - } - if (!removals.isEmpty()) { - remove(removals.toArray(new IPath[removals.size()])); - } - if (!additions.isEmpty()) { - add(additions.toArray(new IDiff[additions.size()])); - } - } - - protected void remove(IPath[] paths) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - DiffChangeSet set = (DiffChangeSet)sets[i]; - set.remove(paths); - } - } - - public synchronized LogEntryCacheUpdateHandler getLogEntryHandler() { - LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)getConfiguration().getProperty(LOG_ENTRY_HANDLER); - if (handler == null) { - handler = initializeLogEntryHandler(getConfiguration()); - } - handler.setListener(this); - return handler; - } - - /* - * Initialize the log entry handler and place it in the configuration - */ - private LogEntryCacheUpdateHandler initializeLogEntryHandler(final ISynchronizePageConfiguration configuration) { - final LogEntryCacheUpdateHandler logEntryHandler = new LogEntryCacheUpdateHandler(configuration); - configuration.setProperty(LOG_ENTRY_HANDLER, logEntryHandler); - // Use an action group to get notified when the configuration is disposed - configuration.addActionContribution(new SynchronizePageActionGroup() { - @Override + removals.addAll(Arrays.asList(event.getRemovals())); + additions.addAll(Arrays.asList(event.getAdditions())); + IDiff[] changed = event.getChanges(); + for (int i = 0; i < changed.length; i++) { + IDiff diff = changed[i]; + additions.add(diff); + removals.add(diff.getPath()); + } + if (!removals.isEmpty()) { + remove(removals.toArray(new IPath[removals.size()])); + } + if (!additions.isEmpty()) { + add(additions.toArray(new IDiff[additions.size()])); + } + } + + protected void remove(IPath[] paths) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + DiffChangeSet set = (DiffChangeSet)sets[i]; + set.remove(paths); + } + } + + public synchronized LogEntryCacheUpdateHandler getLogEntryHandler() { + LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)getConfiguration().getProperty(LOG_ENTRY_HANDLER); + if (handler == null) { + handler = initializeLogEntryHandler(getConfiguration()); + } + handler.setListener(this); + return handler; + } + + /* + * Initialize the log entry handler and place it in the configuration + */ + private LogEntryCacheUpdateHandler initializeLogEntryHandler(final ISynchronizePageConfiguration configuration) { + final LogEntryCacheUpdateHandler logEntryHandler = new LogEntryCacheUpdateHandler(configuration); + configuration.setProperty(LOG_ENTRY_HANDLER, logEntryHandler); + // Use an action group to get notified when the configuration is disposed + configuration.addActionContribution(new SynchronizePageActionGroup() { + @Override public void dispose() { - super.dispose(); - LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)configuration.getProperty(LOG_ENTRY_HANDLER); - if (handler != null) { - handler.shutdown(); - configuration.setProperty(LOG_ENTRY_HANDLER, null); - } - } - }); - return logEntryHandler; - } + super.dispose(); + LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)configuration.getProperty(LOG_ENTRY_HANDLER); + if (handler != null) { + handler.shutdown(); + configuration.setProperty(LOG_ENTRY_HANDLER, null); + } + } + }); + return logEntryHandler; + } - protected void add(IDiff[] diffs) { - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) - try { - handler.fetch(getSyncInfos(diffs)); - } catch (CVSException e) { - CVSUIPlugin.log(e); - } - } + protected void add(IDiff[] diffs) { + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) + try { + handler.fetch(getSyncInfos(diffs)); + } catch (CVSException e) { + CVSUIPlugin.log(e); + } + } private SyncInfo[] getSyncInfos(IDiff[] diffs) { SyncInfoSet set = new SyncInfoSet(); @@ -235,11 +235,11 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem @Override public void dispose() { - // No longer listen for log entry changes - // (The handler is disposed with the page) - disposed = true; - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) handler.setListener(null); + // No longer listen for log entry changes + // (The handler is disposed with the page) + disposed = true; + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) handler.setListener(null); getConfiguration().setProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR, null); logEntryCache = null; super.dispose(); @@ -248,17 +248,17 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem /** * Fetch the log histories for the remote changes and use this information * to add each resource to an appropriate commit set. - */ - private void handleRemoteChanges(final SyncInfo[] infos, final LogEntryCache logEntries, final IProgressMonitor monitor) { - try { - beginSetUpdate(); - addLogEntries(infos, logEntries, monitor); - } finally { - endSetUpdate(monitor); - } - } + */ + private void handleRemoteChanges(final SyncInfo[] infos, final LogEntryCache logEntries, final IProgressMonitor monitor) { + try { + beginSetUpdate(); + addLogEntries(infos, logEntries, monitor); + } finally { + endSetUpdate(monitor); + } + } - private void beginSetUpdate() { + private void beginSetUpdate() { updatedSets = new HashSet<>(); } @@ -299,15 +299,15 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem * @param log the cvs log for this node */ private void addSyncInfoToCommentNode(SyncInfo info, LogEntryCache logs) { - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) { + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) { ICVSRemoteResource remoteResource = handler.getRemoteResource(info); if(handler.getSubscriber() instanceof CVSCompareSubscriber && remoteResource != null) { addMultipleRevisions(info, logs, remoteResource); } else { addSingleRevision(info, logs, remoteResource); } - } + } } /* @@ -319,7 +319,7 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem */ private void addSingleRevision(SyncInfo info, LogEntryCache logs, ICVSRemoteResource remoteResource) { ILogEntry logEntry = logs.getLogEntry(remoteResource); - if (remoteResource != null && !remoteResource.isFolder()) { + if (remoteResource != null && !remoteResource.isFolder()) { // For incoming deletions grab the comment for the latest on the same branch // which is now in the attic. try { @@ -337,11 +337,11 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem } catch (TeamException e) { // continue and skip deletion checks } - } + } addRemoteChange(info, remoteResource, logEntry); } - /* + /* * Add multiple log entries to the model. * * @param info @@ -369,43 +369,43 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem return false; } - /* - * Add the remote change to an incoming commit set - */ - private void addRemoteChange(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { - if (disposed) return; - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if(handler != null && remoteResource != null && logEntry != null && handler.isRemoteChange(info)) { - if(requiresCustomSyncInfo(info, remoteResource, logEntry)) { - info = new CVSUpdatableSyncInfo(info.getKind(), info.getLocal(), info.getBase(), (RemoteResource)logEntry.getRemoteFile(), getSubscriber()); - try { - info.init(); - } catch (TeamException e) { - // this shouldn't happen, we've provided our own calculate kind - } - } - IDiff diff = getConverter().getDeltaFor(info); - // Only add the info if the base and remote differ - IResourceVariant base = info.getBase(); - IResourceVariant remote = info.getRemote(); - if ((base == null && remote != null) || (remote == null && base != null) || (remote != null && base != null && !base.equals(remote))) { - synchronized(this) { - CVSCheckedInChangeSet set = getChangeSetFor(logEntry); - if (set == null) { - set = createChangeSetFor(logEntry); - add(set); - } + /* + * Add the remote change to an incoming commit set + */ + private void addRemoteChange(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { + if (disposed) return; + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if(handler != null && remoteResource != null && logEntry != null && handler.isRemoteChange(info)) { + if(requiresCustomSyncInfo(info, remoteResource, logEntry)) { + info = new CVSUpdatableSyncInfo(info.getKind(), info.getLocal(), info.getBase(), (RemoteResource)logEntry.getRemoteFile(), getSubscriber()); + try { + info.init(); + } catch (TeamException e) { + // this shouldn't happen, we've provided our own calculate kind + } + } + IDiff diff = getConverter().getDeltaFor(info); + // Only add the info if the base and remote differ + IResourceVariant base = info.getBase(); + IResourceVariant remote = info.getRemote(); + if ((base == null && remote != null) || (remote == null && base != null) || (remote != null && base != null && !base.equals(remote))) { + synchronized(this) { + CVSCheckedInChangeSet set = getChangeSetFor(logEntry); + if (set == null) { + set = createChangeSetFor(logEntry); + add(set); + } set.add(diff); - } - } - } else { - // The info was not retrieved for the remote change for some reason. - // Add the node to the root - //addToDefaultSet(DEFAULT_INCOMING_SET_NAME, info); - } - } + } + } + } else { + // The info was not retrieved for the remote change for some reason. + // Add the node to the root + //addToDefaultSet(DEFAULT_INCOMING_SET_NAME, info); + } + } - private SyncInfoToDiffConverter getConverter() { + private SyncInfoToDiffConverter getConverter() { SyncInfoToDiffConverter converter = Adapters.adapt(subscriber, SyncInfoToDiffConverter.class); if (converter == null) converter = SyncInfoToDiffConverter.getDefault(); @@ -414,22 +414,22 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem private CVSCheckedInChangeSet createChangeSetFor(ILogEntry logEntry) { return new CVSCheckedInChangeSet(logEntry); - } + } - private CVSCheckedInChangeSet getChangeSetFor(ILogEntry logEntry) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (set instanceof CVSCheckedInChangeSet && - set.getComment().equals(logEntry.getComment()) && - ((CVSCheckedInChangeSet)set).getAuthor().equals(logEntry.getAuthor())) { - return (CVSCheckedInChangeSet)set; - } - } - return null; - } - - private boolean requiresCustomSyncInfo(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { + private CVSCheckedInChangeSet getChangeSetFor(ILogEntry logEntry) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (set instanceof CVSCheckedInChangeSet && + set.getComment().equals(logEntry.getComment()) && + ((CVSCheckedInChangeSet)set).getAuthor().equals(logEntry.getAuthor())) { + return (CVSCheckedInChangeSet)set; + } + } + return null; + } + + private boolean requiresCustomSyncInfo(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { // Only interested in non-deletions if (logEntry.isDeletion()) return false; // Only require a custom sync info if the remote of the sync info @@ -438,17 +438,17 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem if (remote == null) return true; return !remote.equals(remoteResource); } - + /* * @see * org.eclipse.team.ui.synchronize.SyncInfoSetChangeSetCollector#waitUntilDone( * org.eclipse.core.runtime.IProgressMonitor) */ - public void waitUntilDone(IProgressMonitor monitor) { + public void waitUntilDone(IProgressMonitor monitor) { monitor.worked(1); // wait for the event handler to process changes. - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) { + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) { while(handler.getEventHandlerJob().getState() != Job.NONE) { monitor.worked(1); try { @@ -457,26 +457,26 @@ public class CheckedInChangeSetCollector extends BatchingChangeSetManager implem } Policy.checkCanceled(monitor); } - } + } monitor.worked(1); - } + } - @Override + @Override public void logEntriesFetched(SyncInfoSet set, LogEntryCache logEntryCache, IProgressMonitor monitor) { - if (disposed) return; - // Hold on to the cache so we can use it while commit sets are visible - this.logEntryCache = logEntryCache; - try { - beginInput(); - handleRemoteChanges(set.getSyncInfos(), logEntryCache, monitor); - } finally { - endInput(monitor); - } - } + if (disposed) return; + // Hold on to the cache so we can use it while commit sets are visible + this.logEntryCache = logEntryCache; + try { + beginInput(); + handleRemoteChanges(set.getSyncInfos(), logEntryCache, monitor); + } finally { + endInput(monitor); + } + } - public ICVSRemoteFile getImmediatePredecessor(ICVSRemoteFile file) throws TeamException { - if (logEntryCache != null) - return logEntryCache.getImmediatePredecessor(file); - return null; - } + public ICVSRemoteFile getImmediatePredecessor(ICVSRemoteFile file) throws TeamException { + if (logEntryCache != null) + return logEntryCache.getImmediatePredecessor(file); + return null; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CreatePatchAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CreatePatchAction.java index f910d7279..63a741698 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CreatePatchAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/CreatePatchAction.java @@ -50,7 +50,7 @@ public class CreatePatchAction extends CVSModelProviderAction implements IDiffCh } return getSynchronizationContext().getDiffTree().countFor(IThreeWayDiff.CONFLICTING, IThreeWayDiff.DIRECTION_MASK) > 0; } - + private IResource[] getVisibleResources(ResourceTraversal[] traversals) { final Set resources = new HashSet(); final IResourceDiffTree diffTree = getSynchronizationContext().getDiffTree(); @@ -69,14 +69,14 @@ public class CreatePatchAction extends CVSModelProviderAction implements IDiffCh return (IResource[]) resources.toArray(new IResource[resources.size()]); } - @Override + @Override protected String getBundleKeyPrefix() { - return "GenerateDiffFileAction."; //$NON-NLS-1$ - } - - @Override + return "GenerateDiffFileAction."; //$NON-NLS-1$ + } + + @Override public void execute() { - final ResourceTraversal [][] traversals = new ResourceTraversal[][] { null }; + final ResourceTraversal [][] traversals = new ResourceTraversal[][] { null }; try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { try { @@ -98,7 +98,7 @@ public class CreatePatchAction extends CVSModelProviderAction implements IDiffCh GenerateDiffFileWizard.run(getConfiguration().getSite().getPart(), resources, false); } } - } + } @Override public void diffsChanged(IDiffChangeEvent event, IProgressMonitor monitor) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/MergeSubscriberContext.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/MergeSubscriberContext.java index 476f70639..82f746f13 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/MergeSubscriberContext.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/MergeSubscriberContext.java @@ -115,7 +115,7 @@ public class MergeSubscriberContext extends CVSSubscriberMergeContext { boolean equals(IThreeWayDiff currentDiff, IThreeWayDiff diffTreeDiff) { return currentDiff != null - && currentDiff.getKind() == diffTreeDiff.getKind() + && currentDiff.getKind() == diffTreeDiff.getKind() && currentDiff.getDirection() == diffTreeDiff.getDirection(); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelCompareParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelCompareParticipant.java index 13337f45f..a1fe01b2d 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelCompareParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelCompareParticipant.java @@ -58,9 +58,9 @@ public class ModelCompareParticipant extends CVSModelSynchronizeParticipant impl @Override public ChangeSetCapability getChangeSetCapability() { - if (capability == null) { - capability = new CompareChangeSetCapability(); - } - return capability; + if (capability == null) { + capability = new CompareChangeSetCapability(); + } + return capability; } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelParticipantChangeSetCapability.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelParticipantChangeSetCapability.java index f4c44a78d..3fd2596f9 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelParticipantChangeSetCapability.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelParticipantChangeSetCapability.java @@ -22,7 +22,7 @@ public abstract class ModelParticipantChangeSetCapability extends ChangeSetCapab @Override public boolean enableChangeSetsByDefault() { - return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_COMMIT_SET_DEFAULT_ENABLEMENT); + return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_COMMIT_SET_DEFAULT_ENABLEMENT); } @Override @@ -32,7 +32,7 @@ public abstract class ModelParticipantChangeSetCapability extends ChangeSetCapab @Override public boolean enableCheckedInChangeSetsFor(ISynchronizePageConfiguration configuration) { - return supportsCheckedInChangeSets() && + return supportsCheckedInChangeSets() && configuration.getMode() != ISynchronizePageConfiguration.OUTGOING_MODE; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelReplaceOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelReplaceOperation.java index c44647716..a3364b576 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelReplaceOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelReplaceOperation.java @@ -84,10 +84,10 @@ public class ModelReplaceOperation extends ModelUpdateOperation { result[0] = dialog.open(); }); - if (result[0] == 2) - throw new OperationCanceledException(); - hasPrompted = true; - return result[0] == 0; + if (result[0] == 2) + throw new OperationCanceledException(); + hasPrompted = true; + return result[0] == 0; } private boolean hasLocalChanges() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelSynchronizeWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelSynchronizeWizard.java index 5e73e6371..13e68b6f7 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelSynchronizeWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/ModelSynchronizeWizard.java @@ -35,10 +35,10 @@ public class ModelSynchronizeWizard extends ParticipantSynchronizeWizard { private GlobalRefreshElementSelectionPage selectionPage; - private boolean isShowModelSync() { + private boolean isShowModelSync() { return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_ENABLE_MODEL_SYNC); } - + @Override protected void createParticipant() { if (isShowModelSync()) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/OpenChangeSetAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/OpenChangeSetAction.java index 7cd2e0035..58b40232e 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/OpenChangeSetAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/OpenChangeSetAction.java @@ -45,25 +45,25 @@ import com.ibm.icu.text.DateFormat; class OpenChangeSetAction extends ResourceModelParticipantAction { - protected OpenChangeSetAction(ISynchronizePageConfiguration configuration) { - super(CVSUIMessages.OpenCommitSetAction_20, configuration); + protected OpenChangeSetAction(ISynchronizePageConfiguration configuration) { + super(CVSUIMessages.OpenCommitSetAction_20, configuration); ISelection selection = configuration.getSite().getSelectionProvider().getSelection(); if (selection != null) selectionChanged(selection); - } - - private ChangeSet getChangeSet(IStructuredSelection selection) { - // First, check to see if a change set is selected directly - if (selection.size() == 1) { - Object o = selection.getFirstElement(); - if (o instanceof IAdaptable) { - ChangeSet set = ((IAdaptable)o).getAdapter(ChangeSet.class); - if (set != null) - return set; - } - } - // Failing that, check to see if all the selected elements and their children are in the same change set - if (selection instanceof TreeSelection) { + } + + private ChangeSet getChangeSet(IStructuredSelection selection) { + // First, check to see if a change set is selected directly + if (selection.size() == 1) { + Object o = selection.getFirstElement(); + if (o instanceof IAdaptable) { + ChangeSet set = ((IAdaptable)o).getAdapter(ChangeSet.class); + if (set != null) + return set; + } + } + // Failing that, check to see if all the selected elements and their children are in the same change set + if (selection instanceof TreeSelection) { TreeSelection ts = (TreeSelection) selection; TreePath[] paths = ts.getPaths(); if (paths.length > 0) { @@ -79,8 +79,8 @@ class OpenChangeSetAction extends ResourceModelParticipantAction { return set; } } - return null; - } + return null; + } private ChangeSet getChangeSet(TreePath treePath) { Object test = treePath.getFirstSegment(); @@ -90,70 +90,70 @@ class OpenChangeSetAction extends ResourceModelParticipantAction { } return null; } - + @Override protected boolean isEnabledForSelection(IStructuredSelection selection) { - // The selection only contains appropriate files so - // only enable if the selection is contained within a single change set - ChangeSet set = getChangeSet(selection); - return set != null; + // The selection only contains appropriate files so + // only enable if the selection is contained within a single change set + ChangeSet set = getChangeSet(selection); + return set != null; } - public void openEditor(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - try { + public void openEditor(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + try { IDiff[] diffs = getSelectedDiffs(monitor); if (diffs.length > 0) { - ICVSRepositoryLocation location = getLocation(diffs[0]); - if (location == null) { - throw new CVSException(CVSUIMessages.OpenCommitSetAction_21); - } - CompareTreeBuilder builder = new CompareTreeBuilder(location, null, null); - if (buildTrees(builder, diffs)) { - builder.cacheContents(monitor); - builder.openCompareEditor(getConfiguration().getSite().getPart().getSite().getPage(), getCompareTitle(), getCompareToolTip()); - } + ICVSRepositoryLocation location = getLocation(diffs[0]); + if (location == null) { + throw new CVSException(CVSUIMessages.OpenCommitSetAction_21); + } + CompareTreeBuilder builder = new CompareTreeBuilder(location, null, null); + if (buildTrees(builder, diffs)) { + builder.cacheContents(monitor); + builder.openCompareEditor(getConfiguration().getSite().getPart().getSite().getPage(), getCompareTitle(), getCompareToolTip()); + } } } catch (CoreException e) { throw new InvocationTargetException(e); } - } - - private IDiff[] getSelectedDiffs(IProgressMonitor monitor) throws CoreException { - ResourceTraversal[] traversals = getResourceTraversals(getStructuredSelection(), monitor); - DiffChangeSet set = (DiffChangeSet)getChangeSet(getStructuredSelection()); + } + + private IDiff[] getSelectedDiffs(IProgressMonitor monitor) throws CoreException { + ResourceTraversal[] traversals = getResourceTraversals(getStructuredSelection(), monitor); + DiffChangeSet set = (DiffChangeSet)getChangeSet(getStructuredSelection()); return set.getDiffTree().getDiffs(traversals); } /* - * Build the trees that will be compared - */ - private boolean buildTrees(CompareTreeBuilder builder, IDiff[] diffs) { - for (int i = 0; i < diffs.length; i++) { + * Build the trees that will be compared + */ + private boolean buildTrees(CompareTreeBuilder builder, IDiff[] diffs) { + for (int i = 0; i < diffs.length; i++) { IDiff diff = diffs[i]; if (isFileChange(diff)) { - IFileRevision remoteRevision = Utils.getRemote(diff); - IResourceVariant remote = SyncInfoToDiffConverter.asResourceVariant(remoteRevision); - if (remote == null) { - IFileRevision predecessorRevision = Utils.getBase(diff); - IResourceVariant predecessor = SyncInfoToDiffConverter.asResourceVariant(predecessorRevision); - if (predecessor instanceof ICVSRemoteFile) { - builder.addToTrees((ICVSRemoteFile)predecessor, null); - } - } else if (remote instanceof ICVSRemoteFile) { - try { - ICVSRemoteFile predecessor = getImmediatePredecessor(remote); - builder.addToTrees(predecessor, (ICVSRemoteFile)remote); - } catch (TeamException e) { - Utils.handle(e); - return false; - } - } + IFileRevision remoteRevision = Utils.getRemote(diff); + IResourceVariant remote = SyncInfoToDiffConverter.asResourceVariant(remoteRevision); + if (remote == null) { + IFileRevision predecessorRevision = Utils.getBase(diff); + IResourceVariant predecessor = SyncInfoToDiffConverter.asResourceVariant(predecessorRevision); + if (predecessor instanceof ICVSRemoteFile) { + builder.addToTrees((ICVSRemoteFile)predecessor, null); + } + } else if (remote instanceof ICVSRemoteFile) { + try { + ICVSRemoteFile predecessor = getImmediatePredecessor(remote); + builder.addToTrees(predecessor, (ICVSRemoteFile)remote); + } catch (TeamException e) { + Utils.handle(e); + return false; + } + } } - } - return true; - } - - private boolean isFileChange(IDiff diff) { + } + return true; + } + + private boolean isFileChange(IDiff diff) { IResource resource = ResourceDiffTree.getResourceFor(diff); if (resource.getType() == IResource.FILE) { if (diff instanceof IThreeWayDiff) { @@ -166,9 +166,9 @@ class OpenChangeSetAction extends ResourceModelParticipantAction { } private ICVSRepositoryLocation getLocation(IDiff diff) { - IResource resource = ResourceDiffTree.getResourceFor(diff); - RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject()); - if (provider instanceof CVSTeamProvider) { + IResource resource = ResourceDiffTree.getResourceFor(diff); + RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject()); + if (provider instanceof CVSTeamProvider) { CVSTeamProvider ctp = (CVSTeamProvider) provider; try { return ctp.getCVSWorkspaceRoot().getRemoteLocation(); @@ -176,46 +176,46 @@ class OpenChangeSetAction extends ResourceModelParticipantAction { CVSUIPlugin.log(e); } } - return null; - } - - private String getCompareTitle() { - ChangeSet set = getChangeSet(getStructuredSelection()); - if (set instanceof CVSCheckedInChangeSet) { - CVSCheckedInChangeSet cics = (CVSCheckedInChangeSet)set; - String date = DateFormat.getDateTimeInstance().format(cics.getDate()); - return NLS.bind(CVSUIMessages.OpenChangeSetAction_0, new String[] {cics.getAuthor(), date}); - } - return CVSUIMessages.OpenChangeSetAction_1; - } - - private String getCompareToolTip() { - ChangeSet set = getChangeSet(getStructuredSelection()); - if (set != null) - return set.getName(); - return null; - } - - private ICVSRemoteFile getImmediatePredecessor(IResourceVariant remote) throws TeamException { - CheckedInChangeSetCollector changeSetCollector = getChangeSetCollector(); - if (changeSetCollector != null) { - return changeSetCollector.getImmediatePredecessor((ICVSRemoteFile)remote); - } - return null; - } + return null; + } + + private String getCompareTitle() { + ChangeSet set = getChangeSet(getStructuredSelection()); + if (set instanceof CVSCheckedInChangeSet) { + CVSCheckedInChangeSet cics = (CVSCheckedInChangeSet)set; + String date = DateFormat.getDateTimeInstance().format(cics.getDate()); + return NLS.bind(CVSUIMessages.OpenChangeSetAction_0, new String[] {cics.getAuthor(), date}); + } + return CVSUIMessages.OpenChangeSetAction_1; + } + + private String getCompareToolTip() { + ChangeSet set = getChangeSet(getStructuredSelection()); + if (set != null) + return set.getName(); + return null; + } + + private ICVSRemoteFile getImmediatePredecessor(IResourceVariant remote) throws TeamException { + CheckedInChangeSetCollector changeSetCollector = getChangeSetCollector(); + if (changeSetCollector != null) { + return changeSetCollector.getImmediatePredecessor((ICVSRemoteFile)remote); + } + return null; + } - private CheckedInChangeSetCollector getChangeSetCollector() { - return (CheckedInChangeSetCollector)getConfiguration().getProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR); - } - - @Override + private CheckedInChangeSetCollector getChangeSetCollector() { + return (CheckedInChangeSetCollector)getConfiguration().getProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR); + } + + @Override public void run() { - try { + try { PlatformUI.getWorkbench().getProgressService().run(true, true, monitor -> openEditor(monitor)); } catch (InvocationTargetException e) { Utils.handle(e); } catch (InterruptedException e) { // Ignore } - } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceChangeSetCapability.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceChangeSetCapability.java index b85167427..19ff7923d 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceChangeSetCapability.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceChangeSetCapability.java @@ -37,44 +37,44 @@ public class WorkspaceChangeSetCapability extends ModelParticipantChangeSetCapab @Override public boolean enableActiveChangeSetsFor(ISynchronizePageConfiguration configuration) { - return supportsActiveChangeSets() && - configuration.getMode() != ISynchronizePageConfiguration.INCOMING_MODE; + return supportsActiveChangeSets() && + configuration.getMode() != ISynchronizePageConfiguration.INCOMING_MODE; } - @Override + @Override public ActiveChangeSet createChangeSet(ISynchronizePageConfiguration configuration, IDiff[] infos) { - ActiveChangeSet set = getActiveChangeSetManager().createSet(CVSUIMessages.WorkspaceChangeSetCapability_1, new IDiff[0]); + ActiveChangeSet set = getActiveChangeSetManager().createSet(CVSUIMessages.WorkspaceChangeSetCapability_1, new IDiff[0]); CommitSetDialog dialog = new CommitSetDialog(configuration.getSite().getShell(), set, getResources(infos), CommitSetDialog.NEW); dialog.open(); if (dialog.getReturnCode() != Window.OK) return null; set.add(infos); return set; - } + } - private IResource[] getResources(IDiff[] diffs) { + private IResource[] getResources(IDiff[] diffs) { Set<IResource> result = new HashSet<>(); - for (int i = 0; i < diffs.length; i++) { + for (int i = 0; i < diffs.length; i++) { IDiff diff = diffs[i]; IResource resource = ResourceDiffTree.getResourceFor(diff); if (resource != null) result.add(resource); } - return result.toArray(new IResource[result.size()]); - } - - @Override + return result.toArray(new IResource[result.size()]); + } + + @Override public void editChangeSet(ISynchronizePageConfiguration configuration, ActiveChangeSet set) { - CommitSetDialog dialog = new CommitSetDialog(configuration.getSite().getShell(), set, set.getResources(), CommitSetDialog.EDIT); + CommitSetDialog dialog = new CommitSetDialog(configuration.getSite().getShell(), set, set.getResources(), CommitSetDialog.EDIT); dialog.open(); if (dialog.getReturnCode() != Window.OK) return; // Nothing to do here as the set was updated by the dialog - } + } - @Override + @Override public ActiveChangeSetManager getActiveChangeSetManager() { - return CVSUIPlugin.getPlugin().getChangeSetManager(); - } - + return CVSUIPlugin.getPlugin().getChangeSetManager(); + } + @Override public CheckedInChangeSetCollector createCheckedInChangeSetCollector(ISynchronizePageConfiguration configuration) { return new CheckedInChangeSetCollector(configuration, CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceModelParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceModelParticipant.java index b1fd688e4..315f0249b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceModelParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceModelParticipant.java @@ -238,30 +238,30 @@ public class WorkspaceModelParticipant extends return WorkspaceSubscriberContext.createWorkspaceScopeManager(mappings, true, isConsultChangeSets); } - @Override + @Override public ChangeSetCapability getChangeSetCapability() { - if (capability == null) { - capability = new WorkspaceChangeSetCapability(); - } - return capability; + if (capability == null) { + capability = new WorkspaceChangeSetCapability(); + } + return capability; } - - @Override + + @Override public void saveState(IMemento memento) { - super.saveState(memento); - memento.putString(CTX_CONSULT_CHANGE_SETS, Boolean.toString(isConsultChangeSets)); - } - - @Override + super.saveState(memento); + memento.putString(CTX_CONSULT_CHANGE_SETS, Boolean.toString(isConsultChangeSets)); + } + + @Override public void init(String secondaryId, IMemento memento) throws PartInitException { - try { - String consult = memento.getString(CTX_CONSULT_CHANGE_SETS); - if (consult != null) - isConsultChangeSets = Boolean.valueOf(consult).booleanValue(); - } finally { - super.init(secondaryId, memento); - } - } + try { + String consult = memento.getString(CTX_CONSULT_CHANGE_SETS); + if (consult != null) + isConsultChangeSets = Boolean.valueOf(consult).booleanValue(); + } finally { + super.init(secondaryId, memento); + } + } private boolean isConsultChangeSets(ISynchronizationScopeManager manager) { if (manager instanceof ChangeSetSubscriberScopeManager) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceSubscriberContext.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceSubscriberContext.java index 6a076f904..257dc6d4e 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceSubscriberContext.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/mappings/WorkspaceSubscriberContext.java @@ -412,10 +412,10 @@ public class WorkspaceSubscriberContext extends CVSSubscriberMergeContext implem public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { return traversals; } - @Override + @Override public boolean contains(ResourceMapping mapping) { - return false; - } + return false; + } @Override public String getModelProviderId() { return ModelProvider.RESOURCE_MODEL_PROVIDER_ID; @@ -494,12 +494,12 @@ public class WorkspaceSubscriberContext extends CVSSubscriberMergeContext implem IFile file = (IFile) resource; ICVSFile mFile = CVSWorkspaceRoot.getCVSFileFor(file); try { - // The file may have been set as read-only by a previous checkout/update - if (mFile.isReadOnly()) mFile.setReadOnly(false); - } catch (CVSException e) { - // Just log and keep going - CVSProviderPlugin.log(e); - } + // The file may have been set as read-only by a previous checkout/update + if (mFile.isReadOnly()) mFile.setReadOnly(false); + } catch (CVSException e) { + // Just log and keep going + CVSProviderPlugin.log(e); + } } super.performReplace(diff, monitor); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSAdapterFactory.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSAdapterFactory.java index 50176435e..15f3d277f 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSAdapterFactory.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSAdapterFactory.java @@ -47,11 +47,11 @@ public class CVSAdapterFactory implements IAdapterFactory { } if(IDeferredWorkbenchAdapter.class == adapterType) { - Object o = getWorkbenchAdapter(adaptableObject); - if(o != null && o instanceof IDeferredWorkbenchAdapter) { - return adapterType.cast(o); - } - return null; + Object o = getWorkbenchAdapter(adaptableObject); + if(o != null && o instanceof IDeferredWorkbenchAdapter) { + return adapterType.cast(o); + } + return null; } if (IPropertySource.class == adapterType) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSModelElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSModelElement.java index 7e2d57212..6936d1296 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSModelElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSModelElement.java @@ -83,26 +83,26 @@ public abstract class CVSModelElement implements IWorkbenchAdapter, IAdaptable { * @param description the description to be displayed * @param e the exception that occurred */ - protected void handle(final String title, final String description, final Throwable e) { - CVSUIPlugin.openError(null, title, description, e, CVSUIPlugin.LOG_NONTEAM_EXCEPTIONS | CVSUIPlugin.PERFORM_SYNC_EXEC); - } - - /** - * Helper method error handler that displays a generic dialog title and message when displaying an error to the user. - * @param t the exception that occurred. - */ - protected void handle(Throwable t) { - handle(CVSUIMessages.CVSModelElement_0, CVSUIMessages.CVSModelElement_1, t); // - } - - /** - * Handle an exception that occurred while fetching the children for a deferred workbench adapter. - * @param collector the collector for the adapter - * @param e the exception that occurred - */ - protected void handle(IElementCollector collector, Throwable t) { - // TODO: For now, just display a dialog (see bug 65008 and 65741) - handle(t); - } + protected void handle(final String title, final String description, final Throwable e) { + CVSUIPlugin.openError(null, title, description, e, CVSUIPlugin.LOG_NONTEAM_EXCEPTIONS | CVSUIPlugin.PERFORM_SYNC_EXEC); + } + + /** + * Helper method error handler that displays a generic dialog title and message when displaying an error to the user. + * @param t the exception that occurred. + */ + protected void handle(Throwable t) { + handle(CVSUIMessages.CVSModelElement_0, CVSUIMessages.CVSModelElement_1, t); // + } + + /** + * Handle an exception that occurred while fetching the children for a deferred workbench adapter. + * @param collector the collector for the adapter + * @param e the exception that occurred + */ + protected void handle(IElementCollector collector, Throwable t) { + // TODO: For now, just display a dialog (see bug 65008 and 65741) + handle(t); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSTagElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSTagElement.java index d678a5f06..bfbcca329 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSTagElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/CVSTagElement.java @@ -169,12 +169,12 @@ public class CVSTagElement extends CVSModelElement implements IDeferredWorkbench try { collector.add(fetchChildren(o, monitor), monitor); } catch (TeamException e) { - handle(collector, e); + handle(collector, e); } } } - public ISchedulingRule getRule(Object element) { + public ISchedulingRule getRule(Object element) { return new RepositoryLocationSchedulingRule(root); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteContentProvider.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteContentProvider.java index 93888a648..7c596c2d1 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteContentProvider.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteContentProvider.java @@ -102,7 +102,7 @@ public class RemoteContentProvider extends WorkbenchContentProvider { //check to see if we already have the children cached in the tree map Object tree = cachedTrees.get(element); if (tree != null) { - return ((RemoteFolderTree) tree).getChildren(); + return ((RemoteFolderTree) tree).getChildren(); } if (manager != null) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFileElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFileElement.java index b388872df..fc9b533ad 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFileElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFileElement.java @@ -45,7 +45,7 @@ public class RemoteFileElement extends RemoteResourceElement { try { return NLS.bind(CVSUIMessages.nameAndRevision, new String[] { file.getName(), file.getRevision() }); } catch (TeamException e) { - handle(null, null, e); + handle(null, null, e); return null; } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFolderElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFolderElement.java index c2c88d737..838df54dd 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFolderElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteFolderElement.java @@ -30,36 +30,36 @@ import org.eclipse.ui.progress.IElementCollector; public class RemoteFolderElement extends RemoteResourceElement implements IDeferredWorkbenchAdapter { - /** - * Overridden to append the version name to remote folders which - * have version tags and are top-level folders. - */ - public String getLabel(Object o) { - if (!(o instanceof ICVSRemoteFolder)) - return null; - ICVSRemoteFolder folder = (ICVSRemoteFolder) o; - CVSTag tag = folder.getTag(); - if (tag != null && tag.getType() != CVSTag.HEAD) { - if (folder.getRemoteParent() == null) { - return NLS.bind(CVSUIMessages.RemoteFolderElement_nameAndTag, new String[] { folder.getName(), tag.getName() }); - } - } - return folder.getName(); - } + /** + * Overridden to append the version name to remote folders which + * have version tags and are top-level folders. + */ + public String getLabel(Object o) { + if (!(o instanceof ICVSRemoteFolder)) + return null; + ICVSRemoteFolder folder = (ICVSRemoteFolder) o; + CVSTag tag = folder.getTag(); + if (tag != null && tag.getType() != CVSTag.HEAD) { + if (folder.getRemoteParent() == null) { + return NLS.bind(CVSUIMessages.RemoteFolderElement_nameAndTag, new String[] { folder.getName(), tag.getName() }); + } + } + return folder.getName(); + } - public ImageDescriptor getImageDescriptor(Object object) { - if (!(object instanceof ICVSRemoteFolder)) - return null; - ICVSRemoteFolder folder = (ICVSRemoteFolder) object; - if (folder.isDefinedModule()) { - return CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_MODULE); - } - return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); - } + public ImageDescriptor getImageDescriptor(Object object) { + if (!(object instanceof ICVSRemoteFolder)) + return null; + ICVSRemoteFolder folder = (ICVSRemoteFolder) object; + if (folder.isDefinedModule()) { + return CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_MODULE); + } + return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); + } - public Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { - if (!(o instanceof ICVSRemoteFolder)) - return new Object[0]; + public Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { + if (!(o instanceof ICVSRemoteFolder)) + return new Object[0]; try { monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( @@ -80,8 +80,8 @@ public class RemoteFolderElement extends RemoteResourceElement implements IDefer } } - public void fetchDeferredChildren(Object o, IElementCollector collector, IProgressMonitor monitor) { - // If it's not a folder, return an empty array + public void fetchDeferredChildren(Object o, IElementCollector collector, IProgressMonitor monitor) { + // If it's not a folder, return an empty array if (!(o instanceof ICVSRemoteFolder)) { collector.add(new Object[0], monitor); } @@ -104,20 +104,20 @@ public class RemoteFolderElement extends RemoteResourceElement implements IDefer folder, collector); operation.run(Policy.subMonitorFor(monitor, 50)); } catch (InvocationTargetException e) { - handle(collector, e); + handle(collector, e); } catch (InterruptedException e) { // Cancelled by the user; } catch (CVSException e) { handle(collector, e); } finally { - monitor.done(); - } - } + monitor.done(); + } + } - public ISchedulingRule getRule(Object element) { - ICVSRepositoryLocation location = getRepositoryLocation(element); - return new RepositoryLocationSchedulingRule(location); - } + public ISchedulingRule getRule(Object element) { + ICVSRepositoryLocation location = getRepositoryLocation(element); + return new RepositoryLocationSchedulingRule(location); + } private ICVSRepositoryLocation getRepositoryLocation(Object o) { if (!(o instanceof ICVSRemoteFolder)) @@ -126,6 +126,6 @@ public class RemoteFolderElement extends RemoteResourceElement implements IDefer } public boolean isContainer() { - return true; - } + return true; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteModule.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteModule.java index 9509e8991..a52e48c52 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteModule.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/RemoteModule.java @@ -32,128 +32,128 @@ import org.eclipse.ui.progress.IElementCollector; * VersionsCategory. */ public class RemoteModule extends CVSModelElement implements IAdaptable, - IDeferredWorkbenchAdapter { - ICVSRemoteFolder folder; + IDeferredWorkbenchAdapter { + ICVSRemoteFolder folder; - VersionCategory parent; + VersionCategory parent; - /** - * RemoteProject constructor. - */ - public RemoteModule(ICVSRemoteFolder folder, VersionCategory parent) { - this.folder = folder; - this.parent = parent; - } + /** + * RemoteProject constructor. + */ + public RemoteModule(ICVSRemoteFolder folder, VersionCategory parent) { + this.folder = folder; + this.parent = parent; + } - /** - * Returns an object which is an instance of the given class associated with - * this object. Returns <code>null</code> if no such object can be found. - */ - @Override + /** + * Returns an object which is an instance of the given class associated with + * this object. Returns <code>null</code> if no such object can be found. + */ + @Override public <T> T getAdapter(Class<T> adapter) { - if (adapter == IWorkbenchAdapter.class) - return adapter.cast(this); - if (adapter == IDeferredWorkbenchAdapter.class) - return adapter.cast(this); - return null; - } + if (adapter == IWorkbenchAdapter.class) + return adapter.cast(this); + if (adapter == IDeferredWorkbenchAdapter.class) + return adapter.cast(this); + return null; + } - /** - * Returns an image to be used for displaying an object in the desktop. - * - * @param object The object to get an image for. - * @param owner The viewer that the image will be used in. The image will be - * disposed when this viewer is closed. If the owner is null, a - * new image is returned, and the caller is responsible for - * disposing it. - */ - @Override + /** + * Returns an image to be used for displaying an object in the desktop. + * + * @param object The object to get an image for. + * @param owner The viewer that the image will be used in. The image will be + * disposed when this viewer is closed. If the owner is null, a + * new image is returned, and the caller is responsible for + * disposing it. + */ + @Override public ImageDescriptor getImageDescriptor(Object object) { - return CVSUIPlugin.getPlugin().getImageDescriptor( - ICVSUIConstants.IMG_PROJECT_VERSION); - } + return CVSUIPlugin.getPlugin().getImageDescriptor( + ICVSUIConstants.IMG_PROJECT_VERSION); + } - /** - * Returns the name of this element. This will typically be used to assign a - * label to this object when displayed in the UI. - */ - @Override + /** + * Returns the name of this element. This will typically be used to assign a + * label to this object when displayed in the UI. + */ + @Override public String getLabel(Object o) { - return folder.getName(); - } + return folder.getName(); + } - /** - * Returns the logical parent of the given object in its tree. - */ - @Override + /** + * Returns the logical parent of the given object in its tree. + */ + @Override public Object getParent(Object o) { - return parent; - } + return parent; + } - /** - * Return the repository the given element belongs to. - */ - public ICVSRepositoryLocation getRepository(Object o) { - return folder.getRepository(); - } + /** + * Return the repository the given element belongs to. + */ + public ICVSRepositoryLocation getRepository(Object o) { + return folder.getRepository(); + } /* * For debugging purposes only. */ - @Override + @Override public String toString() { - return "RemoteModule(" + folder.getName() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } + return "RemoteModule(" + folder.getName() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } - public ICVSRemoteResource getCVSResource() { - return folder; - } + public ICVSRemoteResource getCVSResource() { + return folder; + } - /** - * Returns the children of this object. When this object is displayed in a - * tree, the returned objects will be this element's children. Returns an - * empty enumeration if this object has no children. The children of the - * RemoteModule are the versions for that module. - * - * @see org.eclipse.team.internal.ccvs.ui.model.CVSModelElement#internalGetChildren(java.lang.Object, - * org.eclipse.core.runtime.IProgressMonitor) - */ - @Override + /** + * Returns the children of this object. When this object is displayed in a + * tree, the returned objects will be this element's children. Returns an + * empty enumeration if this object has no children. The children of the + * RemoteModule are the versions for that module. + * + * @see org.eclipse.team.internal.ccvs.ui.model.CVSModelElement#internalGetChildren(java.lang.Object, + * org.eclipse.core.runtime.IProgressMonitor) + */ + @Override public Object[] fetchChildren(Object o, IProgressMonitor monitor) - throws TeamException { - RepositoryManager manager = CVSUIPlugin.getPlugin() - .getRepositoryManager(); - try { - manager.refreshDefinedTags(folder, false /* recurse */, false /* notify */, monitor); - } catch (TeamException e) { - // continue - } - CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager() - .getKnownTags(folder, CVSTag.VERSION); - Object[] versions = new Object[tags.length]; - for (int i = 0; i < versions.length; i++) { - versions[i] = folder.forTag(tags[i]); - } - return versions; - } + throws TeamException { + RepositoryManager manager = CVSUIPlugin.getPlugin() + .getRepositoryManager(); + try { + manager.refreshDefinedTags(folder, false /* recurse */, false /* notify */, monitor); + } catch (TeamException e) { + // continue + } + CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager() + .getKnownTags(folder, CVSTag.VERSION); + Object[] versions = new Object[tags.length]; + for (int i = 0; i < versions.length; i++) { + versions[i] = folder.forTag(tags[i]); + } + return versions; + } - @Override + @Override public void fetchDeferredChildren(Object o, IElementCollector collector, - IProgressMonitor monitor) { - try { - collector.add(fetchChildren(o, monitor), monitor); - } catch (TeamException e) { - handle(collector, e); - } - } + IProgressMonitor monitor) { + try { + collector.add(fetchChildren(o, monitor), monitor); + } catch (TeamException e) { + handle(collector, e); + } + } - @Override + @Override public boolean isContainer() { - return true; - } + return true; + } - @Override + @Override public ISchedulingRule getRule(Object element) { - return new RepositoryLocationSchedulingRule(folder.getRepository()); - } + return new RepositoryLocationSchedulingRule(folder.getRepository()); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/VersionCategory.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/VersionCategory.java index 7e57022af..2aa65df5f 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/VersionCategory.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/model/VersionCategory.java @@ -25,132 +25,132 @@ import org.eclipse.ui.progress.IDeferredWorkbenchAdapter; import org.eclipse.ui.progress.IElementCollector; public class VersionCategory extends CVSModelElement implements IAdaptable, - IDeferredWorkbenchAdapter { - private ICVSRepositoryLocation repository; + IDeferredWorkbenchAdapter { + private ICVSRepositoryLocation repository; - /** - * ProjectVersionsCategory constructor. - */ - public VersionCategory(ICVSRepositoryLocation repo) { - super(); - this.repository = repo; - } + /** + * ProjectVersionsCategory constructor. + */ + public VersionCategory(ICVSRepositoryLocation repo) { + super(); + this.repository = repo; + } - /** - * Returns an object which is an instance of the given class associated with - * this object. Returns <code>null</code> if no such object can be found. - */ - public <T> T getAdapter(Class<T> adapter) { - if (adapter == IWorkbenchAdapter.class) - return adapter.cast(this); - if (adapter == IDeferredWorkbenchAdapter.class) - return adapter.cast(this); - return null; - } + /** + * Returns an object which is an instance of the given class associated with + * this object. Returns <code>null</code> if no such object can be found. + */ + public <T> T getAdapter(Class<T> adapter) { + if (adapter == IWorkbenchAdapter.class) + return adapter.cast(this); + if (adapter == IDeferredWorkbenchAdapter.class) + return adapter.cast(this); + return null; + } - /** - * Returns the children of this object. When this object is displayed in a - * tree, the returned objects will be this element's children. Returns an - * empty enumeration if this object has no children. - */ - public Object[] fetchChildren(Object o, IProgressMonitor monitor) - throws TeamException { - if (CVSUIPlugin.getPlugin().getRepositoryManager() - .isDisplayingProjectVersions(repository)) { - return getProjectVersionChildren(o, monitor); - } else { - return getVersionTagChildren(o, monitor); - } - } + /** + * Returns the children of this object. When this object is displayed in a + * tree, the returned objects will be this element's children. Returns an + * empty enumeration if this object has no children. + */ + public Object[] fetchChildren(Object o, IProgressMonitor monitor) + throws TeamException { + if (CVSUIPlugin.getPlugin().getRepositoryManager() + .isDisplayingProjectVersions(repository)) { + return getProjectVersionChildren(o, monitor); + } else { + return getVersionTagChildren(o, monitor); + } + } - /* - * Return the children as a list of versions whose children are projects - */ - private Object[] getVersionTagChildren(Object o, IProgressMonitor monitor) - throws CVSException { - CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager() - .getKnownTags(repository, getWorkingSet(), CVSTag.VERSION, monitor); - CVSTagElement[] versionElements = new CVSTagElement[tags.length]; - for (int i = 0; i < tags.length; i++) { - versionElements[i] = new CVSTagElement(tags[i], repository); - } - return versionElements; - } + /* + * Return the children as a list of versions whose children are projects + */ + private Object[] getVersionTagChildren(Object o, IProgressMonitor monitor) + throws CVSException { + CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager() + .getKnownTags(repository, getWorkingSet(), CVSTag.VERSION, monitor); + CVSTagElement[] versionElements = new CVSTagElement[tags.length]; + for (int i = 0; i < tags.length; i++) { + versionElements[i] = new CVSTagElement(tags[i], repository); + } + return versionElements; + } - /* - * Return the children as a list of projects whose children ar project - * versions - */ - private Object[] getProjectVersionChildren(Object o, - IProgressMonitor monitor) throws TeamException { + /* + * Return the children as a list of projects whose children ar project + * versions + */ + private Object[] getProjectVersionChildren(Object o, + IProgressMonitor monitor) throws TeamException { - ICVSRemoteResource[] resources = CVSUIPlugin.getPlugin() - .getRepositoryManager().getFoldersForTag(repository, - CVSTag.DEFAULT, monitor); - if (getWorkingSet() != null) - resources = CVSUIPlugin.getPlugin().getRepositoryManager() - .filterResources(getWorkingSet(), resources); - Object[] modules = new Object[resources.length]; - for (int i = 0; i < resources.length; i++) { - modules[i] = new RemoteModule((ICVSRemoteFolder) resources[i], - VersionCategory.this); - } - return modules; - } + ICVSRemoteResource[] resources = CVSUIPlugin.getPlugin() + .getRepositoryManager().getFoldersForTag(repository, + CVSTag.DEFAULT, monitor); + if (getWorkingSet() != null) + resources = CVSUIPlugin.getPlugin().getRepositoryManager() + .filterResources(getWorkingSet(), resources); + Object[] modules = new Object[resources.length]; + for (int i = 0; i < resources.length; i++) { + modules[i] = new RemoteModule((ICVSRemoteFolder) resources[i], + VersionCategory.this); + } + return modules; + } - /** - * Returns an image descriptor to be used for displaying an object in the - * workbench. Returns null if there is no appropriate image. - * - * @param object The object to get an image descriptor for. - */ - public ImageDescriptor getImageDescriptor(Object object) { - return CVSUIPlugin.getPlugin().getImageDescriptor( - ICVSUIConstants.IMG_VERSIONS_CATEGORY); - } + /** + * Returns an image descriptor to be used for displaying an object in the + * workbench. Returns null if there is no appropriate image. + * + * @param object The object to get an image descriptor for. + */ + public ImageDescriptor getImageDescriptor(Object object) { + return CVSUIPlugin.getPlugin().getImageDescriptor( + ICVSUIConstants.IMG_VERSIONS_CATEGORY); + } - /** - * Returns the name of this element. This will typically be used to assign a - * label to this object when displayed in the UI. Returns an empty string if - * there is no appropriate name for this object. - * - * @param object The object to get a label for. - */ - public String getLabel(Object o) { - return CVSUIMessages.VersionCategory_Versions_1; - } + /** + * Returns the name of this element. This will typically be used to assign a + * label to this object when displayed in the UI. Returns an empty string if + * there is no appropriate name for this object. + * + * @param object The object to get a label for. + */ + public String getLabel(Object o) { + return CVSUIMessages.VersionCategory_Versions_1; + } - /** - * Returns the logical parent of the given object in its tree. Returns null - * if there is no parent, or if this object doesn't belong to a tree. - * - * @param object The object to get the parent for. - */ - public Object getParent(Object o) { - return repository; - } + /** + * Returns the logical parent of the given object in its tree. Returns null + * if there is no parent, or if this object doesn't belong to a tree. + * + * @param object The object to get the parent for. + */ + public Object getParent(Object o) { + return repository; + } - /** - * Return the repository the given element belongs to. - */ - public ICVSRepositoryLocation getRepository(Object o) { - return repository; - } + /** + * Return the repository the given element belongs to. + */ + public ICVSRepositoryLocation getRepository(Object o) { + return repository; + } - public void fetchDeferredChildren(Object o, IElementCollector collector, - IProgressMonitor monitor) { - try { - collector.add(fetchChildren(o, monitor), monitor); - } catch (TeamException e) { - handle(collector, e); - } - } + public void fetchDeferredChildren(Object o, IElementCollector collector, + IProgressMonitor monitor) { + try { + collector.add(fetchChildren(o, monitor), monitor); + } catch (TeamException e) { + handle(collector, e); + } + } - public boolean isContainer() { - return true; - } + public boolean isContainer() { + return true; + } - public ISchedulingRule getRule(Object element) { - return new RepositoryLocationSchedulingRule(repository); - } + public ISchedulingRule getRule(Object element) { + return new RepositoryLocationSchedulingRule(repository); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/AddOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/AddOperation.java index 1893d642e..7919b5806 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/AddOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/AddOperation.java @@ -46,18 +46,18 @@ public class AddOperation extends RepositoryProviderOperation { fModesForFiles= Collections.EMPTY_MAP; } - public void addModesForExtensions(Map modes) { + public void addModesForExtensions(Map modes) { fModesForExtensions= modes; - } - - public void addModesForNames(Map modes) { - fModesForFiles= modes; + } + + public void addModesForNames(Map modes) { + fModesForFiles= modes; } @Override protected void execute(CVSTeamProvider provider, IResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException { - if (resources.length == 0) - return; + if (resources.length == 0) + return; add(provider, resources, recurse ? IResource.DEPTH_INFINITE : IResource.DEPTH_ONE, monitor); } @@ -129,7 +129,7 @@ public class AddOperation extends RepositoryProviderOperation { // added explicitly (is equal currentResource) or is not ignored if (! isManaged(mResource) && (currentResource.equals(resource) || ! mResource.isIgnored())) { if (resource.getType() == IResource.FILE) { - KSubstOption ksubst= getKSubstOption((IFile)resource); + KSubstOption ksubst= getKSubstOption((IFile)resource); Set set = files.get(ksubst); if (set == null) { set = new HashSet(); @@ -148,7 +148,7 @@ public class AddOperation extends RepositoryProviderOperation { } } - }, depth, false); + }, depth, false); if (exception[0] != null) { throw exception[0]; } @@ -208,13 +208,13 @@ public class AddOperation extends RepositoryProviderOperation { } /* - * Return true if the resource is a project that is already a CVS folder - */ - protected boolean isManagedProject(IResource resource, ICVSResource resource2) throws CVSException { - return resource.getType() == IResource.PROJECT && ((ICVSFolder)resource2).isCVSFolder(); - } + * Return true if the resource is a project that is already a CVS folder + */ + protected boolean isManagedProject(IResource resource, ICVSResource resource2) throws CVSException { + return resource.getType() == IResource.PROJECT && ((ICVSFolder)resource2).isCVSFolder(); + } - /* + /* * Consider a folder managed only if it's also a CVS folder */ protected boolean isManaged(ICVSResource cvsResource) throws CVSException { @@ -226,19 +226,19 @@ public class AddOperation extends RepositoryProviderOperation { return CVSUIMessages.AddAction_addFailed; } - protected KSubstOption getKSubstOption(IFile file) { - final String extension= file.getFileExtension(); - final Integer mode; - if (extension == null) { - mode= (Integer)fModesForFiles.get(file.getName()); - } else { - mode= (Integer)fModesForExtensions.get(extension); - } - if (mode != null) { - return mode.intValue() == Team.BINARY ? Command.KSUBST_BINARY : KSubstOption.getDefaultTextMode(); - } else { - return KSubstOption.fromFile(file); - } - } + protected KSubstOption getKSubstOption(IFile file) { + final String extension= file.getFileExtension(); + final Integer mode; + if (extension == null) { + mode= (Integer)fModesForFiles.get(file.getName()); + } else { + mode= (Integer)fModesForExtensions.get(extension); + } + if (mode != null) { + return mode.intValue() == Team.BINARY ? Command.KSUBST_BINARY : KSubstOption.getDefaultTextMode(); + } else { + return KSubstOption.fromFile(file); + } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/BranchOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/BranchOperation.java index 071f36568..4e350b773 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/BranchOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/BranchOperation.java @@ -71,8 +71,8 @@ public class BranchOperation extends RepositoryProviderOperation { } catch (InterruptedException e1) { throw new OperationCanceledException(); } - - IResource[] resources = getTraversalRoots(); + + IResource[] resources = getTraversalRoots(); boolean allSticky = areAllResourcesSticky(resources); String initialVersionName = calculateInitialVersionName(resources,allSticky); final BranchPromptDialog dialog = new BranchPromptDialog(getShell(), @@ -134,7 +134,7 @@ public class BranchOperation extends RepositoryProviderOperation { try { // Build the arguments list ICVSResource[] arguments = getCVSArguments(resources); - LocalOption[] localOptions = getLocalOptions(recurse); + LocalOption[] localOptions = getLocalOptions(recurse); // Tag the remote resources IStatus status = null; @@ -176,7 +176,7 @@ public class BranchOperation extends RepositoryProviderOperation { Session session = new Session(getRemoteLocation(provider), getLocalRoot(provider), true /* output to console */); session.open(Policy.subMonitorFor(monitor, 5), true /* open for modification */); try { - status = Command.CUSTOM_TAG.execute( + status = Command.CUSTOM_TAG.execute( session, Command.NO_GLOBAL_OPTIONS, localOptions, diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CVSOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CVSOperation.java index 705564909..5030bfad1 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CVSOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CVSOperation.java @@ -176,7 +176,7 @@ public abstract class CVSOperation extends TeamOperation implements IShellProvid */ protected final void handleErrors(IStatus[] errors) throws CVSException { // We are only concerned with reportable errors. - // Others will appear in the console + // Others will appear in the console List<IStatus> reportableErrors = new ArrayList<>(); for (int i = 0; i < errors.length; i++) { IStatus status = errors[i]; @@ -194,7 +194,7 @@ public abstract class CVSOperation extends TeamOperation implements IShellProvid } } if (!reportableErrors.isEmpty()) - asException(reportableErrors.toArray(new IStatus[reportableErrors.size()])); + asException(reportableErrors.toArray(new IStatus[reportableErrors.size()])); } /** @@ -203,11 +203,11 @@ public abstract class CVSOperation extends TeamOperation implements IShellProvid * @param status an error status * @return whether the status is reportable or should be ignored */ - protected boolean isReportableError(IStatus status) { - return status.getCode() == CVSStatus.SERVER_ERROR || CVSStatus.isInternalError(status) || status.getCode() == TeamException.UNABLE; - } + protected boolean isReportableError(IStatus status) { + return status.getCode() == CVSStatus.SERVER_ERROR || CVSStatus.isInternalError(status) || status.getCode() == TeamException.UNABLE; + } - protected String getErrorMessage(IStatus[] failures, int totalOperations) { + protected String getErrorMessage(IStatus[] failures, int totalOperations) { return NLS.bind(CVSUIMessages.CVSOperation_0, new String[] { String.valueOf(failures.length), String.valueOf(totalOperations) }); } @@ -298,29 +298,29 @@ public abstract class CVSOperation extends TeamOperation implements IShellProvid return true; } - @Override + @Override protected boolean isSameFamilyAs(TeamOperation operation) { - // Trat all CVS operations as a single family - return operation instanceof CVSOperation; - } - - /* - * Action to show the console that can be used by subclasses - * that wish to link the progress service to the console - */ - protected IAction getShowConsoleAction() { - // Show the console as the goto action - return new Action(CVSUIMessages.CVSOperation_1) { - @Override + // Trat all CVS operations as a single family + return operation instanceof CVSOperation; + } + + /* + * Action to show the console that can be used by subclasses + * that wish to link the progress service to the console + */ + protected IAction getShowConsoleAction() { + // Show the console as the goto action + return new Action(CVSUIMessages.CVSOperation_1) { + @Override public void run() { - CVSOutputConsole console = CVSUIPlugin.getPlugin().getConsole(); - if (console != null) - console.show(true); - } - @Override + CVSOutputConsole console = CVSUIPlugin.getPlugin().getConsole(); + if (console != null) + console.show(true); + } + @Override public String getToolTipText() { - return CVSUIMessages.CVSOperation_2; - } - }; - } + return CVSUIMessages.CVSOperation_2; + } + }; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheBaseContentsOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheBaseContentsOperation.java index cd0d15bac..1fc91f696 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheBaseContentsOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheBaseContentsOperation.java @@ -99,7 +99,7 @@ public class CacheBaseContentsOperation extends CacheTreeContentsOperation { private void performCleanTimestamps(IProject project, final IResource[] resources, IProgressMonitor monitor) throws CVSException { ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project); - final ContentComparisonSyncInfoFilter comparator = new SyncInfoFilter.ContentComparisonSyncInfoFilter(false); + final ContentComparisonSyncInfoFilter comparator = new SyncInfoFilter.ContentComparisonSyncInfoFilter(false); folder.run(monitor1 -> { monitor1.beginTask(null, resources.length * 100); for (int i = 0; i < resources.length; i++) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheTreeContentsOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheTreeContentsOperation.java index 9177bbe08..b0955b832 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheTreeContentsOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CacheTreeContentsOperation.java @@ -129,28 +129,28 @@ public abstract class CacheTreeContentsOperation extends SingleCommandOperation @Override protected ICVSResource[] getCVSArguments(Session session, IResource[] resources) { List<ICVSResource> result = new ArrayList<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - try { + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + try { ICVSResource file = session.getLocalRoot().getChild(resource.getProjectRelativePath().toString()); result.add(file); } catch (CVSException e) { // Log and continue CVSUIPlugin.log(e); } - } + } - return result.toArray(new ICVSResource[result.size()]); + return result.toArray(new ICVSResource[result.size()]); } @Override protected IStatus executeCommand(Session session, CVSTeamProvider provider, ICVSResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException { return Command.UPDATE.execute( - session, - Command.NO_GLOBAL_OPTIONS, - getLocalOptions(true), - resources, - new UpdateListener(new IUpdateMessageListener() { + session, + Command.NO_GLOBAL_OPTIONS, + getLocalOptions(true), + resources, + new UpdateListener(new IUpdateMessageListener() { @Override public void fileInformation(int type, ICVSFolder parent, String filename) { // Do nothing @@ -169,7 +169,7 @@ public abstract class CacheTreeContentsOperation extends SingleCommandOperation // Do nothing } }), - monitor); + monitor); } @Override diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutIntoOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutIntoOperation.java index 2337cd727..0eb05d5a5 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutIntoOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutIntoOperation.java @@ -250,10 +250,10 @@ public class CheckoutIntoOperation extends CheckoutOperation { FolderSyncInfo info = folder.getFolderSyncInfo(); if (info.isSameMapping(remoteInfo)) { throw new CVSException(NLS.bind(CVSUIMessages.CheckoutIntoOperation_mappingAlreadyExists, (new Object[] { - remoteFolder.getName(), - targetFolder.getIResource().getFullPath().toString(), - resource.getFullPath().toString() - }))); + remoteFolder.getName(), + targetFolder.getIResource().getFullPath().toString(), + resource.getFullPath().toString() + }))); } folder.acceptChildren(this); } @@ -418,9 +418,9 @@ public class CheckoutIntoOperation extends CheckoutOperation { //use the modfiy rule for the time being //TODO: Just lock the project not the entire workspace (so can't use modifyRule) //since the project already exists - IProject tempProject = getLocalFolder().getIResource().getProject(); - IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory(); - return ruleFactory.modifyRule(tempProject); + IProject tempProject = getLocalFolder().getIResource().getProject(); + IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory(); + return ruleFactory.modifyRule(tempProject); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutOperation.java index 03ce62031..863931ea3 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutOperation.java @@ -69,13 +69,13 @@ public abstract class CheckoutOperation extends RemoteOperation { } @Override - public boolean isKeepOneProgressServiceEntry() { - // Keep the last repository provider operation in the progress service - return true; - } - + public boolean isKeepOneProgressServiceEntry() { + // Keep the last repository provider operation in the progress service + return true; + } + @Override - protected IAction getGotoAction() { - return getShowConsoleAction(); - } + protected IAction getGotoAction() { + return getShowConsoleAction(); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutToRemoteFolderOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutToRemoteFolderOperation.java index 512d8a3b9..c0b093015 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutToRemoteFolderOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CheckoutToRemoteFolderOperation.java @@ -58,7 +58,7 @@ public class CheckoutToRemoteFolderOperation extends CheckoutOperation { throws CVSException { if (mFile instanceof RemoteFile) { - try { + try { ((RemoteFile)mFile).aboutToReceiveContents(entryLine.getBytes()); super.receiveTargetFile( session, @@ -69,9 +69,9 @@ public class CheckoutToRemoteFolderOperation extends CheckoutOperation { readOnly, executable, monitor); - } finally { - ((RemoteFile)mFile).doneReceivingContents(); - } + } finally { + ((RemoteFile)mFile).doneReceivingContents(); + } } else { super.receiveTargetFile( session, diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ClipboardDiffOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ClipboardDiffOperation.java index f7125bee5..a51131f09 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ClipboardDiffOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ClipboardDiffOperation.java @@ -29,7 +29,7 @@ public class ClipboardDiffOperation extends DiffOperation { private static final Object DESTINATION_CLIPBOARD = CVSUIMessages.ClipboardDiffOperation_Clipboard; - final ByteArrayOutputStream os = new ByteArrayOutputStream(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); public ClipboardDiffOperation(IWorkbenchPart part, ResourceMapping[] mappings, LocalOption[] options, boolean isMultiPatch, boolean includeFullPathInformation, IPath patchRoot) { super(part, mappings, options, isMultiPatch, includeFullPathInformation, patchRoot, DESTINATION_CLIPBOARD); @@ -37,24 +37,24 @@ public class ClipboardDiffOperation extends DiffOperation { @Override public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { - super.execute(monitor); - - if (os.size() == 0 || - (!patchHasContents && !patchHasNewFiles)) { - reportEmptyDiff(); - } else { - copyToClipboard(os); - } - } + super.execute(monitor); + + if (os.size() == 0 || + (!patchHasContents && !patchHasNewFiles)) { + reportEmptyDiff(); + } else { + copyToClipboard(os); + } + } - private void copyToClipboard(final ByteArrayOutputStream baos) { + private void copyToClipboard(final ByteArrayOutputStream baos) { getShell().getDisplay().syncExec(() -> { TextTransfer plainTextTransfer = TextTransfer.getInstance(); Clipboard clipboard = new Clipboard(getShell().getDisplay()); clipboard.setContents(new String[] { baos.toString() }, new Transfer[] { plainTextTransfer }); clipboard.dispose(); }); - } + } @Override protected PrintStream openStream() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CommitOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CommitOperation.java index 273f7e7a4..9f3bb9757 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CommitOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/CommitOperation.java @@ -67,7 +67,7 @@ public class CommitOperation extends SingleCommandOperation { } @Override - protected ResourceMappingContext getResourceMappingContext() { - return SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); - } + protected ResourceMappingContext getResourceMappingContext() { + return SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/DisconnectOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/DisconnectOperation.java index 71041bbd0..930bc60b8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/DisconnectOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/DisconnectOperation.java @@ -45,7 +45,7 @@ public class DisconnectOperation extends RepositoryProviderOperation { throws CVSException, InterruptedException { // This method will be invoked for each provider being disconnected - monitor.beginTask(null, IProgressMonitor.UNKNOWN); + monitor.beginTask(null, IProgressMonitor.UNKNOWN); IProject project = provider.getProject(); try { RepositoryProvider.unmap(project); @@ -57,7 +57,7 @@ public class DisconnectOperation extends RepositoryProviderOperation { cvsFolder.unmanage(monitor); EclipseSynchronizer.getInstance().deconfigure(project, Policy.subMonitorFor(monitor, IProgressMonitor.UNKNOWN)); } - monitor.done(); + monitor.done(); } @Override diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchAllMembersOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchAllMembersOperation.java index a8fea5535..df4b39a09 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchAllMembersOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FetchAllMembersOperation.java @@ -33,37 +33,37 @@ import org.eclipse.team.internal.ui.Utils; import org.eclipse.ui.IWorkbenchPart; public class FetchAllMembersOperation extends RemoteOperation { - + class RLogTreeBuilder { - - private ICVSRepositoryLocation location; + + private ICVSRepositoryLocation location; private RemoteFolderTree tree; private CVSTag tag; - public RLogTreeBuilder(ICVSRepositoryLocation location, CVSTag tag) { - this.tag = tag; - this.location = location; - reset(); - } + public RLogTreeBuilder(ICVSRepositoryLocation location, CVSTag tag) { + this.tag = tag; + this.location = location; + reset(); + } + + public RemoteFolderTree getTree() { + return tree; + } + + /** + * Reset the builder to prepare for a new build + */ + public void reset() { + tree = new RemoteFolderTree(null, location, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, tag); + tree.setChildren(new ICVSRemoteResource[0]); + } - public RemoteFolderTree getTree() { - return tree; - } - - /** - * Reset the builder to prepare for a new build - */ - public void reset() { - tree = new RemoteFolderTree(null, location, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, tag); - tree.setChildren(new ICVSRemoteResource[0]); - } - /* * @see * org.eclipse.team.internal.ccvs.core.client.listeners.RDiffSummaryListener. * IFileDiffListener#newFile(java.lang.String, java.lang.String) */ - public void newFile(IPath remoteFilePath, ICVSRemoteFile remoteFile) { + public void newFile(IPath remoteFilePath, ICVSRemoteFile remoteFile) { try { addFile(tree,tag,remoteFile, remoteFilePath); } catch (CVSException e) { @@ -89,7 +89,7 @@ public class FetchAllMembersOperation extends RemoteOperation { tree.setChildren(newChildren); } - /* + /* * Get the folder at the given path in the given tree, creating any missing folders as needed. */ private ICVSRemoteFolder getFolder(RemoteFolderTree tree, CVSTag tag, IPath remoteFolderPath, IPath parentPath) throws CVSException { @@ -130,7 +130,7 @@ public class FetchAllMembersOperation extends RemoteOperation { try { operation.run(monitor); ICVSRemoteResource[] remoteRes = getRemoteResources(); - final ICVSRemoteFolder project = (ICVSRemoteFolder) remoteRes[0]; + final ICVSRemoteFolder project = (ICVSRemoteFolder) remoteRes[0]; //Get the entry paths String[] entry = cache.getCachedFilePaths(); //Strip repo + project info from entries diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FileDiffOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FileDiffOperation.java index 99a818dac..840ec84d5 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FileDiffOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/FileDiffOperation.java @@ -42,8 +42,8 @@ public class FileDiffOperation extends DiffOperation { @Override public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { - super.execute(monitor); - + super.execute(monitor); + if (tempFile.length() == 0) { tempFile.delete(); reportEmptyDiff(); @@ -57,7 +57,7 @@ public class FileDiffOperation extends DiffOperation { return; } - copyFile(); + copyFile(); } protected void copyFile() throws CVSException { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ITagOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ITagOperation.java index 1e3d76ae7..353b927d4 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ITagOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ITagOperation.java @@ -23,11 +23,11 @@ public interface ITagOperation { public abstract void setTag(CVSTag tag); public abstract void run() throws InvocationTargetException, InterruptedException; /** - * Return whether the tag operation contains any resource that would be operated on. - * @return whether the tag operation contains any resource that would be operated on + * Return whether the tag operation contains any resource that would be operated on. + * @return whether the tag operation contains any resource that would be operated on */ public abstract boolean isEmpty(); public abstract void moveTag(); public abstract void doNotRecurse(); - public abstract TagSource getTagSource(); + public abstract TagSource getTagSource(); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteCompareOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteCompareOperation.java index d8b5a6d6b..97d82aeeb 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteCompareOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteCompareOperation.java @@ -36,91 +36,91 @@ import org.eclipse.ui.IWorkbenchPart; * Compare the two versions of given remote folders obtained from the two tags specified. */ public class RemoteCompareOperation extends RemoteOperation { - - private CompareTreeBuilder builder; - private CVSTag left, right; - /** - * Helper class for builder and comparing the resource trees - */ + private CompareTreeBuilder builder; + private CVSTag left, right; + + /** + * Helper class for builder and comparing the resource trees + */ public static class CompareTreeBuilder implements RDiffSummaryListener.IFileDiffListener { - private ICVSRepositoryLocation location; + private ICVSRepositoryLocation location; private RemoteFolderTree leftTree, rightTree; private CVSTag left, right; - public CompareTreeBuilder(ICVSRepositoryLocation location, CVSTag left, CVSTag right) { - this.left = left; - this.right = right; - this.location = location; - reset(); - } + public CompareTreeBuilder(ICVSRepositoryLocation location, CVSTag left, CVSTag right) { + this.left = left; + this.right = right; + this.location = location; + reset(); + } + + public RemoteFolderTree getLeftTree() { + return leftTree; + } + public RemoteFolderTree getRightTree() { + return rightTree; + } - public RemoteFolderTree getLeftTree() { - return leftTree; - } - public RemoteFolderTree getRightTree() { - return rightTree; - } - - /** - * Reset the builder to prepare for a new build - */ - public void reset() { - leftTree = new RemoteFolderTree(null, location, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, left); - leftTree.setChildren(new ICVSRemoteResource[0]); - rightTree = new RemoteFolderTree(null, location, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, right); - rightTree.setChildren(new ICVSRemoteResource[0]); - } - - /** - * Cache the contents for the files that are about to be compares - * @throws CVSException - */ - public void cacheContents(IProgressMonitor monitor) throws CVSException { + /** + * Reset the builder to prepare for a new build + */ + public void reset() { + leftTree = new RemoteFolderTree(null, location, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, left); + leftTree.setChildren(new ICVSRemoteResource[0]); + rightTree = new RemoteFolderTree(null, location, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, right); + rightTree.setChildren(new ICVSRemoteResource[0]); + } + + /** + * Cache the contents for the files that are about to be compares + * @throws CVSException + */ + public void cacheContents(IProgressMonitor monitor) throws CVSException { String[] overlappingFilePaths = getOverlappingFilePaths(); if (overlappingFilePaths.length > 0) { - monitor.beginTask(null, 100); + monitor.beginTask(null, 100); fetchFileContents(leftTree, overlappingFilePaths, Policy.subMonitorFor(monitor, 50)); fetchFileContents(rightTree, overlappingFilePaths, Policy.subMonitorFor(monitor, 50)); monitor.done(); } - } - - /** - * Open the comparison in a compare editor - */ - public void openCompareEditor(final IWorkbenchPage page, final String title, final String toolTip) { + } + + /** + * Open the comparison in a compare editor + */ + public void openCompareEditor(final IWorkbenchPage page, final String title, final String toolTip) { if (leftTree == null || rightTree == null) return; Display.getDefault().asyncExec(() -> CompareUI.openCompareEditorOnPage(new CVSCompareEditorInput(title, toolTip, new ResourceEditionNode(leftTree), new ResourceEditionNode(rightTree)), page)); - } + } - /** - * Add the predecessor to the left tree and the remote to the right tree. - * @param predecessor - * @param remote - */ - public void addToTrees(ICVSRemoteFile predecessor, ICVSRemoteFile remote) { - if (remote != null) { + /** + * Add the predecessor to the left tree and the remote to the right tree. + * @param predecessor + * @param remote + */ + public void addToTrees(ICVSRemoteFile predecessor, ICVSRemoteFile remote) { + if (remote != null) { try { Path filePath = new Path(null, remote.getRepositoryRelativePath()); - addFile(rightTree, right, filePath, remote.getRevision()); + addFile(rightTree, right, filePath, remote.getRevision()); getFolder(leftTree, left, filePath.removeLastSegments(1), Path.EMPTY); } catch (TeamException e) { CVSUIPlugin.log(e); } - } - if (predecessor != null) { + } + if (predecessor != null) { try { Path filePath = new Path(null, predecessor.getRepositoryRelativePath()); - addFile(leftTree, left, filePath, predecessor.getRevision()); + addFile(leftTree, left, filePath, predecessor.getRevision()); getFolder(rightTree, right, filePath.removeLastSegments(1), Path.EMPTY); } catch (TeamException e) { CVSUIPlugin.log(e); } - } - } - + } + } + private void addFile(RemoteFolderTree tree, CVSTag tag, Path filePath, String revision) throws CVSException { RemoteFolderTree parent = (RemoteFolderTree)getFolder(tree, tag, filePath.removeLastSegments(1), Path.EMPTY); String name = filePath.lastSegment(); @@ -128,14 +128,14 @@ public class RemoteCompareOperation extends RemoteOperation { addChild(parent, file); } - private CVSTag getTag(String revision, CVSTag tag) { - if (tag == null) { - tag = new CVSTag(revision, CVSTag.VERSION); - } - return tag; - } + private CVSTag getTag(String revision, CVSTag tag) { + if (tag == null) { + tag = new CVSTag(revision, CVSTag.VERSION); + } + return tag; + } - /* + /* * Get the folder at the given path in the given tree, creating any missing folders as needed. */ private ICVSRemoteFolder getFolder(RemoteFolderTree tree, CVSTag tag, IPath remoteFolderPath, IPath parentPath) throws CVSException { @@ -165,7 +165,7 @@ public class RemoteCompareOperation extends RemoteOperation { } tree.setChildren(newChildren); } - + @Override public void fileDiff(String remoteFilePath, String leftRevision, String rightRevision) { try { @@ -320,7 +320,7 @@ public class RemoteCompareOperation extends RemoteOperation { ICVSRemoteResource resource = getRemoteResource(); IStatus status = buildTrees(resource, Policy.subMonitorFor(monitor, 50)); if (status.isOK() && fetchContents) { - builder.cacheContents(Policy.subMonitorFor(monitor, 100)); + builder.cacheContents(Policy.subMonitorFor(monitor, 100)); } collectStatus(status); openCompareEditor(builder); @@ -330,18 +330,18 @@ public class RemoteCompareOperation extends RemoteOperation { } /** - * This method is here to allow subclasses to override - */ - protected void openCompareEditor(CompareTreeBuilder builder) { - builder.openCompareEditor(getTargetPage(), null, null); - } + * This method is here to allow subclasses to override + */ + protected void openCompareEditor(CompareTreeBuilder builder) { + builder.openCompareEditor(getTargetPage(), null, null); + } - /* + /* * Build the two trees uses the reponses from "cvs rdiff -s ...". */ private IStatus buildTrees(ICVSRemoteResource resource, IProgressMonitor monitor) throws CVSException { // Initialize the resulting trees - builder.reset(); + builder.reset(); Command.QuietOption oldOption= CVSProviderPlugin.getPlugin().getQuietness(); Session session = new Session(resource.getRepository(), builder.getLeftTree(), false); try { @@ -365,7 +365,7 @@ public class RemoteCompareOperation extends RemoteOperation { } } - private LocalOption[] getLocalOptions() { + private LocalOption[] getLocalOptions() { return new LocalOption[] {RDiff.SUMMARY, RDiff.makeTagOption(left), RDiff.makeTagOption(right)}; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteLogOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteLogOperation.java index b9f01201a..8eeb0d664 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteLogOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RemoteLogOperation.java @@ -46,41 +46,41 @@ public class RemoteLogOperation extends RepositoryLocationOperation { * remote log operation. */ public static class LogEntryCache implements ILogEntryListener { - - /* - * Cache of all log entries - */ + + /* + * Cache of all log entries + */ private Map<String, Map<String, ILogEntry>> entries = new HashMap<>(); /* * Map String:remoteFilePath->Map * (String:revision -> ILogEntry) */ private Map<String, ILogEntry> internalGetLogEntries(String path) { - return entries.get(path); - } - - /** - * Return all the log entries at the given path - * @param path the file path - * @return the log entries for the file - */ - public ILogEntry[] getLogEntries(String path) { + return entries.get(path); + } + + /** + * Return all the log entries at the given path + * @param path the file path + * @return the log entries for the file + */ + public ILogEntry[] getLogEntries(String path) { Map<String, ILogEntry> map = internalGetLogEntries(path); - return map.values().toArray(new ILogEntry[map.values().size()]); - } - - private ILogEntry internalGetLogEntry(String path, String revision) { - Map fileEntries = internalGetLogEntries(path); - if (fileEntries != null) { - return (ILogEntry)fileEntries.get(revision); - } - return null; - } - - public String[] getCachedFilePaths() { - return entries.keySet().toArray(new String[entries.size()]); - } - + return map.values().toArray(new ILogEntry[map.values().size()]); + } + + private ILogEntry internalGetLogEntry(String path, String revision) { + Map fileEntries = internalGetLogEntries(path); + if (fileEntries != null) { + return (ILogEntry)fileEntries.get(revision); + } + return null; + } + + public String[] getCachedFilePaths() { + return entries.keySet().toArray(new String[entries.size()]); + } + /** * Return the log entry that for the given resource * or <code>null</code> if no entry was fetched or the @@ -89,20 +89,20 @@ public class RemoteLogOperation extends RepositoryLocationOperation { * @return the log entry or <code>null</code> */ public synchronized ILogEntry getLogEntry(ICVSRemoteResource resource) { - if (resource instanceof ICVSRemoteFile) { - try { - String path = getFullPath(resource); - String revision = ((ICVSRemoteFile)resource).getRevision(); - return internalGetLogEntry(path, revision); - } catch (TeamException e) { - // Log and return null - CVSUIPlugin.log(e); - } - } - return null; + if (resource instanceof ICVSRemoteFile) { + try { + String path = getFullPath(resource); + String revision = ((ICVSRemoteFile)resource).getRevision(); + return internalGetLogEntry(path, revision); + } catch (TeamException e) { + // Log and return null + CVSUIPlugin.log(e); + } + } + return null; } - /** + /** * Return the log entries that were fetched for the given resource * or an empty list if no entry was fetched. * @param getFullPath(resource) the resource @@ -110,125 +110,125 @@ public class RemoteLogOperation extends RepositoryLocationOperation { */ public synchronized ILogEntry[] getLogEntries(ICVSRemoteResource resource) { Map<String, ILogEntry> fileEntries = internalGetLogEntries(getFullPath(resource)); - if (fileEntries != null) { - return fileEntries.values().toArray(new ILogEntry[fileEntries.size()]); - } - return new ILogEntry[0]; + if (fileEntries != null) { + return fileEntries.values().toArray(new ILogEntry[fileEntries.size()]); + } + return new ILogEntry[0]; } /* - * Return the full path that uniquely identifies the resource - * accross repositories. This path include the repository and - * resource path but does not include the revision so that - * all log entries for a file can be retrieved. - */ - private String getFullPath(ICVSRemoteResource resource) { - return Util.appendPath(resource.getRepository().getLocation(false), resource.getRepositoryRelativePath()); - } + * Return the full path that uniquely identifies the resource + * accross repositories. This path include the repository and + * resource path but does not include the revision so that + * all log entries for a file can be retrieved. + */ + private String getFullPath(ICVSRemoteResource resource) { + return Util.appendPath(resource.getRepository().getLocation(false), resource.getRepositoryRelativePath()); + } public synchronized void clearEntries() { entries.clear(); } - - public synchronized ICVSRemoteFile getImmediatePredecessor(ICVSRemoteFile file) throws TeamException { - ILogEntry[] allLogs = getLogEntries(file); - String revision = file.getRevision(); - // First decrement the last digit and see if that revision exists - String predecessorRevision = getPredecessorRevision(revision); - ICVSRemoteFile predecessor = findRevison(allLogs, predecessorRevision); - // If nothing was found, try to fond the base of a branch - if (predecessor == null && isBrancheRevision(revision)) { - predecessorRevision = getBaseRevision(revision); - predecessor = findRevison(allLogs, predecessorRevision); - } - // If that fails, it is still possible that there is a revision. - // This can happen if the revision has been manually set. - if (predecessor == null) { - // We don't search in this case since this is costly and would be done - // for any file that is new as well. - } - return predecessor; - } - - /* - * Find the given revision in the list of log entries. - * Return null if the revision wasn't found. - */ - private ICVSRemoteFile findRevison(ILogEntry[] allLogs, String predecessorRevision) throws TeamException { - for (int i = 0; i < allLogs.length; i++) { - ILogEntry entry = allLogs[i]; - ICVSRemoteFile file = entry.getRemoteFile(); - if (file.getRevision().equals(predecessorRevision)) { - return file; - } - } - return null; - } - /* - * Decrement the trailing digit by one. - */ - private String getPredecessorRevision(String revision) { - int digits[] = Util.convertToDigits(revision); - digits[digits.length -1]--; - StringBuffer buffer = new StringBuffer(revision.length()); - for (int i = 0; i < digits.length; i++) { - buffer.append(Integer.toString(digits[i])); - if (i < digits.length - 1) { - buffer.append('.'); - } - } - return buffer.toString(); - } - - /* - * Return true if there are more than 2 digits in the revision number - * (i.e. the revision is on a branch) - */ - private boolean isBrancheRevision(String revision) { - return Util.convertToDigits(revision).length > 2; - } - - /* - * Remove the trailing revision digits such that the - * returned revision is shorter than the given revision - * and is an even number of digits long - */ - private String getBaseRevision(String revision) { - int digits[] = Util.convertToDigits(revision); - int length = digits.length - 1; - if (length % 2 == 1) { - length--; - } - StringBuffer buffer = new StringBuffer(revision.length()); - for (int i = 0; i < length; i++) { - buffer.append(Integer.toString(digits[i])); - if (i < length - 1) { - buffer.append('.'); - } - } - return buffer.toString(); - } - /** - * Remove any entries for the remote resources - * @param resource the remote resource - */ - public synchronized void clearEntries(ICVSRemoteResource resource) { - String remotePath = getFullPath(resource); - entries.remove(remotePath); - } + + public synchronized ICVSRemoteFile getImmediatePredecessor(ICVSRemoteFile file) throws TeamException { + ILogEntry[] allLogs = getLogEntries(file); + String revision = file.getRevision(); + // First decrement the last digit and see if that revision exists + String predecessorRevision = getPredecessorRevision(revision); + ICVSRemoteFile predecessor = findRevison(allLogs, predecessorRevision); + // If nothing was found, try to fond the base of a branch + if (predecessor == null && isBrancheRevision(revision)) { + predecessorRevision = getBaseRevision(revision); + predecessor = findRevison(allLogs, predecessorRevision); + } + // If that fails, it is still possible that there is a revision. + // This can happen if the revision has been manually set. + if (predecessor == null) { + // We don't search in this case since this is costly and would be done + // for any file that is new as well. + } + return predecessor; + } + + /* + * Find the given revision in the list of log entries. + * Return null if the revision wasn't found. + */ + private ICVSRemoteFile findRevison(ILogEntry[] allLogs, String predecessorRevision) throws TeamException { + for (int i = 0; i < allLogs.length; i++) { + ILogEntry entry = allLogs[i]; + ICVSRemoteFile file = entry.getRemoteFile(); + if (file.getRevision().equals(predecessorRevision)) { + return file; + } + } + return null; + } + /* + * Decrement the trailing digit by one. + */ + private String getPredecessorRevision(String revision) { + int digits[] = Util.convertToDigits(revision); + digits[digits.length -1]--; + StringBuffer buffer = new StringBuffer(revision.length()); + for (int i = 0; i < digits.length; i++) { + buffer.append(Integer.toString(digits[i])); + if (i < digits.length - 1) { + buffer.append('.'); + } + } + return buffer.toString(); + } + + /* + * Return true if there are more than 2 digits in the revision number + * (i.e. the revision is on a branch) + */ + private boolean isBrancheRevision(String revision) { + return Util.convertToDigits(revision).length > 2; + } + + /* + * Remove the trailing revision digits such that the + * returned revision is shorter than the given revision + * and is an even number of digits long + */ + private String getBaseRevision(String revision) { + int digits[] = Util.convertToDigits(revision); + int length = digits.length - 1; + if (length % 2 == 1) { + length--; + } + StringBuffer buffer = new StringBuffer(revision.length()); + for (int i = 0; i < length; i++) { + buffer.append(Integer.toString(digits[i])); + if (i < length - 1) { + buffer.append('.'); + } + } + return buffer.toString(); + } + /** + * Remove any entries for the remote resources + * @param resource the remote resource + */ + public synchronized void clearEntries(ICVSRemoteResource resource) { + String remotePath = getFullPath(resource); + entries.remove(remotePath); + } - @Override + @Override public void handleLogEntryReceived(ILogEntry entry) { - ICVSRemoteFile file = entry.getRemoteFile(); - String fullPath = getFullPath(file); - String revision = entry.getRevision(); + ICVSRemoteFile file = entry.getRemoteFile(); + String fullPath = getFullPath(file); + String revision = entry.getRevision(); Map<String, ILogEntry> fileEntries = internalGetLogEntries(fullPath); - if (fileEntries == null) { + if (fileEntries == null) { fileEntries = new HashMap<>(); - entries.put(fullPath, fileEntries); - } - fileEntries.put(revision, entry); - } + entries.put(fullPath, fileEntries); + } + fileEntries.put(revision, entry); + } } public RemoteLogOperation(IWorkbenchPart part, ICVSRemoteResource[] remoteResources, CVSTag tag1, CVSTag tag2, LogEntryCache cache) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ReplaceOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ReplaceOperation.java index 8fb53734a..0962590cb 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ReplaceOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ReplaceOperation.java @@ -44,8 +44,8 @@ public class ReplaceOperation extends UpdateOperation { } public ReplaceOperation(IWorkbenchPart part, ResourceMapping[] mappings, CVSTag tag) { - super(part, mappings, new LocalOption[] { Update.IGNORE_LOCAL_CHANGES }, tag); - } + super(part, mappings, new LocalOption[] { Update.IGNORE_LOCAL_CHANGES }, tag); + } @Override protected String getTaskName() { @@ -60,8 +60,8 @@ public class ReplaceOperation extends UpdateOperation { final boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException { - final IStatus[] status = new IStatus[] { Status.OK_STATUS }; - try { + final IStatus[] status = new IStatus[] { Status.OK_STATUS }; + try { ResourcesPlugin.getWorkspace().run((IWorkspaceRunnable) monitor1 -> { try { status[0] = internalExecuteCommand(session, provider, resources, recurse, monitor1); @@ -69,9 +69,9 @@ public class ReplaceOperation extends UpdateOperation { throw new OperationCanceledException(); } }, null, IWorkspace.AVOID_UPDATE, monitor); - } catch (CoreException e) { - throw CVSException.wrapException(e); - } + } catch (CoreException e) { + throw CVSException.wrapException(e); + } return status[0]; } @@ -85,41 +85,41 @@ public class ReplaceOperation extends UpdateOperation { private boolean ignoreResourcesIfTagDoesNotExist; - private IStatus internalExecuteCommand(Session session, CVSTeamProvider provider, ICVSResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException { - monitor.beginTask(null, 100); - ICVSResource[] managedResources = getResourcesToUpdate(resources, Policy.subMonitorFor(monitor, 5)); + private IStatus internalExecuteCommand(Session session, CVSTeamProvider provider, ICVSResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException { + monitor.beginTask(null, 100); + ICVSResource[] managedResources = getResourcesToUpdate(resources, Policy.subMonitorFor(monitor, 5)); if (ignoreResourcesIfTagDoesNotExist && managedResources.length == 0) return OK; - try { - // Purge any unmanaged or added files - PrepareForReplaceVisitor pfrv = new PrepareForReplaceVisitor(session, getTag()); - pfrv.visitResources( - provider.getProject(), - resources, - CVSUIMessages.ReplaceOperation_1, - recurse ? IResource.DEPTH_INFINITE : IResource.DEPTH_ONE, - Policy.subMonitorFor(monitor, 25)); - prepDeletedFiles = pfrv.getDeletedFiles(); - - // Only perform the remote command if some of the resources being replaced were managed - IStatus status = OK; - if (managedResources.length > 0) { - // Perform an update, ignoring any local file modifications - status = super.executeCommand(session, provider, managedResources, recurse, Policy.subMonitorFor(monitor, 70)); - } - - // Prune any empty folders left after the resources were purged. - // This is done to prune any empty folders that contained only unmanaged resources - if (status.isOK() && CVSProviderPlugin.getPlugin().getPruneEmptyDirectories()) { - new PruneFolderVisitor().visit(session, resources); - } - - return status; - } finally { - monitor.done(); - } - } + try { + // Purge any unmanaged or added files + PrepareForReplaceVisitor pfrv = new PrepareForReplaceVisitor(session, getTag()); + pfrv.visitResources( + provider.getProject(), + resources, + CVSUIMessages.ReplaceOperation_1, + recurse ? IResource.DEPTH_INFINITE : IResource.DEPTH_ONE, + Policy.subMonitorFor(monitor, 25)); + prepDeletedFiles = pfrv.getDeletedFiles(); + + // Only perform the remote command if some of the resources being replaced were managed + IStatus status = OK; + if (managedResources.length > 0) { + // Perform an update, ignoring any local file modifications + status = super.executeCommand(session, provider, managedResources, recurse, Policy.subMonitorFor(monitor, 70)); + } + + // Prune any empty folders left after the resources were purged. + // This is done to prune any empty folders that contained only unmanaged resources + if (status.isOK() && CVSProviderPlugin.getPlugin().getPruneEmptyDirectories()) { + new PruneFolderVisitor().visit(session, resources); + } + + return status; + } finally { + monitor.done(); + } + } /** * Return the resources that need to be updated from the server. diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RepositoryProviderOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RepositoryProviderOperation.java index 12246e034..594210167 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RepositoryProviderOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/RepositoryProviderOperation.java @@ -53,255 +53,255 @@ public abstract class RepositoryProviderOperation extends CVSOperation { private ISynchronizationScopeManager manager; private final ResourceMapping[] selectedMappings; - /** - * Interface that is available to subclasses which identifies - * the depth for various resources. The files will be included - * in whichever group (deep or shallow) has resources. - */ - public interface ICVSTraversal { - IResource[] getShallowResources(); - IResource[] getDeepResources(); - IResource[] getNontraversedFolders(); - } - + /** + * Interface that is available to subclasses which identifies + * the depth for various resources. The files will be included + * in whichever group (deep or shallow) has resources. + */ + public interface ICVSTraversal { + IResource[] getShallowResources(); + IResource[] getDeepResources(); + IResource[] getNontraversedFolders(); + } + /* * A map entry for a provider that divides the traversals to be performed by depth. * There are really only */ private static class TraversalMapEntry implements ICVSTraversal { - // The provider for this entry - RepositoryProvider provider; - // Files are always shallow + // The provider for this entry + RepositoryProvider provider; + // Files are always shallow List<IResource> files = new ArrayList<>(); - // Not sure what to do with zero depth folders but we'll record them + // Not sure what to do with zero depth folders but we'll record them List<IResource> zeroFolders = new ArrayList<>(); - // Non-recursive folder (-l) + // Non-recursive folder (-l) List<IResource> shallowFolders = new ArrayList<>(); - // Recursive folders (-R) + // Recursive folders (-R) List<IResource> deepFolders = new ArrayList<>(); - public TraversalMapEntry(RepositoryProvider provider) { - this.provider = provider; - } - /** - * Add the resources from the traversals to the entry - * @param traversals the traversals - */ - public void add(ResourceTraversal[] traversals) { - for (int i = 0; i < traversals.length; i++) { - ResourceTraversal traversal = traversals[i]; - add(traversal); - } - } - /** - * Add the resources from the traversal to the entry - * @param traversal the traversal - */ - public void add(ResourceTraversal traversal) { - IResource[] resources = traversal.getResources(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - if (resource.getProject().equals(provider.getProject())) { - if (resource.getType() == IResource.FILE) { - files.add(resource); - } else { - switch (traversal.getDepth()) { - case IResource.DEPTH_ZERO: - zeroFolders.add(resource); - break; - case IResource.DEPTH_ONE: - shallowFolders.add(resource); - break; - case IResource.DEPTH_INFINITE: - deepFolders.add(resource); - break; - default: - deepFolders.add(resource); - } - } - } - } - } - /** - * Return the resources that can be included in a shallow operation. - * Include files with the shallow resources if there are shallow folders - * or if there are no shallow or deep folders. - * @return the resources that can be included in a shallow operation - */ - @Override + public TraversalMapEntry(RepositoryProvider provider) { + this.provider = provider; + } + /** + * Add the resources from the traversals to the entry + * @param traversals the traversals + */ + public void add(ResourceTraversal[] traversals) { + for (int i = 0; i < traversals.length; i++) { + ResourceTraversal traversal = traversals[i]; + add(traversal); + } + } + /** + * Add the resources from the traversal to the entry + * @param traversal the traversal + */ + public void add(ResourceTraversal traversal) { + IResource[] resources = traversal.getResources(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + if (resource.getProject().equals(provider.getProject())) { + if (resource.getType() == IResource.FILE) { + files.add(resource); + } else { + switch (traversal.getDepth()) { + case IResource.DEPTH_ZERO: + zeroFolders.add(resource); + break; + case IResource.DEPTH_ONE: + shallowFolders.add(resource); + break; + case IResource.DEPTH_INFINITE: + deepFolders.add(resource); + break; + default: + deepFolders.add(resource); + } + } + } + } + } + /** + * Return the resources that can be included in a shallow operation. + * Include files with the shallow resources if there are shallow folders + * or if there are no shallow or deep folders. + * @return the resources that can be included in a shallow operation + */ + @Override public IResource[] getShallowResources() { - if (shallowFolders.isEmpty() && deepFolders.isEmpty() && !files.isEmpty()) { - return files.toArray(new IResource[files.size()]); - } - if (!shallowFolders.isEmpty()) { - if (files.isEmpty()) { - return shallowFolders.toArray(new IResource[shallowFolders.size()]); - } + if (shallowFolders.isEmpty() && deepFolders.isEmpty() && !files.isEmpty()) { + return files.toArray(new IResource[files.size()]); + } + if (!shallowFolders.isEmpty()) { + if (files.isEmpty()) { + return shallowFolders.toArray(new IResource[shallowFolders.size()]); + } List<IResource> result = new ArrayList<>(); - result.addAll(shallowFolders); - result.addAll(files); - return result.toArray(new IResource[result.size()]); - } - return new IResource[0]; - } - /** - * Return the resources to be included in a deep operation. - * If there are no shallow folders, this will include any files. - * @return - */ - @Override + result.addAll(shallowFolders); + result.addAll(files); + return result.toArray(new IResource[result.size()]); + } + return new IResource[0]; + } + /** + * Return the resources to be included in a deep operation. + * If there are no shallow folders, this will include any files. + * @return + */ + @Override public IResource[] getDeepResources() { - if (deepFolders.isEmpty()) - return new IResource[0]; - if (!shallowFolders.isEmpty()) - return deepFolders.toArray(new IResource[deepFolders.size()]); + if (deepFolders.isEmpty()) + return new IResource[0]; + if (!shallowFolders.isEmpty()) + return deepFolders.toArray(new IResource[deepFolders.size()]); List<IResource> result = new ArrayList<>(); - result.addAll(deepFolders); - result.addAll(files); - return result.toArray(new IResource[result.size()]); - } - /** - * Return the folders that are depth zero - */ - @Override + result.addAll(deepFolders); + result.addAll(files); + return result.toArray(new IResource[result.size()]); + } + /** + * Return the folders that are depth zero + */ + @Override public IResource[] getNontraversedFolders() { - return zeroFolders.toArray(new IResource[zeroFolders.size()]); - } + return zeroFolders.toArray(new IResource[zeroFolders.size()]); + } } - - /** - * Convert the provided resources to one or more resource mappers - * that traverse the elements deeply. The model element of the resource - * mappers will be an IStructuredSelection. - * @param resources the resources - * @return a resource mappers that traverses the resources - */ - public static ResourceMapping[] asResourceMappers(final IResource[] resources) { - return asResourceMappers(resources, IResource.DEPTH_INFINITE); - } - - /** - * Convert the provided resources to one or more resource mappers - * that traverse the elements deeply. The model element of the resource - * mappers will be an IStructuredSelection. - * @param resources the resources - * @return a resource mappers that traverses the resources - */ - public static ResourceMapping[] asResourceMappers(final IResource[] resources, int depth) { - return WorkspaceResourceMapper.asResourceMappers(resources, depth); - } - + + /** + * Convert the provided resources to one or more resource mappers + * that traverse the elements deeply. The model element of the resource + * mappers will be an IStructuredSelection. + * @param resources the resources + * @return a resource mappers that traverses the resources + */ + public static ResourceMapping[] asResourceMappers(final IResource[] resources) { + return asResourceMappers(resources, IResource.DEPTH_INFINITE); + } + + /** + * Convert the provided resources to one or more resource mappers + * that traverse the elements deeply. The model element of the resource + * mappers will be an IStructuredSelection. + * @param resources the resources + * @return a resource mappers that traverses the resources + */ + public static ResourceMapping[] asResourceMappers(final IResource[] resources, int depth) { + return WorkspaceResourceMapper.asResourceMappers(resources, depth); + } + public RepositoryProviderOperation(IWorkbenchPart part, final IResource[] resources) { this(part, asResourceMappers(resources)); } - public RepositoryProviderOperation(IWorkbenchPart part, ResourceMapping[] selectedMappings) { - super(part); + public RepositoryProviderOperation(IWorkbenchPart part, ResourceMapping[] selectedMappings) { + super(part); this.selectedMappings = selectedMappings; - } + } @Override public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { try { - monitor.beginTask(null, 100); - buildScope(monitor); - Map table = getProviderTraversalMapping(Policy.subMonitorFor(monitor, 30)); - execute(table, Policy.subMonitorFor(monitor, 30)); - } catch (CoreException e) { - throw CVSException.wrapException(e); - } finally { - monitor.done(); - } + monitor.beginTask(null, 100); + buildScope(monitor); + Map table = getProviderTraversalMapping(Policy.subMonitorFor(monitor, 30)); + execute(table, Policy.subMonitorFor(monitor, 30)); + } catch (CoreException e) { + throw CVSException.wrapException(e); + } finally { + monitor.done(); + } } @Override protected void endOperation() throws CVSException { - if (manager != null) { - manager.dispose(); - manager = null; - } + if (manager != null) { + manager.dispose(); + manager = null; + } super.endOperation(); } - public ISynchronizationScope buildScope(IProgressMonitor monitor) throws InterruptedException, CVSException { - if (manager == null) { - manager = createScopeManager(consultModelsWhenBuildingScope && consultModelsForMappings()); - BuildScopeOperation op = new BuildScopeOperation(getPart(), manager); + public ISynchronizationScope buildScope(IProgressMonitor monitor) throws InterruptedException, CVSException { + if (manager == null) { + manager = createScopeManager(consultModelsWhenBuildingScope && consultModelsForMappings()); + BuildScopeOperation op = new BuildScopeOperation(getPart(), manager); try { op.run(monitor); } catch (InvocationTargetException e) { throw CVSException.wrapException(e); } - } - return manager.getScope(); + } + return manager.getScope(); } - /** - * Create the scope manager to be used by this operation. - * @param consultModels whether models should be consulted to include additional mappings - * @return a scope manager - */ + /** + * Create the scope manager to be used by this operation. + * @param consultModels whether models should be consulted to include additional mappings + * @return a scope manager + */ protected SynchronizationScopeManager createScopeManager(boolean consultModels) { return new SynchronizationScopeManager(getJobName(), getSelectedMappings(), getResourceMappingContext(), consultModels); } private void execute(Map providerTraversal, IProgressMonitor monitor) throws CVSException, InterruptedException { - Set keySet = providerTraversal.keySet(); - monitor.beginTask(null, keySet.size() * 1000); - Iterator iterator = keySet.iterator(); - while (iterator.hasNext()) { - CVSTeamProvider provider = (CVSTeamProvider)iterator.next(); - monitor.setTaskName(getTaskName(provider)); - TraversalMapEntry entry = (TraversalMapEntry)providerTraversal.get(provider); - execute(provider, entry, Policy.subMonitorFor(monitor, 1000)); - } - } + Set keySet = providerTraversal.keySet(); + monitor.beginTask(null, keySet.size() * 1000); + Iterator iterator = keySet.iterator(); + while (iterator.hasNext()) { + CVSTeamProvider provider = (CVSTeamProvider)iterator.next(); + monitor.setTaskName(getTaskName(provider)); + TraversalMapEntry entry = (TraversalMapEntry)providerTraversal.get(provider); + execute(provider, entry, Policy.subMonitorFor(monitor, 1000)); + } + } - /** - * Execute the operation on the given set of traversals - * @param provider - * @param entry - * @param subMonitor - * @throws CVSException - * @throws InterruptedException - */ - protected void execute(CVSTeamProvider provider, ICVSTraversal entry, IProgressMonitor monitor) throws CVSException, InterruptedException { - IResource[] deepResources = entry.getDeepResources(); - IResource[] shallowResources = entry.getShallowResources(); - IResource[] nontraversedFolders = entry.getNontraversedFolders(); - try { - monitor.beginTask(getTaskName(provider), (deepResources.length > 0 ? 100 : 0) + (shallowResources.length > 0 ? 100 : 0) + (nontraversedFolders.length > 0 ? 10 : 0)); - if (deepResources.length == 0 && shallowResources.length == 0 && nontraversedFolders.length == 0) - return; - final ISchedulingRule rule = getSchedulingRule(provider); - try { - Job.getJobManager().beginRule(rule, monitor); - if (deepResources.length > 0) - execute(provider, deepResources, true /* recurse */, Policy.subMonitorFor(monitor, 100)); - if (shallowResources.length > 0) - execute(provider, shallowResources, false /* recurse */, Policy.subMonitorFor(monitor, 100)); - if (nontraversedFolders.length > 0) { - handleNontraversedFolders(provider, nontraversedFolders, Policy.subMonitorFor(monitor, 10)); - } - } finally { - Job.getJobManager().endRule(rule); - } - } finally { - monitor.done(); - } - } + /** + * Execute the operation on the given set of traversals + * @param provider + * @param entry + * @param subMonitor + * @throws CVSException + * @throws InterruptedException + */ + protected void execute(CVSTeamProvider provider, ICVSTraversal entry, IProgressMonitor monitor) throws CVSException, InterruptedException { + IResource[] deepResources = entry.getDeepResources(); + IResource[] shallowResources = entry.getShallowResources(); + IResource[] nontraversedFolders = entry.getNontraversedFolders(); + try { + monitor.beginTask(getTaskName(provider), (deepResources.length > 0 ? 100 : 0) + (shallowResources.length > 0 ? 100 : 0) + (nontraversedFolders.length > 0 ? 10 : 0)); + if (deepResources.length == 0 && shallowResources.length == 0 && nontraversedFolders.length == 0) + return; + final ISchedulingRule rule = getSchedulingRule(provider); + try { + Job.getJobManager().beginRule(rule, monitor); + if (deepResources.length > 0) + execute(provider, deepResources, true /* recurse */, Policy.subMonitorFor(monitor, 100)); + if (shallowResources.length > 0) + execute(provider, shallowResources, false /* recurse */, Policy.subMonitorFor(monitor, 100)); + if (nontraversedFolders.length > 0) { + handleNontraversedFolders(provider, nontraversedFolders, Policy.subMonitorFor(monitor, 10)); + } + } finally { + Job.getJobManager().endRule(rule); + } + } finally { + monitor.done(); + } + } /** - * Handle any non-traversed (depth-zero) folders that were in the logical modle that primed this operation. - * @param provider the repository provider associated with the project containing the folders - * @param nontraversedFolders the folders - * @param monitor a progress monitor - */ - protected void handleNontraversedFolders(CVSTeamProvider provider, IResource[] nontraversedFolders, IProgressMonitor monitor) throws CVSException { - // Default is do nothing - } + * Handle any non-traversed (depth-zero) folders that were in the logical modle that primed this operation. + * @param provider the repository provider associated with the project containing the folders + * @param nontraversedFolders the folders + * @param monitor a progress monitor + */ + protected void handleNontraversedFolders(CVSTeamProvider provider, IResource[] nontraversedFolders, IProgressMonitor monitor) throws CVSException { + // Default is do nothing + } - /** + /** * Return the taskname to be shown in the progress monitor while operating * on the given provider. * @param provider the provider being processed @@ -327,37 +327,37 @@ public abstract class RepositoryProviderOperation extends CVSOperation { Map getProviderTraversalMapping(IProgressMonitor monitor) throws CoreException { Map<RepositoryProvider, TraversalMapEntry> result = new HashMap<>(); ResourceMapping[] mappings = getScope().getMappings(); - for (int j = 0; j < mappings.length; j++) { - ResourceMapping mapping = mappings[j]; - IProject[] projects = mapping.getProjects(); - ResourceTraversal[] traversals = getScope().getTraversals(mapping); - for (int k = 0; k < projects.length; k++) { - IProject project = projects[k]; - RepositoryProvider provider = RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); - if (provider != null) { - TraversalMapEntry entry = result.get(provider); - if (entry == null) { - entry = new TraversalMapEntry(provider); - result.put(provider, entry); - } - entry.add(traversals); - } - } - } + for (int j = 0; j < mappings.length; j++) { + ResourceMapping mapping = mappings[j]; + IProject[] projects = mapping.getProjects(); + ResourceTraversal[] traversals = getScope().getTraversals(mapping); + for (int k = 0; k < projects.length; k++) { + IProject project = projects[k]; + RepositoryProvider provider = RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); + if (provider != null) { + TraversalMapEntry entry = result.get(provider); + if (entry == null) { + entry = new TraversalMapEntry(provider); + result.put(provider, entry); + } + entry.add(traversals); + } + } + } return result; } - /** - * Return the resource mapping context that is to be used by this operation. - * By default, <code>null</code> is returned but subclasses may override - * to provide a specific context. - * @return the resource mapping context for this operation - */ + /** + * Return the resource mapping context that is to be used by this operation. + * By default, <code>null</code> is returned but subclasses may override + * to provide a specific context. + * @return the resource mapping context for this operation + */ protected ResourceMappingContext getResourceMappingContext() { - return ResourceMappingContext.LOCAL_CONTEXT; - } + return ResourceMappingContext.LOCAL_CONTEXT; + } - /** + /** * Execute the operation on the resources for the given provider. * @param provider the provider for the project that contains the resources * @param resources the resources to be operated on @@ -368,19 +368,19 @@ public abstract class RepositoryProviderOperation extends CVSOperation { */ protected abstract void execute(CVSTeamProvider provider, IResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException; - /** - * Return the local options for this operation including the - * option to provide the requested traversal. - * @param recurse deep or shallow - * @return the local options for the operation - */ - protected LocalOption[] getLocalOptions(boolean recurse) { - if (!recurse) { - return new LocalOption[] { Command.DO_NOT_RECURSE }; - } - return Command.NO_LOCAL_OPTIONS; - } - + /** + * Return the local options for this operation including the + * option to provide the requested traversal. + * @param recurse deep or shallow + * @return the local options for the operation + */ + protected LocalOption[] getLocalOptions(boolean recurse) { + if (!recurse) { + return new LocalOption[] { Command.DO_NOT_RECURSE }; + } + return Command.NO_LOCAL_OPTIONS; + } + protected ICVSResource[] getCVSArguments(IResource[] resources) { ICVSResource[] cvsResources = new ICVSResource[resources.length]; for (int i = 0; i < cvsResources.length; i++) { @@ -444,46 +444,46 @@ public abstract class RepositoryProviderOperation extends CVSOperation { } } - @Override + @Override public boolean isKeepOneProgressServiceEntry() { - // Keep the last repository provider operation in the progress service - return true; - } - - @Override + // Keep the last repository provider operation in the progress service + return true; + } + + @Override protected IAction getGotoAction() { - return getShowConsoleAction(); - } - - /** - * Return the root resources for all the traversals of this operation. - * This method may only be invoked after {@link #buildScope(IProgressMonitor) }. - * @return the root resources for all the traversals of this operation - * @throws CoreException - */ - protected IResource[] getTraversalRoots() { + return getShowConsoleAction(); + } + + /** + * Return the root resources for all the traversals of this operation. + * This method may only be invoked after {@link #buildScope(IProgressMonitor) }. + * @return the root resources for all the traversals of this operation + * @throws CoreException + */ + protected IResource[] getTraversalRoots() { List<IResource> result = new ArrayList<>(); - ResourceTraversal[] traversals = getTraversals(); - for (int i = 0; i < traversals.length; i++) { - ResourceTraversal traversal = traversals[i]; - result.addAll(Arrays.asList(traversal.getResources())); - } - return result.toArray(new IResource[result.size()]); - } - - /** - * Return the traversals that will be used by this operation. - * This method can only be called after {@link #buildScope(IProgressMonitor) }. - * @return the traversals that will be used by this operation - * @throws CoreException - */ - public ResourceTraversal[] getTraversals() { - return getScope().getTraversals(); - } - - public boolean consultModelsForMappings() { - return true; - } + ResourceTraversal[] traversals = getTraversals(); + for (int i = 0; i < traversals.length; i++) { + ResourceTraversal traversal = traversals[i]; + result.addAll(Arrays.asList(traversal.getResources())); + } + return result.toArray(new IResource[result.size()]); + } + + /** + * Return the traversals that will be used by this operation. + * This method can only be called after {@link #buildScope(IProgressMonitor) }. + * @return the traversals that will be used by this operation + * @throws CoreException + */ + public ResourceTraversal[] getTraversals() { + return getScope().getTraversals(); + } + + public boolean consultModelsForMappings() { + return true; + } public ResourceMapping[] getSelectedMappings() { return selectedMappings; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShareProjectOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShareProjectOperation.java index eebe6925d..af8b6e747 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShareProjectOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShareProjectOperation.java @@ -110,7 +110,7 @@ public class ShareProjectOperation extends CVSOperation { monitor.beginTask(null, IProgressMonitor.UNKNOWN); purgeAnyCVSFolders(Policy.subMonitorFor(monitor, IProgressMonitor.UNKNOWN)); // Link the project to the newly created module - monitor.subTask(NLS.bind(CVSUIMessages.ShareProjectOperation_3, new String[] { project.getName(), remote.getRepositoryRelativePath() })); + monitor.subTask(NLS.bind(CVSUIMessages.ShareProjectOperation_3, new String[] { project.getName(), remote.getRepositoryRelativePath() })); ICVSFolder folder = (ICVSFolder)CVSWorkspaceRoot.getCVSResourceFor(project); folder.setFolderSyncInfo(remote.getFolderSyncInfo()); //Register it with Team. If it already is, no harm done. @@ -187,7 +187,7 @@ public class ShareProjectOperation extends CVSOperation { */ private void purgeAnyCVSFolders(final IProgressMonitor monitor) { try { - monitor.beginTask(null, IProgressMonitor.UNKNOWN); + monitor.beginTask(null, IProgressMonitor.UNKNOWN); ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project); folder.accept(new ICVSResourceVisitor() { @Override @@ -196,7 +196,7 @@ public class ShareProjectOperation extends CVSOperation { } @Override public void visitFolder(ICVSFolder folder) throws CVSException { - monitor.subTask(NLS.bind(CVSUIMessages.ShareProjectOperation_2, new String[] { folder.getIResource().getFullPath().toString() } )); + monitor.subTask(NLS.bind(CVSUIMessages.ShareProjectOperation_2, new String[] { folder.getIResource().getFullPath().toString() } )); if (folder.isCVSFolder()) { // for now, just unmanage folder.unmanage(null); @@ -207,7 +207,7 @@ public class ShareProjectOperation extends CVSOperation { // log the exception and return null CVSUIPlugin.log(e); } finally { - monitor.done(); - } + monitor.done(); + } } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShowAnnotationOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShowAnnotationOperation.java index 40403b4df..7e043bbe0 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShowAnnotationOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/ShowAnnotationOperation.java @@ -57,21 +57,21 @@ import com.ibm.icu.text.DateFormat; * display them in the annotations view. */ public class ShowAnnotationOperation extends CVSOperation { - - private final ICVSResource fCVSResource; - private final String fRevision; - private final boolean fBinary; + + private final ICVSResource fCVSResource; + private final String fRevision; + private final boolean fBinary; - public ShowAnnotationOperation(IWorkbenchPart part, ICVSResource cvsResource, String revision, boolean binary) { - super(part); - fCVSResource= cvsResource; - fRevision= revision; - fBinary = binary; - } + public ShowAnnotationOperation(IWorkbenchPart part, ICVSResource cvsResource, String revision, boolean binary) { + super(part); + fCVSResource= cvsResource; + fRevision= revision; + fBinary = binary; + } - @Override + @Override protected void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { - + monitor.beginTask(null, 100); // Get the annotations from the repository. @@ -100,35 +100,35 @@ public class ShowAnnotationOperation extends CVSOperation { monitor.done(); } - - /** - * Shows the history view, creating it if necessary, but does not give it focus. - * - * @param page the workbench page to operate in - * @param editor the editor that is showing the file - * @return the history view - * @throws PartInitException - */ - private IHistoryView showHistoryView(IWorkbenchPage page, AbstractDecoratedTextEditor editor) throws PartInitException { - Object object = fCVSResource.getIResource(); - if (object == null) - object = editor.getEditorInput(); + + /** + * Shows the history view, creating it if necessary, but does not give it focus. + * + * @param page the workbench page to operate in + * @param editor the editor that is showing the file + * @return the history view + * @throws PartInitException + */ + private IHistoryView showHistoryView(IWorkbenchPage page, AbstractDecoratedTextEditor editor) throws PartInitException { + Object object = fCVSResource.getIResource(); + if (object == null) + object = editor.getEditorInput(); IHistoryView historyView= TeamUI.showHistoryFor(page, object, null); - IHistoryPage historyPage = historyView.getHistoryPage(); - if (historyPage instanceof CVSHistoryPage){ - CVSHistoryPage cvsHistoryPage = (CVSHistoryPage) historyPage; - cvsHistoryPage.setMode(CVSHistoryPage.REMOTE_MODE); - // We need to call link to ensure that the history page gets linked + IHistoryPage historyPage = historyView.getHistoryPage(); + if (historyPage instanceof CVSHistoryPage){ + CVSHistoryPage cvsHistoryPage = (CVSHistoryPage) historyPage; + cvsHistoryPage.setMode(CVSHistoryPage.REMOTE_MODE); + // We need to call link to ensure that the history page gets linked // even if the page input did not change - cvsHistoryPage.linkWithEditor(); - } - return historyView; - } + cvsHistoryPage.linkWithEditor(); + } + return historyView; + } - @Override + @Override protected String getTaskName() { - return CVSUIMessages.ShowAnnotationOperation_taskName; - } + return CVSUIMessages.ShowAnnotationOperation_taskName; + } protected boolean hasCharset(ICVSResource cvsResource, InputStream contents) { try { @@ -147,45 +147,45 @@ public class ShowAnnotationOperation extends CVSOperation { if (fCVSResource instanceof ICVSRemoteResource) { return RevisionAnnotationController.openEditor(getPart().getSite().getPage(), fCVSResource, new RemoteAnnotationStorage((ICVSRemoteFile)fCVSResource, listener.getContents())); } - return null; + return null; } private void fetchAnnotation(AnnotateListener listener, ICVSResource cvsResource, String revision, IProgressMonitor monitor) throws CVSException { - - monitor = Policy.monitorFor(monitor); - monitor.beginTask(null, 100); - - final ICVSFolder folder = cvsResource.getParent(); - final FolderSyncInfo info = folder.getFolderSyncInfo(); - final ICVSRepositoryLocation location = KnownRepositories.getInstance().getRepository(info.getRoot()); - - final Session session = new Session(location, folder, true /*output to console*/); - session.open(Policy.subMonitorFor(monitor, 10), false /* read-only */); - try { - final Command.QuietOption quietness = CVSProviderPlugin.getPlugin().getQuietness(); - try { - CVSProviderPlugin.getPlugin().setQuietness(Command.VERBOSE); + + monitor = Policy.monitorFor(monitor); + monitor.beginTask(null, 100); + + final ICVSFolder folder = cvsResource.getParent(); + final FolderSyncInfo info = folder.getFolderSyncInfo(); + final ICVSRepositoryLocation location = KnownRepositories.getInstance().getRepository(info.getRoot()); + + final Session session = new Session(location, folder, true /*output to console*/); + session.open(Policy.subMonitorFor(monitor, 10), false /* read-only */); + try { + final Command.QuietOption quietness = CVSProviderPlugin.getPlugin().getQuietness(); + try { + CVSProviderPlugin.getPlugin().setQuietness(Command.VERBOSE); List<Object> localOptions = new ArrayList<>(); - if (revision != null) { - localOptions.add(Annotate.makeRevisionOption(revision)); - } - if (fBinary) { - localOptions.add(Annotate.FORCE_BINARY_ANNOTATE); - } - final IStatus status = Command.ANNOTATE.execute(session, Command.NO_GLOBAL_OPTIONS, localOptions.toArray(new LocalOption[localOptions.size()]), new ICVSResource[]{cvsResource}, listener, Policy.subMonitorFor(monitor, 90)); - if (status.getCode() == CVSStatus.SERVER_ERROR) { - throw new CVSServerException(status); - } - } finally { - CVSProviderPlugin.getPlugin().setQuietness(quietness); - monitor.done(); - } - } finally { - session.close(); - } - } + if (revision != null) { + localOptions.add(Annotate.makeRevisionOption(revision)); + } + if (fBinary) { + localOptions.add(Annotate.FORCE_BINARY_ANNOTATE); + } + final IStatus status = Command.ANNOTATE.execute(session, Command.NO_GLOBAL_OPTIONS, localOptions.toArray(new LocalOption[localOptions.size()]), new ICVSResource[]{cvsResource}, listener, Policy.subMonitorFor(monitor, 90)); + if (status.getCode() == CVSStatus.SERVER_ERROR) { + throw new CVSServerException(status); + } + } finally { + CVSProviderPlugin.getPlugin().setQuietness(quietness); + monitor.done(); + } + } finally { + session.close(); + } + } - private RevisionInformation createRevisionInformation(final AnnotateListener listener, IProgressMonitor monitor) throws CVSException { + private RevisionInformation createRevisionInformation(final AnnotateListener listener, IProgressMonitor monitor) throws CVSException { Map<String, ILogEntry> logEntriesByRevision = new HashMap<>(); if (fCVSResource instanceof ICVSFile) { try { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/SingleCommandOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/SingleCommandOperation.java index a2424a47c..31793ce78 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/SingleCommandOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/SingleCommandOperation.java @@ -42,8 +42,8 @@ public abstract class SingleCommandOperation extends RepositoryProviderOperation try { IStatus status = executeCommand(session, provider, getCVSArguments(session, resources), recurse, Policy.subMonitorFor(monitor, 90)); if (isReportableError(status)) { - throw new CVSException(status); - } + throw new CVSException(status); + } } finally { session.close(); } @@ -54,21 +54,21 @@ public abstract class SingleCommandOperation extends RepositoryProviderOperation return super.getCVSArguments(resources); } - protected ICVSResource[] getCVSArguments(Session session, IResource[] resources) { + protected ICVSResource[] getCVSArguments(Session session, IResource[] resources) { return getCVSArguments(resources); } @Override - protected void execute(CVSTeamProvider provider, ICVSTraversal entry, IProgressMonitor monitor) throws CVSException, InterruptedException { - try { - // TODO: This does not properly count the number of operations - // Changing it causes an error in the test cases - super.execute(provider, entry, monitor); - collectStatus(Status.OK_STATUS); - } catch (CVSException e) { - collectStatus(e.getStatus()); - } - } + protected void execute(CVSTeamProvider provider, ICVSTraversal entry, IProgressMonitor monitor) throws CVSException, InterruptedException { + try { + // TODO: This does not properly count the number of operations + // Changing it causes an error in the test cases + super.execute(provider, entry, monitor); + collectStatus(Status.OK_STATUS); + } catch (CVSException e) { + collectStatus(e.getStatus()); + } + } /** * Indicate whether the operation requires write access to the server (i.e. * the operation changes state on the server whether it be to commit, tag, admin, etc). @@ -80,24 +80,24 @@ public abstract class SingleCommandOperation extends RepositoryProviderOperation /** * Method overridden by subclasses to issue the command to the CVS repository using the given session. - * @param session an open session which will be closed by the caller - * @param provider the provider for the project that contains the resources - * @param resources the resources to be operated on - * @param recurse whether the operation is deep or shallow - * @param monitor a progress monitor + * @param session an open session which will be closed by the caller + * @param provider the provider for the project that contains the resources + * @param resources the resources to be operated on + * @param recurse whether the operation is deep or shallow + * @param monitor a progress monitor */ protected abstract IStatus executeCommand(Session session, CVSTeamProvider provider, ICVSResource[] resources, boolean recurse, IProgressMonitor monitor) throws CVSException, InterruptedException; @Override protected LocalOption[] getLocalOptions(boolean recurse) { - LocalOption[] result = options; - if (recurse) { - // For deep operations, we just need to make sure that the -l option isn't present - result = Command.DO_NOT_RECURSE.removeFrom(options); - } else { - result = Command.RECURSE.removeFrom(options); - result = Command.DO_NOT_RECURSE.addTo(options); - } + LocalOption[] result = options; + if (recurse) { + // For deep operations, we just need to make sure that the -l option isn't present + result = Command.DO_NOT_RECURSE.removeFrom(options); + } else { + result = Command.RECURSE.removeFrom(options); + result = Command.DO_NOT_RECURSE.addTo(options); + } return result; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagInRepositoryOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagInRepositoryOperation.java index 8ac845dbd..3efb9d265 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagInRepositoryOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagInRepositoryOperation.java @@ -104,18 +104,18 @@ public class TagInRepositoryOperation extends RemoteOperation implements ITagOpe } @Override - public TagSource getTagSource() { - return TagSource.create(getCVSResources()); - } - - @Override + public TagSource getTagSource() { + return TagSource.create(getCVSResources()); + } + + @Override protected boolean isReportableError(IStatus status) { - return super.isReportableError(status) - || status.getCode() == CVSStatus.TAG_ALREADY_EXISTS; - } + return super.isReportableError(status) + || status.getCode() == CVSStatus.TAG_ALREADY_EXISTS; + } @Override - public boolean isEmpty() { - return getCVSResources().length == 0; - } + public boolean isEmpty() { + return getCVSResources().length == 0; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagOperation.java index b9ae57e79..a525ba91e 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/TagOperation.java @@ -84,12 +84,12 @@ public class TagOperation extends RepositoryProviderOperation implements ITagOpe public IStatus tag(CVSTeamProvider provider, IResource[] resources, boolean recurse, IProgressMonitor progress) throws CVSException { LocalOption[] commandOptions = localOptions.toArray(new LocalOption[localOptions.size()]); - if (recurse) { - commandOptions = Command.DO_NOT_RECURSE.removeFrom(commandOptions); - } else { - commandOptions = Command.RECURSE.removeFrom(commandOptions); - commandOptions = Command.DO_NOT_RECURSE.addTo(commandOptions); - } + if (recurse) { + commandOptions = Command.DO_NOT_RECURSE.removeFrom(commandOptions); + } else { + commandOptions = Command.RECURSE.removeFrom(commandOptions); + commandOptions = Command.DO_NOT_RECURSE.addTo(commandOptions); + } // Build the arguments list String[] arguments = getStringArguments(resources); @@ -150,21 +150,21 @@ public class TagOperation extends RepositoryProviderOperation implements ITagOpe } } - private ICVSResource[] getCVSResources() { - IResource[] resources = getTraversalRoots(); - ICVSResource[] cvsResources = new ICVSResource[resources.length]; - for (int i = 0; i < resources.length; i++) { - cvsResources[i] = CVSWorkspaceRoot.getCVSResourceFor(resources[i]); - } - return cvsResources; - } + private ICVSResource[] getCVSResources() { + IResource[] resources = getTraversalRoots(); + ICVSResource[] cvsResources = new ICVSResource[resources.length]; + for (int i = 0; i < resources.length; i++) { + cvsResources[i] = CVSWorkspaceRoot.getCVSResourceFor(resources[i]); + } + return cvsResources; + } - @Override + @Override public TagSource getTagSource() { - return TagSource.create(getProjects()); - } + return TagSource.create(getProjects()); + } - private IProject[] getProjects() { + private IProject[] getProjects() { ResourceMapping[] mappings = getSelectedMappings(); Set<IProject> projects = new HashSet<>(); for (int i = 0; i < mappings.length; i++) { @@ -176,12 +176,12 @@ public class TagOperation extends RepositoryProviderOperation implements ITagOpe @Override protected boolean isReportableError(IStatus status) { - return super.isReportableError(status) - || status.getCode() == CVSStatus.TAG_ALREADY_EXISTS; - } + return super.isReportableError(status) + || status.getCode() == CVSStatus.TAG_ALREADY_EXISTS; + } - @Override + @Override public boolean isEmpty() { - return getSelectedMappings().length == 0; - } + return getSelectedMappings().length == 0; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/UpdateOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/UpdateOperation.java index d84d546f2..ef808f6c5 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/UpdateOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/UpdateOperation.java @@ -48,17 +48,17 @@ public class UpdateOperation extends SingleCommandOperation { this(part, asResourceMappers(resources), options, tag); } - /** - * Create an UpdateOperation that will perform on update on the given resources - * using the given local option. If a tag is provided, it will be added to the - * local options using the appropriate argument (-r or -D). If the tag is <code>null</code> - * then the tag will be omitted from the local options and the tags on the local resources - * will be used. - */ - public UpdateOperation(IWorkbenchPart part, ResourceMapping[] mappings, LocalOption[] options, CVSTag tag) { - super(part, mappings, options); - this.tag = tag; - } + /** + * Create an UpdateOperation that will perform on update on the given resources + * using the given local option. If a tag is provided, it will be added to the + * local options using the appropriate argument (-r or -D). If the tag is <code>null</code> + * then the tag will be omitted from the local options and the tags on the local resources + * will be used. + */ + public UpdateOperation(IWorkbenchPart part, ResourceMapping[] mappings, LocalOption[] options, CVSTag tag) { + super(part, mappings, options); + this.tag = tag; + } @Override protected IStatus executeCommand( @@ -84,19 +84,19 @@ public class UpdateOperation extends SingleCommandOperation { return execute; } - @Override + @Override protected LocalOption[] getLocalOptions(boolean recurse) { - // Build the local options + // Build the local options List<LocalOption> localOptions = new ArrayList<>(); - // Use the appropriate tag options - if (tag != null) { - localOptions.add(Update.makeTagOption(tag)); - } - // Build the arguments list - localOptions.addAll(Arrays.asList(super.getLocalOptions(recurse))); - LocalOption[] commandOptions = localOptions.toArray(new LocalOption[localOptions.size()]); - return commandOptions; - } + // Use the appropriate tag options + if (tag != null) { + localOptions.add(Update.makeTagOption(tag)); + } + // Build the arguments list + localOptions.addAll(Arrays.asList(super.getLocalOptions(recurse))); + LocalOption[] commandOptions = localOptions.toArray(new LocalOption[localOptions.size()]); + return commandOptions; + } protected Update getUpdateCommand() { return Command.UPDATE; @@ -121,23 +121,23 @@ public class UpdateOperation extends SingleCommandOperation { return null; } - @Override + @Override protected boolean isReportableError(IStatus status) { - return super.isReportableError(status) - || status.getCode() == CVSStatus.UNMEGERED_BINARY_CONFLICT - || status.getCode() == CVSStatus.INVALID_LOCAL_RESOURCE_PATH - || status.getCode() == CVSStatus.RESPONSE_HANDLING_FAILURE; - } + return super.isReportableError(status) + || status.getCode() == CVSStatus.UNMEGERED_BINARY_CONFLICT + || status.getCode() == CVSStatus.INVALID_LOCAL_RESOURCE_PATH + || status.getCode() == CVSStatus.RESPONSE_HANDLING_FAILURE; + } @Override protected String getErrorMessage(IStatus[] failures, int totalOperations) { return CVSUIMessages.UpdateAction_update; } - - @Override + + @Override protected ResourceMappingContext getResourceMappingContext() { - return SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); - } + return SubscriberResourceMappingContext.createContext(CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber()); + } public CVSTag getTag() { return tag; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceFileDiffOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceFileDiffOperation.java index e57e8454d..e96513200 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceFileDiffOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceFileDiffOperation.java @@ -70,7 +70,7 @@ public class WorkspaceFileDiffOperation extends FileDiffOperation { tempFile.delete(); } } - } + } } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceResourceMapper.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceResourceMapper.java index 4cacf52ec..2ba9ce323 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceResourceMapper.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/operations/WorkspaceResourceMapper.java @@ -33,49 +33,49 @@ import org.eclipse.core.runtime.IProgressMonitor; * @since 3.1 */ public final class WorkspaceResourceMapper extends ResourceMapping { - - private final IResource resource; - private final int depth; - - /** - * Convert the provided resources to one or more resource mappers - * that traverse the elements deeply. The model element of the resource - * mappers will be the workspace root. - * @param resources the resources - * @return a resource mappers that traverses the resources - */ - public static ResourceMapping[] asResourceMappers(final IResource[] resources, int depth) { + + private final IResource resource; + private final int depth; + + /** + * Convert the provided resources to one or more resource mappers + * that traverse the elements deeply. The model element of the resource + * mappers will be the workspace root. + * @param resources the resources + * @return a resource mappers that traverses the resources + */ + public static ResourceMapping[] asResourceMappers(final IResource[] resources, int depth) { List<WorkspaceResourceMapper> result = new ArrayList<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - result.add(new WorkspaceResourceMapper(resource, depth)); - } - return result.toArray(new ResourceMapping[result.size()]); - } - - public WorkspaceResourceMapper(IResource resource, int depth) { - this.resource = resource; - this.depth = depth; - } - @Override + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + result.add(new WorkspaceResourceMapper(resource, depth)); + } + return result.toArray(new ResourceMapping[result.size()]); + } + + public WorkspaceResourceMapper(IResource resource, int depth) { + this.resource = resource; + this.depth = depth; + } + @Override public Object getModelObject() { - return resource; - } - @Override + return resource; + } + @Override public IProject[] getProjects() { - return new IProject[] { resource.getProject() }; - } - @Override + return new IProject[] { resource.getProject() }; + } + @Override public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - return asTraversal(resource, depth, context); - } - private ResourceTraversal[] asTraversal(IResource resource, final int depth, ResourceMappingContext context) { - return new ResourceTraversal[] { new ResourceTraversal(new IResource[] { resource }, depth, IResource.NONE)} ; - } - @Override + return asTraversal(resource, depth, context); + } + private ResourceTraversal[] asTraversal(IResource resource, final int depth, ResourceMappingContext context) { + return new ResourceTraversal[] { new ResourceTraversal(new IResource[] { resource }, depth, IResource.NONE)} ; + } + @Override public boolean contains(ResourceMapping mapping) { - return false; - } + return false; + } @Override public String getModelProviderId() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/CVSRepositoryPropertiesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/CVSRepositoryPropertiesPage.java index ff5318b85..ff40e8262 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/CVSRepositoryPropertiesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/CVSRepositoryPropertiesPage.java @@ -170,8 +170,8 @@ public class CVSRepositoryPropertiesPage extends PropertyPage { useCustomPort.addListener(SWT.Selection, connectionInfoChangedListener); pathText.addListener(SWT.Modify, connectionInfoChangedListener); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.REPOSITORY_LOCATION_PROPERTY_PAGE); - Dialog.applyDialogFont(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.REPOSITORY_LOCATION_PROPERTY_PAGE); + Dialog.applyDialogFont(parent); return composite; } @@ -352,7 +352,7 @@ public class CVSRepositoryPropertiesPage extends PropertyPage { } final boolean[] result = new boolean[] { false }; final ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(getShell()); - progressMonitorDialog.run(false, false, new WorkspaceModifyOperation(null) { + progressMonitorDialog.run(false, false, new WorkspaceModifyOperation(null) { @Override public void execute(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { @@ -376,7 +376,7 @@ public class CVSRepositoryPropertiesPage extends PropertyPage { if (projects.size() > 0) { // To do: warn the user DetailsDialogWithProjects dialog = new DetailsDialogWithProjects( - progressMonitorDialog.getShell(), + progressMonitorDialog.getShell(), CVSUIMessages.CVSRepositoryPropertiesPage_Confirm_Project_Sharing_Changes_1, CVSUIMessages.CVSRepositoryPropertiesPage_There_are_projects_in_the_workspace_shared_with_this_repository_2, NLS.bind(CVSUIMessages.CVSRepositoryPropertiesPage_sharedProject, new String[] { location.toString() }), diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectSelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectSelectionPage.java index 57015f8e7..ce5df81d7 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectSelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectSelectionPage.java @@ -39,7 +39,7 @@ import org.eclipse.ui.model.WorkbenchLabelProvider; * refreshed. */ public class RefreshRemoteProjectSelectionPage extends CVSWizardPage { - + private ICVSRemoteResource[] rootFolders; private ListSelectionArea listArea; private WorkingSetSelectionArea workingSetArea; @@ -102,7 +102,7 @@ public class RefreshRemoteProjectSelectionPage extends CVSWizardPage { setControl(composite); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.REFRESH_REMOTE_PROJECT_SELECTION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.REFRESH_REMOTE_PROJECT_SELECTION_PAGE); listArea = new ListSelectionArea( new InputElement(), @@ -129,7 +129,7 @@ public class RefreshRemoteProjectSelectionPage extends CVSWizardPage { } }); workingSetArea.createArea(composite); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } /** diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectWizard.java index 5677462a3..b6b56db1c 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RefreshRemoteProjectWizard.java @@ -35,11 +35,11 @@ import org.eclipse.team.internal.ccvs.ui.Policy; * Wizard for refreshing the tags for a CVS repository location */ public class RefreshRemoteProjectWizard extends Wizard { - - // The initial size of this wizard. - private final static int INITIAL_WIDTH = 300; - private final static int INITIAL_HEIGHT = 350; - + + // The initial size of this wizard. + private final static int INITIAL_WIDTH = 300; + private final static int INITIAL_HEIGHT = 350; + private ICVSRepositoryLocation root; private ICVSRemoteResource[] rootFolders; private RefreshRemoteProjectSelectionPage projectSelectionPage; @@ -128,27 +128,27 @@ public class RefreshRemoteProjectWizard extends Wizard { /* * Refresh the tags of the given resources and return those for which no tags were found. */ - private ICVSRemoteResource[] internalRefresh(final RepositoryManager manager, final ICVSRemoteResource[] selectedFolders, final boolean recurse, IProgressMonitor monitor) throws InvocationTargetException { - List failedFolders = new ArrayList(); - monitor.beginTask(null, 100 * selectedFolders.length); - for (int i = 0; i < selectedFolders.length; i++) { - try { + private ICVSRemoteResource[] internalRefresh(final RepositoryManager manager, final ICVSRemoteResource[] selectedFolders, final boolean recurse, IProgressMonitor monitor) throws InvocationTargetException { + List failedFolders = new ArrayList(); + monitor.beginTask(null, 100 * selectedFolders.length); + for (int i = 0; i < selectedFolders.length; i++) { + try { ICVSRemoteResource resource = selectedFolders[i]; if (resource instanceof ICVSFolder) { CVSTag[] tags = manager.refreshDefinedTags((ICVSFolder)resource, recurse, true /* notify */, Policy.subMonitorFor(monitor, 100)); if (tags.length == 0) { - failedFolders.add(resource); + failedFolders.add(resource); } } } catch (TeamException e) { CVSUIPlugin.log(IStatus.ERROR, NLS.bind("An error occurred while fetching the tags for {0}", selectedFolders[i].getName()), e); //$NON-NLS-1$ } - } - return (ICVSRemoteResource[]) failedFolders.toArray(new ICVSRemoteResource[failedFolders.size()]); - } + } + return (ICVSRemoteResource[]) failedFolders.toArray(new ICVSRemoteResource[failedFolders.size()]); + } - private boolean promptForDeepRefresh(final ICVSRemoteResource[] folders) { - final boolean[] prompt = new boolean[] { false }; + private boolean promptForDeepRefresh(final ICVSRemoteResource[] folders) { + final boolean[] prompt = new boolean[] { false }; getShell().getDisplay().syncExec(() -> { MessageDialog dialog = new MessageDialog(getShell(), CVSUIMessages.RefreshRemoteProjectWizard_0, null, getNoTagsMessage(folders), MessageDialog.INFORMATION, new String[] { @@ -160,13 +160,13 @@ public class RefreshRemoteProjectWizard extends Wizard { } }); - return prompt[0]; - } + return prompt[0]; + } - private String getNoTagsMessage(ICVSRemoteResource[] folders) { - if (folders.length == 1) { - return NLS.bind(CVSUIMessages.RefreshRemoteProjectWizard_3, new String[] { folders[0].getRepositoryRelativePath() }); - } - return NLS.bind(CVSUIMessages.RefreshRemoteProjectWizard_4, new String[] { Integer.toString(folders.length) }); - } + private String getNoTagsMessage(ICVSRemoteResource[] folders) { + if (folders.length == 1) { + return NLS.bind(CVSUIMessages.RefreshRemoteProjectWizard_3, new String[] { folders[0].getRepositoryRelativePath() }); + } + return NLS.bind(CVSUIMessages.RefreshRemoteProjectWizard_4, new String[] { Integer.toString(folders.length) }); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RemoteViewPart.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RemoteViewPart.java index 204e49302..6bdd97b72 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RemoteViewPart.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RemoteViewPart.java @@ -96,7 +96,7 @@ public abstract class RemoteViewPart extends ViewPart implements ISelectionListe // F1 Help String helpID = getHelpContextId(); if (helpID != null) - PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), helpID); + PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), helpID); } @Override @@ -233,23 +233,23 @@ public abstract class RemoteViewPart extends ViewPart implements ISelectionListe bars.updateActionBars(); } - /** - * Returns the action group. - * - * @return the action group - */ - private WorkingSetFilterActionGroup getWorkingSetActionGroup() { - return workingSetActionGroup; - } + /** + * Returns the action group. + * + * @return the action group + */ + private WorkingSetFilterActionGroup getWorkingSetActionGroup() { + return workingSetActionGroup; + } - /** - * Sets the action group. - * - * @param actionGroup the action group - */ - private void setActionGroup(WorkingSetFilterActionGroup actionGroup) { - this.workingSetActionGroup = actionGroup; - } + /** + * Sets the action group. + * + * @param actionGroup the action group + */ + private void setActionGroup(WorkingSetFilterActionGroup actionGroup) { + this.workingSetActionGroup = actionGroup; + } /** * Add the menu actions that were contributed in plugin.xml @@ -286,9 +286,9 @@ public abstract class RemoteViewPart extends ViewPart implements ISelectionListe ((RemoteContentProvider)viewer.getContentProvider()).cancelJobs(CVSUIPlugin.getPlugin().getRepositoryManager().getKnownRepositoryRoots()); ((RemoteContentProvider)viewer.getContentProvider()).purgeCache(); CVSUIPlugin.getPlugin().getRepositoryManager().purgeCache(); - viewer.getControl().setRedraw(false); + viewer.getControl().setRedraw(false); viewer.refresh(); - viewer.getControl().setRedraw(true); + viewer.getControl().setRedraw(true); } public void collapseAll() { @@ -334,9 +334,9 @@ public abstract class RemoteViewPart extends ViewPart implements ISelectionListe @Override public void dispose() { getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this); - if (getWorkingSetActionGroup() != null) { - getWorkingSetActionGroup().dispose(); - } + if (getWorkingSetActionGroup() != null) { + getWorkingSetActionGroup().dispose(); + } super.dispose(); viewer = null; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesView.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesView.java index ac21a7266..6b0ad1e5c 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesView.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesView.java @@ -88,57 +88,57 @@ public class RepositoriesView extends RemoteViewPart { display.asyncExec(() -> RepositoriesView.this.refreshViewer()); } }; - - private static final class RepositoryDragSourceListener implements DragSourceListener { - private IStructuredSelection selection; + + private static final class RepositoryDragSourceListener implements DragSourceListener { + private IStructuredSelection selection; - @Override + @Override public void dragStart(DragSourceEvent event) { - if(selection!=null) { - final Object[] array = selection.toArray(); - // event.doit = Utils.getResources(array).length > 0; - for (int i = 0; i < array.length; i++) { - if (array[i] instanceof ICVSRemoteFile) { - event.doit = true; - return; - } - } - event.doit = false; - } - } + if(selection!=null) { + final Object[] array = selection.toArray(); + // event.doit = Utils.getResources(array).length > 0; + for (int i = 0; i < array.length; i++) { + if (array[i] instanceof ICVSRemoteFile) { + event.doit = true; + return; + } + } + event.doit = false; + } + } - @Override + @Override public void dragSetData(DragSourceEvent event) { - if (selection!=null && CVSResourceTransfer.getInstance().isSupportedType(event.dataType)) { - final Object[] array = selection.toArray(); - for (int i = 0; i < array.length; i++) { - if (array[i] instanceof ICVSRemoteFile) { - event.data = array[i]; - return; - } - } - } else if (PluginTransfer.getInstance().isSupportedType(event.dataType)) { - final Object[] array = selection.toArray(); - for (int i = 0; i < array.length; i++) { - if (array[i] instanceof ICVSRemoteFile) { - event.data = new PluginTransferData("org.eclipse.team.cvs.ui.cvsRemoteDrop", CVSResourceTransfer.getInstance().toByteArray((ICVSRemoteFile) array[i])); //$NON-NLS-1$ - return; - } - } - - } - } - - @Override + if (selection!=null && CVSResourceTransfer.getInstance().isSupportedType(event.dataType)) { + final Object[] array = selection.toArray(); + for (int i = 0; i < array.length; i++) { + if (array[i] instanceof ICVSRemoteFile) { + event.data = array[i]; + return; + } + } + } else if (PluginTransfer.getInstance().isSupportedType(event.dataType)) { + final Object[] array = selection.toArray(); + for (int i = 0; i < array.length; i++) { + if (array[i] instanceof ICVSRemoteFile) { + event.data = new PluginTransferData("org.eclipse.team.cvs.ui.cvsRemoteDrop", CVSResourceTransfer.getInstance().toByteArray((ICVSRemoteFile) array[i])); //$NON-NLS-1$ + return; + } + } + + } + } + + @Override public void dragFinished( DragSourceEvent event) { - } + } - public void updateSelection( IStructuredSelection selection) { - this.selection = selection; - } - } - - RepositoryDragSourceListener repositoryDragSourceListener; + public void updateSelection( IStructuredSelection selection) { + this.selection = selection; + } + } + + RepositoryDragSourceListener repositoryDragSourceListener; /** * Constructor for RepositoriesView. @@ -190,7 +190,7 @@ public class RepositoriesView extends RemoteViewPart { dialog.open(); } }; - PlatformUI.getWorkbench().getHelpSystem().setHelp(newAction, IHelpContextIds.NEW_REPOSITORY_LOCATION_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newAction, IHelpContextIds.NEW_REPOSITORY_LOCATION_ACTION); if (includeAnonConnection()) { newAnonAction = new Action(CVSUIMessages.RepositoriesView_newAnonCVS, CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_NEWLOCATION)) { @@ -207,7 +207,7 @@ public class RepositoriesView extends RemoteViewPart { dialog.open(); } }; - PlatformUI.getWorkbench().getHelpSystem().setHelp(newAnonAction, IHelpContextIds.NEW_DEV_ECLIPSE_REPOSITORY_LOCATION_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newAnonAction, IHelpContextIds.NEW_DEV_ECLIPSE_REPOSITORY_LOCATION_ACTION); } // Properties @@ -239,22 +239,22 @@ public class RepositoriesView extends RemoteViewPart { } } }; - PlatformUI.getWorkbench().getHelpSystem().setHelp(removeRootAction, IHelpContextIds.REMOVE_REPOSITORY_LOCATION_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(removeRootAction, IHelpContextIds.REMOVE_REPOSITORY_LOCATION_ACTION); IActionBars bars = getViewSite().getActionBars(); bars.setGlobalActionHandler(ActionFactory.DELETE.getId(), removeAction); // Sort By action group IPropertyChangeListener comparatorUpdater = event -> { - String property = event.getProperty(); - if (RepositoriesSortingActionGroup.CHANGE_COMPARATOR - .equals(property)) { - Object newValue = event.getNewValue(); - getViewer().refresh(); - saveSelectedComparator((RepositoryComparator) newValue); - } + String property = event.getProperty(); + if (RepositoriesSortingActionGroup.CHANGE_COMPARATOR + .equals(property)) { + Object newValue = event.getNewValue(); + getViewer().refresh(); + saveSelectedComparator((RepositoryComparator) newValue); + } }; - setActionGroup(new RepositoriesSortingActionGroup(shell, - comparatorUpdater)); + setActionGroup(new RepositoriesSortingActionGroup(shell, + comparatorUpdater)); // restore comparator selection getRepositoriesSortingActionGroup().setSelectedComparator( savedComparator); @@ -296,23 +296,23 @@ public class RepositoriesView extends RemoteViewPart { } } - /** - * Returns the action group. - * - * @return the action group - */ - private RepositoriesSortingActionGroup getRepositoriesSortingActionGroup() { - return repositoriesSortingActionGroup; - } + /** + * Returns the action group. + * + * @return the action group + */ + private RepositoriesSortingActionGroup getRepositoriesSortingActionGroup() { + return repositoriesSortingActionGroup; + } - /** - * Sets the action group. - * - * @param actionGroup the action group - */ - private void setActionGroup(RepositoriesSortingActionGroup actionGroup) { - this.repositoriesSortingActionGroup = actionGroup; - } + /** + * Sets the action group. + * + * @param actionGroup the action group + */ + private void setActionGroup(RepositoriesSortingActionGroup actionGroup) { + this.repositoriesSortingActionGroup = actionGroup; + } /** * Method includeEclipseConnection. @@ -367,9 +367,9 @@ public class RepositoriesView extends RemoteViewPart { else dialogSettings.put(FILTER_SHOW_MODULES, (String) null); CVSUIPlugin.getPlugin().getRepositoryManager().removeRepositoryListener(listener); - if (getRepositoriesSortingActionGroup() != null) { - getRepositoriesSortingActionGroup().dispose(); - } + if (getRepositoriesSortingActionGroup() != null) { + getRepositoriesSortingActionGroup().dispose(); + } super.dispose(); } @@ -389,11 +389,11 @@ public class RepositoriesView extends RemoteViewPart { IStructuredSelection selection = (IStructuredSelection)event.getSelection(); handleChange(selection); }); - - repositoryDragSourceListener = new RepositoryDragSourceListener(); - viewer.addDragSupport( DND.DROP_LINK | DND.DROP_DEFAULT, - new Transfer[] { CVSResourceTransfer.getInstance(),PluginTransfer.getInstance()}, - repositoryDragSourceListener); + + repositoryDragSourceListener = new RepositoryDragSourceListener(); + viewer.addDragSupport( DND.DROP_LINK | DND.DROP_DEFAULT, + new Transfer[] { CVSResourceTransfer.getInstance(),PluginTransfer.getInstance()}, + repositoryDragSourceListener); } @Override @@ -414,7 +414,7 @@ public class RepositoriesView extends RemoteViewPart { IStructuredSelection s = (IStructuredSelection)selection; if (s.size() > 1) - return NLS.bind(CVSUIMessages.RepositoriesView_NItemsSelected, new String[] { String.valueOf(s.size()) }); + return NLS.bind(CVSUIMessages.RepositoriesView_NItemsSelected, new String[] { String.valueOf(s.size()) }); Object element = TeamAction.getAdapter(s.getFirstElement(), ICVSResource.class); if (element instanceof ICVSRemoteResource) { ICVSRemoteResource res = (ICVSRemoteResource)element; @@ -464,8 +464,8 @@ public class RepositoriesView extends RemoteViewPart { removeRootAction.updateSelection(selection); removeDateTagAction.updateSelection(selection); removeAction.setEnabled(removeRootAction.isEnabled() || removeDateTagAction.isEnabled()); - - repositoryDragSourceListener.updateSelection(selection); + + repositoryDragSourceListener.updateSelection(selection); } public void showFilter(RepositoriesFilter filter) { @@ -475,5 +475,5 @@ public class RepositoriesView extends RemoteViewPart { getViewer().addFilter(filter); toggleFilterAction.setEnabled(true); } - + } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesViewContentHandler.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesViewContentHandler.java index 063302a89..145c0539c 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesViewContentHandler.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoriesViewContentHandler.java @@ -60,7 +60,7 @@ public class RepositoriesViewContentHandler extends DefaultHandler { private List autoRefreshFiles; private boolean ignoreElements; - private long lastAccessTime; + private long lastAccessTime; public RepositoriesViewContentHandler(RepositoryManager manager) { this.manager = manager; @@ -97,7 +97,7 @@ public class RepositoriesViewContentHandler extends DefaultHandler { currentRepositoryRoot.addTags(currentRemotePath, (CVSTag[]) tags.toArray(new CVSTag[tags.size()])); if (lastAccessTime > 0) - currentRepositoryRoot.setLastAccessedTime(currentRemotePath, lastAccessTime); + currentRepositoryRoot.setLastAccessedTime(currentRemotePath, lastAccessTime); currentRepositoryRoot.setAutoRefreshFiles(currentRemotePath, (String[]) autoRefreshFiles.toArray(new String[autoRefreshFiles.size()])); } @@ -171,12 +171,12 @@ public class RepositoriesViewContentHandler extends DefaultHandler { long cachedTime = 0; String cachedTimeString = atts.getValue(LAST_ACCESS_TIME_ATTRIBUTE); if (cachedTimeString != null) { - try { - Long time = Long.valueOf(cachedTimeString); - cachedTime = time.longValue(); - } catch (NumberFormatException e) { - // Ignore - } + try { + Long time = Long.valueOf(cachedTimeString); + cachedTime = time.longValue(); + } catch (NumberFormatException e) { + // Ignore + } } startModule(path, cachedTime); } else if (elementName.equals(TAG_TAG)) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryEncodingPropertyPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryEncodingPropertyPage.java index 8abe42e71..b573eedd8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryEncodingPropertyPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryEncodingPropertyPage.java @@ -300,7 +300,7 @@ public class RepositoryEncodingPropertyPage extends PropertyPage implements IPro pageLink.setLayoutData(label.getLayoutData()); pageLink.setText(CVSUIMessages.RepositoryEncodingPropertyPage_4); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.REPOSITORY_ENCODING_PROPERTY_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.REPOSITORY_ENCODING_PROPERTY_PAGE); Dialog.applyDialogFont(parent); return composite; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryManager.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryManager.java index 29814778a..d37c958be 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryManager.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryManager.java @@ -55,10 +55,10 @@ public class RepositoryManager { // new state file private static final String REPOSITORIES_VIEW_FILE = "repositoriesView.xml"; //$NON-NLS-1$ private static final String COMMENT_HIST_FILE = "commitCommentHistory.xml"; //$NON-NLS-1$ - private static final String COMMENT_TEMPLATES_FILE = "commentTemplates.xml"; //$NON-NLS-1$ + private static final String COMMENT_TEMPLATES_FILE = "commentTemplates.xml"; //$NON-NLS-1$ static final String ELEMENT_COMMIT_COMMENT = "CommitComment"; //$NON-NLS-1$ static final String ELEMENT_COMMIT_HISTORY = "CommitComments"; //$NON-NLS-1$ - static final String ELEMENT_COMMENT_TEMPLATES = "CommitCommentTemplates"; //$NON-NLS-1$ + static final String ELEMENT_COMMENT_TEMPLATES = "CommitCommentTemplates"; //$NON-NLS-1$ private Map<String, RepositoryRoot> repositoryRoots = new HashMap<>(); @@ -66,7 +66,7 @@ public class RepositoryManager { // The previously remembered comment static String[] previousComments = new String[0]; - static String[] commentTemplates = new String[0]; + static String[] commentTemplates = new String[0]; public static boolean notifyRepoView = true; @@ -375,7 +375,7 @@ public class RepositoryManager { public void startup() { loadState(); loadCommentHistory(); - loadCommentTemplates(); + loadCommentTemplates(); CVSProviderPlugin.getPlugin().addRepositoryListener(new ICVSListener() { @Override public void repositoryAdded(ICVSRepositoryLocation root) { @@ -406,7 +406,7 @@ public class RepositoryManager { public void shutdown() throws TeamException { saveState(); saveCommentHistory(); - saveCommentTemplates(); + saveCommentTemplates(); } private void loadState() { @@ -463,23 +463,23 @@ public class RepositoryManager { CVSUIPlugin.log(e); } } - private void loadCommentTemplates() { - IPath pluginStateLocation = CVSUIPlugin.getPlugin().getStateLocation().append(COMMENT_TEMPLATES_FILE); - File file = pluginStateLocation.toFile(); - if (!file.exists()) return; - try { - BufferedInputStream is = new BufferedInputStream(new FileInputStream(file)); - try { - readCommentTemplates(is); - } finally { - is.close(); - } - } catch (IOException e) { - CVSUIPlugin.log(IStatus.ERROR, CVSUIMessages.RepositoryManager_ioException, e); - } catch (TeamException e) { - CVSUIPlugin.log(e); - } - } + private void loadCommentTemplates() { + IPath pluginStateLocation = CVSUIPlugin.getPlugin().getStateLocation().append(COMMENT_TEMPLATES_FILE); + File file = pluginStateLocation.toFile(); + if (!file.exists()) return; + try { + BufferedInputStream is = new BufferedInputStream(new FileInputStream(file)); + try { + readCommentTemplates(is); + } finally { + is.close(); + } + } catch (IOException e) { + CVSUIPlugin.log(IStatus.ERROR, CVSUIMessages.RepositoryManager_ioException, e); + } catch (TeamException e) { + CVSUIPlugin.log(e); + } + } protected void saveState() throws TeamException { IPath pluginStateLocation = CVSUIPlugin.getPlugin().getStateLocation(); @@ -608,22 +608,22 @@ public class RepositoryManager { File tempFile = pluginStateLocation.append(COMMENT_HIST_FILE + ".tmp").toFile(); //$NON-NLS-1$ File histFile = pluginStateLocation.append(COMMENT_HIST_FILE).toFile(); try { - XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(tempFile))); - try { - writeCommentHistory(writer); - } finally { - writer.close(); - } - if (histFile.exists()) { - histFile.delete(); - } - boolean renamed = tempFile.renameTo(histFile); - if (!renamed) { - throw new TeamException(new Status(IStatus.ERROR, CVSUIPlugin.ID, TeamException.UNABLE, NLS.bind(CVSUIMessages.RepositoryManager_rename, new String[] { tempFile.getAbsolutePath() }), null)); - } - } catch (IOException e) { - throw new TeamException(new Status(IStatus.ERROR, CVSUIPlugin.ID, TeamException.UNABLE, NLS.bind(CVSUIMessages.RepositoryManager_save, new String[] { histFile.getAbsolutePath() }), e)); - } + XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(tempFile))); + try { + writeCommentHistory(writer); + } finally { + writer.close(); + } + if (histFile.exists()) { + histFile.delete(); + } + boolean renamed = tempFile.renameTo(histFile); + if (!renamed) { + throw new TeamException(new Status(IStatus.ERROR, CVSUIPlugin.ID, TeamException.UNABLE, NLS.bind(CVSUIMessages.RepositoryManager_rename, new String[] { tempFile.getAbsolutePath() }), null)); + } + } catch (IOException e) { + throw new TeamException(new Status(IStatus.ERROR, CVSUIPlugin.ID, TeamException.UNABLE, NLS.bind(CVSUIMessages.RepositoryManager_save, new String[] { histFile.getAbsolutePath() }), e)); + } } private void writeCommentHistory(XMLWriter writer) { writer.startTag(ELEMENT_COMMIT_HISTORY, null, false); @@ -631,7 +631,7 @@ public class RepositoryManager { writer.printSimpleTag(ELEMENT_COMMIT_COMMENT, previousComments[i]); writer.endTag(ELEMENT_COMMIT_HISTORY); } - + public void addRepositoryListener(IRepositoryListener listener) { listeners.add(listener); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryRoot.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryRoot.java index e1e4bc53d..fb73fefcc 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryRoot.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/repo/RepositoryRoot.java @@ -74,14 +74,14 @@ public class RepositoryRoot extends PlatformObject { return getTags().isEmpty() && children.isEmpty(); } - public boolean isExpired() { - long currentTime = System.currentTimeMillis(); - long ms = currentTime - lastAccessTime; - int seconds = (int)ms / 1000; - int hours = seconds / 60 / 60; - int days = hours / 24; - return days > CACHE_LIFESPAN_IN_DAYS; - } + public boolean isExpired() { + long currentTime = System.currentTimeMillis(); + long ms = currentTime - lastAccessTime; + int seconds = (int)ms / 1000; + int hours = seconds / 60 / 60; + int days = hours / 24; + return days > CACHE_LIFESPAN_IN_DAYS; + } private void accessed() { lastAccessTime = System.currentTimeMillis(); @@ -421,50 +421,50 @@ public class RepositoryRoot extends PlatformObject { } } - private CVSTag[] fetchTagsUsingLog(ICVSFolder folder, IProgressMonitor monitor) throws CVSException { - LogEntryCache logEntries = new LogEntryCache(); - RemoteLogOperation operation = new RemoteLogOperation(null, new ICVSRemoteResource[] { asRemoteResource(folder) }, null, null, logEntries) { - @Override + private CVSTag[] fetchTagsUsingLog(ICVSFolder folder, IProgressMonitor monitor) throws CVSException { + LogEntryCache logEntries = new LogEntryCache(); + RemoteLogOperation operation = new RemoteLogOperation(null, new ICVSRemoteResource[] { asRemoteResource(folder) }, null, null, logEntries) { + @Override protected Command.LocalOption[] getLocalOptions(CVSTag tag1,CVSTag tag2) { - Command.LocalOption[] options = new Command.LocalOption[] {}; - Command.LocalOption[] newOptions = new Command.LocalOption[options.length + 1]; - System.arraycopy(options, 0, newOptions, 0, options.length); - newOptions[options.length] = Command.DO_NOT_RECURSE; - return newOptions; - } - }; - try { - operation.run(monitor); - } catch (InvocationTargetException e) { - throw CVSException.wrapException(e); - } catch (InterruptedException e) { - // Ignore; - } - String[] keys = logEntries.getCachedFilePaths(); + Command.LocalOption[] options = new Command.LocalOption[] {}; + Command.LocalOption[] newOptions = new Command.LocalOption[options.length + 1]; + System.arraycopy(options, 0, newOptions, 0, options.length); + newOptions[options.length] = Command.DO_NOT_RECURSE; + return newOptions; + } + }; + try { + operation.run(monitor); + } catch (InvocationTargetException e) { + throw CVSException.wrapException(e); + } catch (InterruptedException e) { + // Ignore; + } + String[] keys = logEntries.getCachedFilePaths(); Set<CVSTag> tags = new HashSet<>(); - for (int i = 0; i < keys.length; i++) { - String key = keys[i]; - ILogEntry[] entries = logEntries.getLogEntries(key); - for (int j = 0; j < entries.length; j++) { - ILogEntry entry = entries[j]; - tags.addAll(Arrays.asList(entry.getTags())); - } - } - return tags.toArray(new CVSTag[tags.size()]); - } - - private ICVSRemoteResource asRemoteResource(ICVSFolder folder) throws CVSException { - if (folder instanceof ICVSRemoteResource) { - return (ICVSRemoteResource)folder; - } - return CVSWorkspaceRoot.getRemoteResourceFor(folder); - } - - /** + for (int i = 0; i < keys.length; i++) { + String key = keys[i]; + ILogEntry[] entries = logEntries.getLogEntries(key); + for (int j = 0; j < entries.length; j++) { + ILogEntry entry = entries[j]; + tags.addAll(Arrays.asList(entry.getTags())); + } + } + return tags.toArray(new CVSTag[tags.size()]); + } + + private ICVSRemoteResource asRemoteResource(ICVSFolder folder) throws CVSException { + if (folder instanceof ICVSRemoteResource) { + return (ICVSRemoteResource)folder; + } + return CVSWorkspaceRoot.getRemoteResourceFor(folder); + } + + /** * Fetches tags from auto-refresh files. */ private CVSTag[] fetchTagsUsingAutoRefreshFiles(ICVSFolder folder, IProgressMonitor monitor) throws TeamException { - String remotePath = getRemotePathFor(folder); + String remotePath = getRemotePathFor(folder); String[] filesToRefresh = getAutoRefreshFiles(remotePath); try { monitor.beginTask(null, filesToRefresh.length * 10); @@ -472,21 +472,21 @@ public class RepositoryRoot extends PlatformObject { for (int i = 0; i < filesToRefresh.length; i++) { ICVSRemoteFile file = root.getRemoteFile(filesToRefresh[i], CVSTag.DEFAULT); try { - tags.addAll(Arrays.asList(fetchTags(file, Policy.subMonitorFor(monitor, 5)))); - } catch (TeamException e) { - IStatus status = e.getStatus(); - boolean doesNotExist = false; - if (status.getCode() == CVSStatus.SERVER_ERROR && status.isMultiStatus()) { - IStatus[] children = status.getChildren(); - if (children.length == 1 && children[0].getCode() == CVSStatus.DOES_NOT_EXIST) { - // Don't throw an exception if the file does no exist - doesNotExist = true; - } - } - if (!doesNotExist) { - throw e; - } - } + tags.addAll(Arrays.asList(fetchTags(file, Policy.subMonitorFor(monitor, 5)))); + } catch (TeamException e) { + IStatus status = e.getStatus(); + boolean doesNotExist = false; + if (status.getCode() == CVSStatus.SERVER_ERROR && status.isMultiStatus()) { + IStatus[] children = status.getChildren(); + if (children.length == 1 && children[0].getCode() == CVSStatus.DOES_NOT_EXIST) { + // Don't throw an exception if the file does no exist + doesNotExist = true; + } + } + if (!doesNotExist) { + throw e; + } + } } return tags.toArray(new CVSTag[tags.size()]); } finally { @@ -634,7 +634,7 @@ public class RepositoryRoot extends PlatformObject { TagCacheEntry entry = getTagCacheEntryFor(path, false); boolean writeOutTags = entry != null && !entry.isExpired(); if (writeOutTags) - attributes.put(RepositoriesViewContentHandler.LAST_ACCESS_TIME_ATTRIBUTE, Long.toString(entry.lastAccessTime)); + attributes.put(RepositoriesViewContentHandler.LAST_ACCESS_TIME_ATTRIBUTE, Long.toString(entry.lastAccessTime)); writer.startTag(RepositoriesViewContentHandler.MODULE_TAG, attributes, true); if (writeOutTags) { Iterator tagIt = entry.getTags().iterator(); @@ -658,7 +658,7 @@ public class RepositoryRoot extends PlatformObject { writer.endTag(RepositoriesViewContentHandler.REPOSITORY_TAG); } - private void writeATag(XMLWriter writer, HashMap attributes, CVSTag tag, String s) { + private void writeATag(XMLWriter writer, HashMap attributes, CVSTag tag, String s) { attributes.clear(); attributes.put(RepositoriesViewContentHandler.NAME_ATTRIBUTE, tag.getName()); attributes.put(RepositoriesViewContentHandler.TYPE_ATTRIBUTE, RepositoriesViewContentHandler.TAG_TYPES[tag.getType()]); @@ -788,15 +788,15 @@ public class RepositoryRoot extends PlatformObject { this.root = root; } - /* - * Set the last access time of the cache entry for the given path - * as it was read from the persistent store. - */ - /* package */ void setLastAccessedTime(String remotePath, long lastAccessTime) { + /* + * Set the last access time of the cache entry for the given path + * as it was read from the persistent store. + */ + /* package */ void setLastAccessedTime(String remotePath, long lastAccessTime) { TagCacheEntry entry = getTagCacheEntryFor(remotePath, false); if(entry != null){ - entry.lastAccessTime = lastAccessTime; + entry.lastAccessTime = lastAccessTime; } - } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetActionGroup.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetActionGroup.java index d8ed0894d..f20fa53e8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetActionGroup.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetActionGroup.java @@ -22,8 +22,8 @@ import org.eclipse.team.ui.synchronize.*; */ public class CVSChangeSetActionGroup extends SynchronizePageActionGroup { - private OpenChangeSetAction openCommitSet; - + private OpenChangeSetAction openCommitSet; + @Override public void initialize(ISynchronizePageConfiguration configuration) { super.initialize(configuration); @@ -31,15 +31,15 @@ public class CVSChangeSetActionGroup extends SynchronizePageActionGroup { } @Override - public void fillContextMenu(IMenuManager menu) { - ISynchronizeParticipant participant = getConfiguration().getParticipant(); - if (participant instanceof IChangeSetProvider) { - if (((IChangeSetProvider)participant).getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { - appendToGroup( - menu, - ISynchronizePageConfiguration.FILE_GROUP, - openCommitSet); - } - } - } + public void fillContextMenu(IMenuManager menu) { + ISynchronizeParticipant participant = getConfiguration().getParticipant(); + if (participant instanceof IChangeSetProvider) { + if (((IChangeSetProvider)participant).getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { + appendToGroup( + menu, + ISynchronizePageConfiguration.FILE_GROUP, + openCommitSet); + } + } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCapability.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCapability.java index c115f6a5c..de3018981 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCapability.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCapability.java @@ -24,27 +24,27 @@ import org.eclipse.team.ui.synchronize.SynchronizePageActionGroup; public class CVSChangeSetCapability extends ChangeSetCapability { @Override - public boolean supportsCheckedInChangeSets() { - return true; - } + public boolean supportsCheckedInChangeSets() { + return true; + } @Override - public boolean supportsActiveChangeSets() { - return getActiveChangeSetManager() != null; - } + public boolean supportsActiveChangeSets() { + return getActiveChangeSetManager() != null; + } @Override - public SyncInfoSetChangeSetCollector createSyncInfoSetChangeSetCollector(ISynchronizePageConfiguration configuration) { - return new CVSChangeSetCollector(configuration); - } - + public SyncInfoSetChangeSetCollector createSyncInfoSetChangeSetCollector(ISynchronizePageConfiguration configuration) { + return new CVSChangeSetCollector(configuration); + } + @Override - public SynchronizePageActionGroup getActionGroup() { - return new CVSChangeSetActionGroup(); - } - + public SynchronizePageActionGroup getActionGroup() { + return new CVSChangeSetActionGroup(); + } + @Override - public boolean enableChangeSetsByDefault() { - return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_COMMIT_SET_DEFAULT_ENABLEMENT); - } + public boolean enableChangeSetsByDefault() { + return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_COMMIT_SET_DEFAULT_ENABLEMENT); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCollector.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCollector.java index b2a1537c6..a4234e41a 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCollector.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSChangeSetCollector.java @@ -46,24 +46,24 @@ import com.ibm.icu.text.DateFormat; */ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector implements LogEntryCacheUpdateHandler.ILogsFetchedListener { - /* - * Constant used to add the collector to the configuration of a page so - * it can be accessed by the CVS custom actions - */ - public static final String CVS_CHECKED_IN_COLLECTOR = CVSUIPlugin.ID + ".CVSCheckedInCollector"; //$NON-NLS-1$ - - /* - * Constant used to store the log entry handler in the configuration so it can - * be kept around over layout changes - */ - private static final String LOG_ENTRY_HANDLER = CVSUIPlugin.ID + ".LogEntryHandler"; //$NON-NLS-1$ - - private static final String DEFAULT_INCOMING_SET_NAME = CVSUIMessages.CVSChangeSetCollector_0; - - boolean disposed = false; + /* + * Constant used to add the collector to the configuration of a page so + * it can be accessed by the CVS custom actions + */ + public static final String CVS_CHECKED_IN_COLLECTOR = CVSUIPlugin.ID + ".CVSCheckedInCollector"; //$NON-NLS-1$ + + /* + * Constant used to store the log entry handler in the configuration so it can + * be kept around over layout changes + */ + private static final String LOG_ENTRY_HANDLER = CVSUIPlugin.ID + ".LogEntryHandler"; //$NON-NLS-1$ + + private static final String DEFAULT_INCOMING_SET_NAME = CVSUIMessages.CVSChangeSetCollector_0; + + boolean disposed = false; - private LogEntryCache logEntryCache; - + private LogEntryCache logEntryCache; + /* ***************************************************************************** * Special sync info that has its kind already calculated. */ @@ -82,125 +82,125 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme private class DefaultCheckedInChangeSet extends CheckedInChangeSet { - private Date date = new Date(); - - public DefaultCheckedInChangeSet(String name) { - setName(name); - } - @Override + private Date date = new Date(); + + public DefaultCheckedInChangeSet(String name) { + setName(name); + } + @Override public String getAuthor() { - return ""; //$NON-NLS-1$ - } + return ""; //$NON-NLS-1$ + } - @Override + @Override public Date getDate() { - return date; - } + return date; + } - @Override + @Override public String getComment() { - return ""; //$NON-NLS-1$ - } - + return ""; //$NON-NLS-1$ + } + } private class CVSCheckedInChangeSet extends CheckedInChangeSet { - private final ILogEntry entry; + private final ILogEntry entry; - public CVSCheckedInChangeSet(ILogEntry entry) { - this.entry = entry; - Date date = entry.getDate(); - String comment = Util.flattenText(entry.getComment()); - if (date == null) { - setName("["+entry.getAuthor()+ "] " + comment); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - String dateString = DateFormat.getDateTimeInstance().format(date); - setName("["+entry.getAuthor()+ "] (" + dateString +") " + comment); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - @Override + public CVSCheckedInChangeSet(ILogEntry entry) { + this.entry = entry; + Date date = entry.getDate(); + String comment = Util.flattenText(entry.getComment()); + if (date == null) { + setName("["+entry.getAuthor()+ "] " + comment); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + String dateString = DateFormat.getDateTimeInstance().format(date); + setName("["+entry.getAuthor()+ "] (" + dateString +") " + comment); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + + @Override public String getAuthor() { - return entry.getAuthor(); - } + return entry.getAuthor(); + } - @Override + @Override public Date getDate() { - return entry.getDate(); - } + return entry.getDate(); + } - @Override + @Override public String getComment() { - return entry.getComment(); - } + return entry.getComment(); + } } - public CVSChangeSetCollector(ISynchronizePageConfiguration configuration) { - super(configuration); - configuration.setProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR, this); - } + public CVSChangeSetCollector(ISynchronizePageConfiguration configuration) { + super(configuration); + configuration.setProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR, this); + } - public synchronized LogEntryCacheUpdateHandler getLogEntryHandler() { - LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)getConfiguration().getProperty(LOG_ENTRY_HANDLER); - if (handler == null) { - handler = initializeLogEntryHandler(getConfiguration()); - } - handler.setListener(this); - return handler; - } - - /* - * Initialize the log entry handler and place it in the configuration - */ - private LogEntryCacheUpdateHandler initializeLogEntryHandler(final ISynchronizePageConfiguration configuration) { - final LogEntryCacheUpdateHandler logEntryHandler = new LogEntryCacheUpdateHandler(configuration); - configuration.setProperty(LOG_ENTRY_HANDLER, logEntryHandler); - // Use an action group to get notified when the configuration is disposed - configuration.addActionContribution(new SynchronizePageActionGroup() { - @Override + public synchronized LogEntryCacheUpdateHandler getLogEntryHandler() { + LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)getConfiguration().getProperty(LOG_ENTRY_HANDLER); + if (handler == null) { + handler = initializeLogEntryHandler(getConfiguration()); + } + handler.setListener(this); + return handler; + } + + /* + * Initialize the log entry handler and place it in the configuration + */ + private LogEntryCacheUpdateHandler initializeLogEntryHandler(final ISynchronizePageConfiguration configuration) { + final LogEntryCacheUpdateHandler logEntryHandler = new LogEntryCacheUpdateHandler(configuration); + configuration.setProperty(LOG_ENTRY_HANDLER, logEntryHandler); + // Use an action group to get notified when the configuration is disposed + configuration.addActionContribution(new SynchronizePageActionGroup() { + @Override public void dispose() { - super.dispose(); - LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)configuration.getProperty(LOG_ENTRY_HANDLER); - if (handler != null) { - handler.shutdown(); - configuration.setProperty(LOG_ENTRY_HANDLER, null); - } - } - }); - // It is possible that the configuration has been disposed concurrently by another thread - // TODO - return logEntryHandler; - } + super.dispose(); + LogEntryCacheUpdateHandler handler = (LogEntryCacheUpdateHandler)configuration.getProperty(LOG_ENTRY_HANDLER); + if (handler != null) { + handler.shutdown(); + configuration.setProperty(LOG_ENTRY_HANDLER, null); + } + } + }); + // It is possible that the configuration has been disposed concurrently by another thread + // TODO + return logEntryHandler; + } - @Override + @Override protected void add(SyncInfo[] infos) { - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) - try { - handler.fetch(infos); - } catch (CVSException e) { - getConfiguration().getSyncInfoSet().addError(new TeamStatus(IStatus.ERROR, CVSUIPlugin.ID, 0, e.getMessage(), e, null)); - } - } + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) + try { + handler.fetch(infos); + } catch (CVSException e) { + getConfiguration().getSyncInfoSet().addError(new TeamStatus(IStatus.ERROR, CVSUIPlugin.ID, 0, e.getMessage(), e, null)); + } + } - @Override + @Override public void reset(SyncInfoSet seedSet) { - // Notify that handler to stop any fetches in progress - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) { - handler.stopFetching(); - } - super.reset(seedSet); - } + // Notify that handler to stop any fetches in progress + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) { + handler.stopFetching(); + } + super.reset(seedSet); + } @Override public void dispose() { - // No longer listen for log entry changes - // (The handler is disposed with the page) - disposed = true; - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) handler.setListener(null); + // No longer listen for log entry changes + // (The handler is disposed with the page) + disposed = true; + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) handler.setListener(null); getConfiguration().setProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR, null); logEntryCache = null; super.dispose(); @@ -209,12 +209,12 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme /** * Fetch the log histories for the remote changes and use this information * to add each resource to an appropriate commit set. - */ - private void handleRemoteChanges(final SyncInfo[] infos, final LogEntryCache logEntries, final IProgressMonitor monitor) { + */ + private void handleRemoteChanges(final SyncInfo[] infos, final LogEntryCache logEntries, final IProgressMonitor monitor) { performUpdate(monitor1 -> addLogEntries(infos, logEntries, monitor1), true /* preserver expansion */, monitor); - } + } - /* + /* * Add the following sync info elements to the viewer. It is assumed that these elements have associated * log entries cached in the log operation. */ @@ -239,15 +239,15 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme * @param log the cvs log for this node */ private void addSyncInfoToCommentNode(SyncInfo info, LogEntryCache logs) { - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) { + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) { ICVSRemoteResource remoteResource = handler.getRemoteResource(info); if(handler.getSubscriber() instanceof CVSCompareSubscriber && remoteResource != null) { addMultipleRevisions(info, logs, remoteResource); } else { addSingleRevision(info, logs, remoteResource); } - } + } } /* @@ -259,7 +259,7 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme */ private void addSingleRevision(SyncInfo info, LogEntryCache logs, ICVSRemoteResource remoteResource) { ILogEntry logEntry = logs.getLogEntry(remoteResource); - if (remoteResource != null && !remoteResource.isFolder()) { + if (remoteResource != null && !remoteResource.isFolder()) { // For incoming deletions grab the comment for the latest on the same branch // which is now in the attic. try { @@ -277,11 +277,11 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme } catch (TeamException e) { // continue and skip deletion checks } - } + } addRemoteChange(info, remoteResource, logEntry); } - /* + /* * Add multiple log entries to the model. * * @param info @@ -309,86 +309,86 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme return false; } - /* - * Add the remote change to an incoming commit set - */ - private void addRemoteChange(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { - if (disposed) return; - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if(handler != null && remoteResource != null && logEntry != null && handler.isRemoteChange(info)) { - if(requiresCustomSyncInfo(info, remoteResource, logEntry)) { - info = new CVSUpdatableSyncInfo(info.getKind(), info.getLocal(), info.getBase(), (RemoteResource)logEntry.getRemoteFile(), ((CVSSyncInfo)info).getSubscriber()); - try { - info.init(); - } catch (TeamException e) { - // this shouldn't happen, we've provided our own calculate kind - } - } - // Only add the info if the base and remote differ - IResourceVariant base = info.getBase(); - IResourceVariant remote = info.getRemote(); - if ((base == null && remote != null) || (remote == null && base != null) || (remote != null && base != null && !base.equals(remote))) { - synchronized(this) { - CheckedInChangeSet set = getChangeSetFor(logEntry); - if (set == null) { - set = createChangeSetFor(logEntry); - add(set); - } - set.add(info); - } - } - } else { - // The info was not retrieved for the remote change for some reason. - // Add the node to the root - addToDefaultSet(DEFAULT_INCOMING_SET_NAME, info); - } - } - - private void addToDefaultSet(String name, SyncInfo info) { - CheckedInChangeSet set; - synchronized(this) { - set = getChangeSetFor(name); - if (set == null) { - set = createDefaultChangeSet(name); - add(set); - } - set.add(info); - } - } - - private CheckedInChangeSet createDefaultChangeSet(String name) { - return new DefaultCheckedInChangeSet(name); - } + /* + * Add the remote change to an incoming commit set + */ + private void addRemoteChange(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { + if (disposed) return; + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if(handler != null && remoteResource != null && logEntry != null && handler.isRemoteChange(info)) { + if(requiresCustomSyncInfo(info, remoteResource, logEntry)) { + info = new CVSUpdatableSyncInfo(info.getKind(), info.getLocal(), info.getBase(), (RemoteResource)logEntry.getRemoteFile(), ((CVSSyncInfo)info).getSubscriber()); + try { + info.init(); + } catch (TeamException e) { + // this shouldn't happen, we've provided our own calculate kind + } + } + // Only add the info if the base and remote differ + IResourceVariant base = info.getBase(); + IResourceVariant remote = info.getRemote(); + if ((base == null && remote != null) || (remote == null && base != null) || (remote != null && base != null && !base.equals(remote))) { + synchronized(this) { + CheckedInChangeSet set = getChangeSetFor(logEntry); + if (set == null) { + set = createChangeSetFor(logEntry); + add(set); + } + set.add(info); + } + } + } else { + // The info was not retrieved for the remote change for some reason. + // Add the node to the root + addToDefaultSet(DEFAULT_INCOMING_SET_NAME, info); + } + } + + private void addToDefaultSet(String name, SyncInfo info) { + CheckedInChangeSet set; + synchronized(this) { + set = getChangeSetFor(name); + if (set == null) { + set = createDefaultChangeSet(name); + add(set); + } + set.add(info); + } + } + + private CheckedInChangeSet createDefaultChangeSet(String name) { + return new DefaultCheckedInChangeSet(name); + } - private CheckedInChangeSet createChangeSetFor(ILogEntry logEntry) { - return new CVSCheckedInChangeSet(logEntry); - } + private CheckedInChangeSet createChangeSetFor(ILogEntry logEntry) { + return new CVSCheckedInChangeSet(logEntry); + } - private CheckedInChangeSet getChangeSetFor(ILogEntry logEntry) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (set instanceof CheckedInChangeSet && - set.getComment().equals(logEntry.getComment()) && - ((CheckedInChangeSet)set).getAuthor().equals(logEntry.getAuthor())) { - return (CheckedInChangeSet)set; - } - } - return null; - } + private CheckedInChangeSet getChangeSetFor(ILogEntry logEntry) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (set instanceof CheckedInChangeSet && + set.getComment().equals(logEntry.getComment()) && + ((CheckedInChangeSet)set).getAuthor().equals(logEntry.getAuthor())) { + return (CheckedInChangeSet)set; + } + } + return null; + } - private CheckedInChangeSet getChangeSetFor(String name) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (set.getName().equals(name)) { - return (CheckedInChangeSet)set; - } - } - return null; - } - - private boolean requiresCustomSyncInfo(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { + private CheckedInChangeSet getChangeSetFor(String name) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (set.getName().equals(name)) { + return (CheckedInChangeSet)set; + } + } + return null; + } + + private boolean requiresCustomSyncInfo(SyncInfo info, ICVSRemoteResource remoteResource, ILogEntry logEntry) { // Only interested in non-deletions if (logEntry.isDeletion() || !(info instanceof CVSSyncInfo)) return false; // Only require a custom sync info if the remote of the sync info @@ -397,14 +397,14 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme if (remote == null) return true; return !remote.equals(remoteResource); } - - @Override + + @Override public void waitUntilDone(IProgressMonitor monitor) { - super.waitUntilDone(monitor); + super.waitUntilDone(monitor); monitor.worked(1); // wait for the event handler to process changes. - LogEntryCacheUpdateHandler handler = getLogEntryHandler(); - if (handler != null) { + LogEntryCacheUpdateHandler handler = getLogEntryHandler(); + if (handler != null) { while(handler.getEventHandlerJob().getState() != Job.NONE) { monitor.worked(1); try { @@ -413,23 +413,23 @@ public class CVSChangeSetCollector extends SyncInfoSetChangeSetCollector impleme } Policy.checkCanceled(monitor); } - } + } monitor.worked(1); - } + } - @Override + @Override public void logEntriesFetched(SyncInfoSet set, LogEntryCache logEntryCache, IProgressMonitor monitor) { - if (disposed) return; - // Hold on to the cache so we can use it while commit sets are visible - this.logEntryCache = logEntryCache; - handleRemoteChanges(set.getSyncInfos(), logEntryCache, monitor); - } + if (disposed) return; + // Hold on to the cache so we can use it while commit sets are visible + this.logEntryCache = logEntryCache; + handleRemoteChanges(set.getSyncInfos(), logEntryCache, monitor); + } - public ICVSRemoteFile getImmediatePredecessor(ICVSRemoteFile file) throws TeamException { - if (logEntryCache != null) - return logEntryCache.getImmediatePredecessor(file); - return null; - } + public ICVSRemoteFile getImmediatePredecessor(ICVSRemoteFile file) throws TeamException { + if (logEntryCache != null) + return logEntryCache.getImmediatePredecessor(file); + return null; + } @Override protected void initializeSets() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipant.java index 8050fc515..60e423cab 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipant.java @@ -47,129 +47,129 @@ public class CVSParticipant extends SubscriberParticipant implements IChangeSetP configuration.addLabelDecorator(labelDecorator); } - @Override + @Override public void prepareCompareInput(ISynchronizeModelElement element, CompareConfiguration config, IProgressMonitor monitor) throws TeamException { - monitor.beginTask(null, 100); - deriveBaseContentsFromLocal(element, Policy.subMonitorFor(monitor, 10)); - super.prepareCompareInput(element, config, Policy.subMonitorFor(monitor, 80)); - updateLabelsForCVS(element, config, Policy.subMonitorFor(monitor, 10)); - monitor.done(); - } + monitor.beginTask(null, 100); + deriveBaseContentsFromLocal(element, Policy.subMonitorFor(monitor, 10)); + super.prepareCompareInput(element, config, Policy.subMonitorFor(monitor, 80)); + updateLabelsForCVS(element, config, Policy.subMonitorFor(monitor, 10)); + monitor.done(); + } - /** - * Helper method for updating compare editor labels - */ - protected static void updateLabelsForCVS(ISynchronizeModelElement element, CompareConfiguration config, IProgressMonitor monitor) { - // Add the author to the remote or base - if (TeamUIPlugin.getPlugin().getPreferenceStore().getBoolean(IPreferenceIds.SHOW_AUTHOR_IN_COMPARE_EDITOR)) { - SyncInfo info = getSyncInfo(element); - if (info != null) { - final IResourceVariant remote = info.getRemote(); - final IResourceVariant base = info.getBase(); - String remoteAuthor = null; - if (remote != null && !remote.isContainer()) { - try { - ILogEntry entry = ((ICVSRemoteFile)remote).getLogEntry(monitor); - remoteAuthor = entry.getAuthor(); - config.setRightLabel(NLS.bind(CVSUIMessages.CVSParticipant_0, new String[] { remote.getContentIdentifier(), remoteAuthor })); - } catch (TeamException e) { - CVSUIPlugin.log(e); - } - } - if (base != null && !base.isContainer()) { - try { - String baseAuthor; - if (remoteAuthor != null && remote.getContentIdentifier().equals(base.getContentIdentifier())) { - baseAuthor = remoteAuthor; - } else { - ILogEntry entry = ((ICVSRemoteFile)base).getLogEntry(monitor); - baseAuthor = entry.getAuthor(); - } - config.setAncestorLabel(NLS.bind(CVSUIMessages.CVSParticipant_1, new String[] { base.getContentIdentifier(), baseAuthor })); - } catch (TeamException e) { - CVSUIPlugin.log(e); - } - } - } - } - } - + /** + * Helper method for updating compare editor labels + */ + protected static void updateLabelsForCVS(ISynchronizeModelElement element, CompareConfiguration config, IProgressMonitor monitor) { + // Add the author to the remote or base + if (TeamUIPlugin.getPlugin().getPreferenceStore().getBoolean(IPreferenceIds.SHOW_AUTHOR_IN_COMPARE_EDITOR)) { + SyncInfo info = getSyncInfo(element); + if (info != null) { + final IResourceVariant remote = info.getRemote(); + final IResourceVariant base = info.getBase(); + String remoteAuthor = null; + if (remote != null && !remote.isContainer()) { + try { + ILogEntry entry = ((ICVSRemoteFile)remote).getLogEntry(monitor); + remoteAuthor = entry.getAuthor(); + config.setRightLabel(NLS.bind(CVSUIMessages.CVSParticipant_0, new String[] { remote.getContentIdentifier(), remoteAuthor })); + } catch (TeamException e) { + CVSUIPlugin.log(e); + } + } + if (base != null && !base.isContainer()) { + try { + String baseAuthor; + if (remoteAuthor != null && remote.getContentIdentifier().equals(base.getContentIdentifier())) { + baseAuthor = remoteAuthor; + } else { + ILogEntry entry = ((ICVSRemoteFile)base).getLogEntry(monitor); + baseAuthor = entry.getAuthor(); + } + config.setAncestorLabel(NLS.bind(CVSUIMessages.CVSParticipant_1, new String[] { base.getContentIdentifier(), baseAuthor })); + } catch (TeamException e) { + CVSUIPlugin.log(e); + } + } + } + } + } + protected static SyncInfo getSyncInfo(ISynchronizeModelElement element) { - if (element instanceof IAdaptable) { - return ((IAdaptable)element).getAdapter(SyncInfo.class); - } - return null; + if (element instanceof IAdaptable) { + return ((IAdaptable)element).getAdapter(SyncInfo.class); + } + return null; } - /** - * If the local is not modified and the base matches the local then - * cache the local contents as the contents of the base. - * @param element - * @throws CoreException - * @throws TeamException - */ - public static void deriveBaseContentsFromLocal(ISynchronizeModelElement element, IProgressMonitor monitor) throws TeamException { - SyncInfo info = getSyncInfo(element); - if (info == null) - return; - - // We need a base that is a file and a local that is a file - IResource local = info.getLocal(); - IResourceVariant base = info.getBase(); - if (base == null || base.isContainer() || local.getType() != IResource.FILE || !local.exists()) - return; - - // We can only use the local contents for incoming changes. - // Outgoing or conflicting changes imply that the local has changed - if ((info.getKind() & SyncInfo.DIRECTION_MASK) != SyncInfo.INCOMING) - return; - - try { - RemoteFile remoteFile = (RemoteFile)base; - if (!remoteFile.isContentsCached()) - (remoteFile).setContents((IFile)local, monitor); - } catch (CoreException e) { - if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) { - // The file must have just been deleted - return; - } - throw CVSException.wrapException(e); - } - } - - @Override + /** + * If the local is not modified and the base matches the local then + * cache the local contents as the contents of the base. + * @param element + * @throws CoreException + * @throws TeamException + */ + public static void deriveBaseContentsFromLocal(ISynchronizeModelElement element, IProgressMonitor monitor) throws TeamException { + SyncInfo info = getSyncInfo(element); + if (info == null) + return; + + // We need a base that is a file and a local that is a file + IResource local = info.getLocal(); + IResourceVariant base = info.getBase(); + if (base == null || base.isContainer() || local.getType() != IResource.FILE || !local.exists()) + return; + + // We can only use the local contents for incoming changes. + // Outgoing or conflicting changes imply that the local has changed + if ((info.getKind() & SyncInfo.DIRECTION_MASK) != SyncInfo.INCOMING) + return; + + try { + RemoteFile remoteFile = (RemoteFile)base; + if (!remoteFile.isContentsCached()) + (remoteFile).setContents((IFile)local, monitor); + } catch (CoreException e) { + if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) { + // The file must have just been deleted + return; + } + throw CVSException.wrapException(e); + } + } + + @Override public PreferencePage[] getPreferencePages() { - return addCVSPreferencePages(super.getPreferencePages()); - } + return addCVSPreferencePages(super.getPreferencePages()); + } - public static PreferencePage[] addCVSPreferencePages(PreferencePage[] inheritedPages) { - PreferencePage[] pages = new PreferencePage[inheritedPages.length + 1]; - for (int i = 0; i < inheritedPages.length; i++) { - pages[i] = inheritedPages[i]; - } - pages[pages.length - 1] = new ComparePreferencePage(); - pages[pages.length - 1].setTitle(CVSUIMessages.CVSParticipant_2); - return pages; - } - - @Override + public static PreferencePage[] addCVSPreferencePages(PreferencePage[] inheritedPages) { + PreferencePage[] pages = new PreferencePage[inheritedPages.length + 1]; + for (int i = 0; i < inheritedPages.length; i++) { + pages[i] = inheritedPages[i]; + } + pages[pages.length - 1] = new ComparePreferencePage(); + pages[pages.length - 1].setTitle(CVSUIMessages.CVSParticipant_2); + return pages; + } + + @Override public ChangeSetCapability getChangeSetCapability() { - if (capability == null) { - capability = createChangeSetCapability(); - } - return capability; - } + if (capability == null) { + capability = createChangeSetCapability(); + } + return capability; + } - /** - * Create the change set capability for this particpant. - * @return the created capability - */ - protected CVSChangeSetCapability createChangeSetCapability() { - return new CVSChangeSetCapability(); - } - - @Override + /** + * Create the change set capability for this particpant. + * @return the created capability + */ + protected CVSChangeSetCapability createChangeSetCapability() { + return new CVSChangeSetCapability(); + } + + @Override protected boolean isViewerContributionsSupported() { - return true; - } + return true; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipantLabelDecorator.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipantLabelDecorator.java index f74d3d540..1447e6ef7 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipantLabelDecorator.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CVSParticipantLabelDecorator.java @@ -93,11 +93,11 @@ public class CVSParticipantLabelDecorator extends LabelProvider implements IProp return Utils.getResource(internalGetElement(element)); } - protected CVSDecoration getDecoration(IResource resource) throws CoreException { - return CVSLightweightDecorator.decorate(resource, tester); - } + protected CVSDecoration getDecoration(IResource resource) throws CoreException { + return CVSLightweightDecorator.decorate(resource, tester); + } - public Image decorateImage(Image base, Object element) { + public Image decorateImage(Image base, Object element) { return base; } public void propertyChange(PropertyChangeEvent event) { @@ -110,8 +110,8 @@ public class CVSParticipantLabelDecorator extends LabelProvider implements IProp } protected boolean needsRefresh(PropertyChangeEvent event) { - final String property= event.getProperty(); - return property.equals(CVSUIPlugin.P_DECORATORS_CHANGED) || property.equals(TeamUI.GLOBAL_FILE_TYPES_CHANGED); + final String property= event.getProperty(); + return property.equals(CVSUIPlugin.P_DECORATORS_CHANGED) || property.equals(TeamUI.GLOBAL_FILE_TYPES_CHANGED); } public void dispose() { CVSUIPlugin.removePropertyChangeListener(this); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CommitSetDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CommitSetDialog.java index ad35c092f..81ec85208 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CommitSetDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CommitSetDialog.java @@ -34,75 +34,75 @@ import org.eclipse.ui.PlatformUI; */ public class CommitSetDialog extends TitleAreaDialog { - public final static short NEW = 0; - public final static short EDIT = 1; - + public final static short NEW = 0; + public final static short EDIT = 1; + private static final int DEFAULT_WIDTH_IN_CHARS= 80; - - private final ActiveChangeSet set; - private CommitCommentArea commitCommentArea; - private Text nameText; - private Button customTitleButton; - private final String title; - private final String description; - private String comment; - private short mode; + + private final ActiveChangeSet set; + private CommitCommentArea commitCommentArea; + private Text nameText; + private Button customTitleButton; + private final String title; + private final String description; + private String comment; + private short mode; protected String customTitle; - public CommitSetDialog(Shell parentShell, ActiveChangeSet set, IResource[] files, short mode) { - super(parentShell); - this.set = set; - this.mode = mode; + public CommitSetDialog(Shell parentShell, ActiveChangeSet set, IResource[] files, short mode) { + super(parentShell); + this.set = set; + this.mode = mode; this.title = mode == NEW ? CVSUIMessages.WorkspaceChangeSetCapability_2 : CVSUIMessages.WorkspaceChangeSetCapability_7; this.description = mode == NEW ? CVSUIMessages.WorkspaceChangeSetCapability_3 : CVSUIMessages.WorkspaceChangeSetCapability_8; - - if (files == null) { - files = set.getResources(); - } - + + if (files == null) { + files = set.getResources(); + } + int shellStyle = getShellStyle(); setShellStyle(shellStyle | SWT.RESIZE | SWT.MAX); commitCommentArea = new CommitCommentArea(); // Get a project from which the commit template can be obtained if (files.length > 0) - commitCommentArea.setProject(files[0].getProject()); - } - - @Override + commitCommentArea.setProject(files[0].getProject()); + } + + @Override protected Control createContents(Composite parent) { - Control contents = super.createContents(parent); - setTitle(title); - setMessage(description); - return contents; - } - - @Override + Control contents = super.createContents(parent); + setTitle(title); + setMessage(description); + return contents; + } + + @Override protected Control createDialogArea(Composite parent) { - Composite parentComposite = (Composite) super.createDialogArea(parent); + Composite parentComposite = (Composite) super.createDialogArea(parent); - // create a composite with standard margins and spacing - Composite composite = new Composite(parentComposite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - composite.setFont(parentComposite.getFont()); + // create a composite with standard margins and spacing + Composite composite = new Composite(parentComposite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + composite.setLayout(layout); + composite.setLayoutData(new GridData(GridData.FILL_BOTH)); + composite.setFont(parentComposite.getFont()); if (hasCommitTemplate()) { - if (set.hasComment()) { - // Only set the comment if the set has a custom comment. - // Otherwise, the template should be used - comment = set.getComment(); - commitCommentArea.setProposedComment(comment); - } + if (set.hasComment()) { + // Only set the comment if the set has a custom comment. + // Otherwise, the template should be used + comment = set.getComment(); + commitCommentArea.setProposedComment(comment); + } } else { - comment = set.getComment(); - commitCommentArea.setProposedComment(comment); + comment = set.getComment(); + commitCommentArea.setProposedComment(comment); } commitCommentArea.createArea(composite); @@ -124,19 +124,19 @@ public class CommitSetDialog extends TitleAreaDialog { initializeValues(); updateEnablements(); - Dialog.applyDialogFont(parent); - return composite; - } - + Dialog.applyDialogFont(parent); + return composite; + } + @Override protected Point getInitialSize() { - final Point size= super.getInitialSize(); - size.x= convertWidthInCharsToPixels(DEFAULT_WIDTH_IN_CHARS); - size.y += convertHeightInCharsToPixels(8); - return size; + final Point size= super.getInitialSize(); + size.x= convertWidthInCharsToPixels(DEFAULT_WIDTH_IN_CHARS); + size.y += convertHeightInCharsToPixels(8); + return size; } - private void createNameArea(Composite parent) { + private void createNameArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight = 0; @@ -158,20 +158,20 @@ public class CommitSetDialog extends TitleAreaDialog { customTitle = nameText.getText(); updateEnablements(); }); - } + } - private void initializeValues() { - String initialText = set.getTitle(); - if (initialText == null) initialText = ""; //$NON-NLS-1$ - nameText.setText(initialText); - nameText.setSelection(0, initialText.length()); - - if (customTitleButton != null) { - customTitleButton.setSelection(!commitCommentArea.getFirstLineOfComment().equals(initialText)); - } - } - - private void createOptionsArea(Composite composite) { + private void initializeValues() { + String initialText = set.getTitle(); + if (initialText == null) initialText = ""; //$NON-NLS-1$ + nameText.setText(initialText); + nameText.setSelection(0, initialText.length()); + + if (customTitleButton != null) { + customTitleButton.setSelection(!commitCommentArea.getFirstLineOfComment().equals(initialText)); + } + } + + private void createOptionsArea(Composite composite) { Composite radioArea = new Composite(composite, SWT.NONE); RowLayout radioAreaLayout = new RowLayout(SWT.VERTICAL); radioAreaLayout.marginLeft = 0; @@ -180,29 +180,29 @@ public class CommitSetDialog extends TitleAreaDialog { radioAreaLayout.marginBottom = 0; radioArea.setLayout(radioAreaLayout); - customTitleButton = createCheckButton(radioArea, CVSUIMessages.CommitSetDialog_2); - SelectionAdapter listener = new SelectionAdapter() { - @Override + customTitleButton = createCheckButton(radioArea, CVSUIMessages.CommitSetDialog_2); + SelectionAdapter listener = new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - if (customTitleButton.getSelection()) { - nameText.setText(customTitle); - } else { - nameText.setText(commitCommentArea.getFirstLineOfComment()); - } - updateEnablements(); - } - }; - customTitleButton.addSelectionListener(listener); - - } - + if (customTitleButton.getSelection()) { + nameText.setText(customTitle); + } else { + nameText.setText(commitCommentArea.getFirstLineOfComment()); + } + updateEnablements(); + } + }; + customTitleButton.addSelectionListener(listener); + + } + private Button createCheckButton(Composite parent, String label) { Button button = new Button(parent, SWT.CHECK); button.setText(label); return button; } - private void updateEnablements() { + private void updateEnablements() { setErrorMessage(null); String name; @@ -218,7 +218,7 @@ public class CommitSetDialog extends TitleAreaDialog { setPageComplete(false); return; } - + // check if the new change set already exists if (mode == NEW && CVSUIPlugin.getPlugin().getChangeSetManager().getSet(name) != null) { @@ -236,36 +236,36 @@ public class CommitSetDialog extends TitleAreaDialog { return; } - - setPageComplete(true); - } - + + setPageComplete(true); + } + final protected void setPageComplete(boolean complete) { - Button okButton = getButton(IDialogConstants.OK_ID); + Button okButton = getButton(IDialogConstants.OK_ID); if(okButton != null ) { okButton.setEnabled(complete); } } - private boolean hasCommitTemplate() { - return commitCommentArea.hasCommitTemplate(); - } - - @Override + private boolean hasCommitTemplate() { + return commitCommentArea.hasCommitTemplate(); + } + + @Override protected void okPressed() { - String title = null; - if (customTitleButton.getSelection()) { + String title = null; + if (customTitleButton.getSelection()) { title= customTitle; } else { title= commitCommentArea.getFirstLineOfComment(); } - - set.setTitle(title); - // Call getComment so the comment gets saved - set.setComment(commitCommentArea.getComment(true)); - - super.okPressed(); - } + + set.setTitle(title); + // Call getComment so the comment gets saved + set.setComment(commitCommentArea.getComment(true)); + + super.okPressed(); + } protected Label createWrappingLabel(Composite parent, String text) { @@ -281,13 +281,13 @@ public class CommitSetDialog extends TitleAreaDialog { return label; } - @Override + @Override protected Control createButtonBar(Composite parent) { - Control control = super.createButtonBar(parent); - updateEnablements(); - return control; - } - + Control control = super.createButtonBar(parent); + updateEnablements(); + return control; + } + @Override protected void configureShell(Shell shell) { super.configureShell(shell); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CompareParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CompareParticipant.java index 9faaf017d..7d3e007b4 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CompareParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CompareParticipant.java @@ -120,7 +120,7 @@ public class CompareParticipant extends CVSParticipant implements IPreferenceCha } public CompareParticipant(CVSCompareSubscriber subscriber) { - setSubscriber(subscriber); + setSubscriber(subscriber); } @Override @@ -152,9 +152,9 @@ public class CompareParticipant extends CVSParticipant implements IPreferenceCha ISynchronizeParticipantReference reference = refs[i]; if (reference.getId().equals(CVSCompareSubscriber.ID)) { try { - CompareParticipant p = (CompareParticipant) reference.getParticipant(); + CompareParticipant p = (CompareParticipant) reference.getParticipant(); if (p.matches(resources, tag)) { - return p; + return p; } } catch (TeamException e) { continue; @@ -188,11 +188,11 @@ public class CompareParticipant extends CVSParticipant implements IPreferenceCha /** * Return the subscriber as an instance of CVSCompareSubscriber. - * @return the subscriber as an instance of CVSCompareSubscriber - */ - public CVSCompareSubscriber getCVSCompareSubscriber() { - return (CVSCompareSubscriber)getSubscriber(); - } + * @return the subscriber as an instance of CVSCompareSubscriber + */ + public CVSCompareSubscriber getCVSCompareSubscriber() { + return (CVSCompareSubscriber)getSubscriber(); + } @Override protected void initializeConfiguration(ISynchronizePageConfiguration configuration) { @@ -235,18 +235,18 @@ public class CompareParticipant extends CVSParticipant implements IPreferenceCha return CVSUIMessages.Participant_comparing; } - @Override + @Override protected CVSChangeSetCapability createChangeSetCapability() { - return new CVSChangeSetCapability() { - @Override + return new CVSChangeSetCapability() { + @Override public ActiveChangeSetManager getActiveChangeSetManager() { - return CVSUIPlugin.getPlugin().getChangeSetManager(); - } - @Override + return CVSUIPlugin.getPlugin().getChangeSetManager(); + } + @Override public boolean enableActiveChangeSetsFor(ISynchronizePageConfiguration configuration) { - return super.enableActiveChangeSetsFor(configuration) || - configuration.getComparisonType() == ISynchronizePageConfiguration.TWO_WAY; - } - }; - } + return super.enableActiveChangeSetsFor(configuration) || + configuration.getComparisonType() == ISynchronizePageConfiguration.TWO_WAY; + } + }; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchAction.java index 7a03054b7..8b738501a 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchAction.java @@ -39,29 +39,29 @@ public class CreatePatchAction extends CVSParticipantAction { @Override public void runOperation() { - final SyncInfoSet set = getSyncInfoSet(); - GenerateDiffFileWizard.run(getConfiguration().getSite().getPart(), set.getResources(), false); - } + final SyncInfoSet set = getSyncInfoSet(); + GenerateDiffFileWizard.run(getConfiguration().getSite().getPart(), set.getResources(), false); + } /* - * Return the selected SyncInfo for which this action is enabled. - * - * @return the selected SyncInfo for which this action is enabled. - */ - private SyncInfoSet getSyncInfoSet() { - IDiffElement [] elements= getFilteredDiffElements(); - SyncInfoSet filtered = new SyncInfoSet(); - for (int i = 0; i < elements.length; i++) { - IDiffElement e = elements[i]; - if (e instanceof SyncInfoModelElement) { - filtered.add(((SyncInfoModelElement)e).getSyncInfo()); - } - } - return filtered; - } - - @Override + * Return the selected SyncInfo for which this action is enabled. + * + * @return the selected SyncInfo for which this action is enabled. + */ + private SyncInfoSet getSyncInfoSet() { + IDiffElement [] elements= getFilteredDiffElements(); + SyncInfoSet filtered = new SyncInfoSet(); + for (int i = 0; i < elements.length; i++) { + IDiffElement e = elements[i]; + if (e instanceof SyncInfoModelElement) { + filtered.add(((SyncInfoModelElement)e).getSyncInfo()); + } + } + return filtered; + } + + @Override protected String getBundleKeyPrefix() { - return "GenerateDiffFileAction."; //$NON-NLS-1$ - } + return "GenerateDiffFileAction."; //$NON-NLS-1$ + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchWizardParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchWizardParticipant.java index 91bbf51c2..4ce58e99b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchWizardParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/CreatePatchWizardParticipant.java @@ -19,26 +19,26 @@ import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; import org.eclipse.team.ui.synchronize.ISynchronizeScope; public class CreatePatchWizardParticipant extends WorkspaceSynchronizeParticipant { - - final GenerateDiffFileWizard fWizard; - - public CreatePatchWizardParticipant(ISynchronizeScope scope, GenerateDiffFileWizard wizard) { - super(scope); - fWizard= wizard; - } + + final GenerateDiffFileWizard fWizard; + + public CreatePatchWizardParticipant(ISynchronizeScope scope, GenerateDiffFileWizard wizard) { + super(scope); + fWizard= wizard; + } @Override - protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { - super.initializeConfiguration(configuration); - configuration.setProperty(ISynchronizePageConfiguration.P_TOOLBAR_MENU, new String[] {ISynchronizePageConfiguration.LAYOUT_GROUP}); - configuration.setProperty(ISynchronizePageConfiguration.P_CONTEXT_MENU, ISynchronizePageConfiguration.DEFAULT_CONTEXT_MENU); - ((SynchronizePageConfiguration)configuration).setViewerStyle(SynchronizePageConfiguration.CHECKBOX); - configuration.setSupportedModes(ISynchronizePageConfiguration.OUTGOING_MODE); - configuration.setMode(ISynchronizePageConfiguration.OUTGOING_MODE); - } + protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { + super.initializeConfiguration(configuration); + configuration.setProperty(ISynchronizePageConfiguration.P_TOOLBAR_MENU, new String[] {ISynchronizePageConfiguration.LAYOUT_GROUP}); + configuration.setProperty(ISynchronizePageConfiguration.P_CONTEXT_MENU, ISynchronizePageConfiguration.DEFAULT_CONTEXT_MENU); + ((SynchronizePageConfiguration)configuration).setViewerStyle(SynchronizePageConfiguration.CHECKBOX); + configuration.setSupportedModes(ISynchronizePageConfiguration.OUTGOING_MODE); + configuration.setMode(ISynchronizePageConfiguration.OUTGOING_MODE); + } @Override - public boolean doesSupportSynchronize() { - return false; - } + public boolean doesSupportSynchronize() { + return false; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/LogEntryCacheUpdateHandler.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/LogEntryCacheUpdateHandler.java index 93eb373a0..ff57ec0e4 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/LogEntryCacheUpdateHandler.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/LogEntryCacheUpdateHandler.java @@ -44,265 +44,265 @@ import org.eclipse.team.ui.synchronize.*; * in the subscriber. */ public class LogEntryCacheUpdateHandler extends BackgroundEventHandler { - - private static final int REMOVAL = 1; - private static final int CHANGE = 2; - private static final int FETCH_REQUEST = 3; - private static final int PAUSE = 4; - - /* - * Lock used to ensure that fetches are queued when the job is - * a non-system job. - */ - private final Object queueLock = new Object(); - - /* - * Exception used to stop processing so the job can be restarted as a non-system job - */ - private static final OperationCanceledException PAUSE_EXCEPTION = new OperationCanceledException(); - - /* - * Contants for configuring how long to wait for the job to be paused - * when a fetch is required and the job needs to be converted to a non-system - * job. If the wait time is elapsed, an exception is thrown. - */ - private static final int WAIT_INCREMENT = 10; - private static final int MAX_WAIT = 1000; - - /* - * Set that keeps track of all resource for which we haved fetched log entries - */ - private final SyncInfoTree collectedInfos = new SyncInfoTree(); - - /* - * The cache that hold the log entries while the job is running - */ - //private LogEntryCache logEntriesCache; - - /* - * SoftReference used to hold on to the log entry cache while - * the job is not running so the cache can be cleared if memory is low. - */ - private SoftReference cacheReference; - - /* - * Collector that forewards subscriber changes so that - * stale cache entries can be cleared. - */ - private final LogEntryResourceCollector collector; + + private static final int REMOVAL = 1; + private static final int CHANGE = 2; + private static final int FETCH_REQUEST = 3; + private static final int PAUSE = 4; + + /* + * Lock used to ensure that fetches are queued when the job is + * a non-system job. + */ + private final Object queueLock = new Object(); + + /* + * Exception used to stop processing so the job can be restarted as a non-system job + */ + private static final OperationCanceledException PAUSE_EXCEPTION = new OperationCanceledException(); + + /* + * Contants for configuring how long to wait for the job to be paused + * when a fetch is required and the job needs to be converted to a non-system + * job. If the wait time is elapsed, an exception is thrown. + */ + private static final int WAIT_INCREMENT = 10; + private static final int MAX_WAIT = 1000; + + /* + * Set that keeps track of all resource for which we haved fetched log entries + */ + private final SyncInfoTree collectedInfos = new SyncInfoTree(); + + /* + * The cache that hold the log entries while the job is running + */ + //private LogEntryCache logEntriesCache; + + /* + * SoftReference used to hold on to the log entry cache while + * the job is not running so the cache can be cleared if memory is low. + */ + private SoftReference cacheReference; + + /* + * Collector that forewards subscriber changes so that + * stale cache entries can be cleared. + */ + private final LogEntryResourceCollector collector; - /* - * The subscriber generating the SyncInfo and log entries - */ - private final Subscriber subscriber; - - /* - * The accumulated list of updates that need to be dispatched - * (i.e. the cache should be purged of out-of-date resources). - * This list is only modified and accessed from the event processing - * thread. - */ + /* + * The subscriber generating the SyncInfo and log entries + */ + private final Subscriber subscriber; + + /* + * The accumulated list of updates that need to be dispatched + * (i.e. the cache should be purged of out-of-date resources). + * This list is only modified and accessed from the event processing + * thread. + */ private final List<Event> updates = new ArrayList<>(); - - /* - * The accumulated list of fetches that have been requested - */ + + /* + * The accumulated list of fetches that have been requested + */ private final List<Event> fetches = new ArrayList<>(); - private final ISynchronizePageConfiguration configuration; - - - /* - * Interface for notifying a single client that the infos have been fetched - */ - public interface ILogsFetchedListener { + private final ISynchronizePageConfiguration configuration; + + + /* + * Interface for notifying a single client that the infos have been fetched + */ + public interface ILogsFetchedListener { - void logEntriesFetched(SyncInfoSet set, LogEntryCache logEntryCache, IProgressMonitor monitor); - - } - - /* - * The listener or null if noone is listening - */ - private ILogsFetchedListener listener; - - /* - * Subscriber resource collector that forwards subscriber changes - * through the handler so that stale cache entries can be cleared - */ - private class LogEntryResourceCollector extends SubscriberResourceCollector { + void logEntriesFetched(SyncInfoSet set, LogEntryCache logEntryCache, IProgressMonitor monitor); + + } + + /* + * The listener or null if noone is listening + */ + private ILogsFetchedListener listener; + + /* + * Subscriber resource collector that forwards subscriber changes + * through the handler so that stale cache entries can be cleared + */ + private class LogEntryResourceCollector extends SubscriberResourceCollector { - public LogEntryResourceCollector(Subscriber subscriber) { - super(subscriber); - } + public LogEntryResourceCollector(Subscriber subscriber) { + super(subscriber); + } - @Override + @Override protected void remove(IResource resource) { - queueEvent(new ResourceEvent(resource, REMOVAL, IResource.DEPTH_INFINITE), false /* do not put in on the front of the queue*/); - } + queueEvent(new ResourceEvent(resource, REMOVAL, IResource.DEPTH_INFINITE), false /* do not put in on the front of the queue*/); + } - @Override + @Override protected void change(IResource resource, int depth) { - queueEvent(new ResourceEvent(resource, CHANGE, depth), false /* do not put in on the front of the queue*/); - } + queueEvent(new ResourceEvent(resource, CHANGE, depth), false /* do not put in on the front of the queue*/); + } - @Override + @Override protected boolean hasMembers(IResource resource) { - return collectedInfos.hasMembers(resource); - } - } - - /* - * Custom event for queue a log entry fetch request - */ - private class FetchRequest extends Event { - private final SyncInfo[] infos; - public FetchRequest(SyncInfo[] infos) { - super(FETCH_REQUEST); - this.infos = infos; - } - public SyncInfo[] getInfos() { - return infos; - } - } - - public LogEntryCacheUpdateHandler(ISynchronizePageConfiguration configuration) { - super(CVSUIMessages.LogEntryCacheUpdateHandler_1, CVSUIMessages.LogEntryCacheUpdateHandler_0); // - this.configuration = configuration; - this.subscriber = getSubscriber(configuration); - cacheReference = new SoftReference(new LogEntryCache()); - collector = new LogEntryResourceCollector(subscriber); - } + return collectedInfos.hasMembers(resource); + } + } + + /* + * Custom event for queue a log entry fetch request + */ + private class FetchRequest extends Event { + private final SyncInfo[] infos; + public FetchRequest(SyncInfo[] infos) { + super(FETCH_REQUEST); + this.infos = infos; + } + public SyncInfo[] getInfos() { + return infos; + } + } + + public LogEntryCacheUpdateHandler(ISynchronizePageConfiguration configuration) { + super(CVSUIMessages.LogEntryCacheUpdateHandler_1, CVSUIMessages.LogEntryCacheUpdateHandler_0); // + this.configuration = configuration; + this.subscriber = getSubscriber(configuration); + cacheReference = new SoftReference(new LogEntryCache()); + collector = new LogEntryResourceCollector(subscriber); + } - private Subscriber getSubscriber(ISynchronizePageConfiguration configuration) { - ISynchronizeParticipant participant = configuration.getParticipant(); - if (participant instanceof SubscriberParticipant) { + private Subscriber getSubscriber(ISynchronizePageConfiguration configuration) { + ISynchronizeParticipant participant = configuration.getParticipant(); + if (participant instanceof SubscriberParticipant) { SubscriberParticipant sp = (SubscriberParticipant) participant; return sp.getSubscriber(); } - if (participant instanceof ModelCompareParticipant) { + if (participant instanceof ModelCompareParticipant) { ModelCompareParticipant mcp = (ModelCompareParticipant) participant; return mcp.getSubscriber(); } - return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); - } + return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber(); + } - public ISynchronizePageConfiguration getConfiguration() { - return configuration; - } - - public Subscriber getSubscriber() { - return subscriber; - } - - /** - * Set the listener that should receive notification when log entries - * have been fetched and are avalable. - * @param listener the listener or <code>null</code> - */ - public void setListener(ILogsFetchedListener listener) { - this.listener = listener; - } - - @Override + public ISynchronizePageConfiguration getConfiguration() { + return configuration; + } + + public Subscriber getSubscriber() { + return subscriber; + } + + /** + * Set the listener that should receive notification when log entries + * have been fetched and are avalable. + * @param listener the listener or <code>null</code> + */ + public void setListener(ILogsFetchedListener listener) { + this.listener = listener; + } + + @Override protected Object getJobFamiliy() { - return ISynchronizeManager.FAMILY_SYNCHRONIZE_OPERATION; - } - - @Override + return ISynchronizeManager.FAMILY_SYNCHRONIZE_OPERATION; + } + + @Override protected void createEventHandlingJob() { - super.createEventHandlingJob(); - Job job = getEventHandlerJob(); - job.setSystem(false); - job.setUser(false); - } - - @Override + super.createEventHandlingJob(); + Job job = getEventHandlerJob(); + job.setSystem(false); + job.setUser(false); + } + + @Override protected void processEvent(Event event, IProgressMonitor monitor) throws CoreException { - Policy.checkCanceled(monitor); - switch (event.getType()) { - case REMOVAL: - case CHANGE: - updates.add(event); - break; - case FETCH_REQUEST: - fetches.add(event); - break; - case PAUSE: - throw PAUSE_EXCEPTION; - } - - } - - @Override + Policy.checkCanceled(monitor); + switch (event.getType()) { + case REMOVAL: + case CHANGE: + updates.add(event); + break; + case FETCH_REQUEST: + fetches.add(event); + break; + case PAUSE: + throw PAUSE_EXCEPTION; + } + + } + + @Override protected boolean doDispatchEvents(IProgressMonitor monitor) throws TeamException { - Policy.checkCanceled(monitor); - boolean dispatched = false; - monitor.beginTask(null, 50); - dispatched |= updateCache(Policy.subMonitorFor(monitor, 20)); - dispatched |= processQueuedFetches(Policy.subMonitorFor(monitor, 80)); - monitor.done(); - return dispatched; - } - - /* - * Remove any stale or unneeded log entries from the cache. - * Return whether there were any entries to purge. - */ - private boolean updateCache(IProgressMonitor monitor) { - if (updates.isEmpty()) return false; - try { - collectedInfos.beginInput(); - // Cycle through the update events - for (Iterator iter = updates.iterator(); iter.hasNext();) { - Event event = (Event) iter.next(); - Policy.checkCanceled(monitor); - if (event.getType() == REMOVAL) { - remove(event.getResource(), ((ResourceEvent)event).getDepth()); - } else if (event.getType() == CHANGE) { - change(event.getResource(), ((ResourceEvent)event).getDepth()); - } - // Use the iterator to remove so that updates will not be lost - // if the job is cancelled and then restarted. - iter.remove(); - } - } finally { - collectedInfos.endInput(monitor); - } - return true; - } + Policy.checkCanceled(monitor); + boolean dispatched = false; + monitor.beginTask(null, 50); + dispatched |= updateCache(Policy.subMonitorFor(monitor, 20)); + dispatched |= processQueuedFetches(Policy.subMonitorFor(monitor, 80)); + monitor.done(); + return dispatched; + } + + /* + * Remove any stale or unneeded log entries from the cache. + * Return whether there were any entries to purge. + */ + private boolean updateCache(IProgressMonitor monitor) { + if (updates.isEmpty()) return false; + try { + collectedInfos.beginInput(); + // Cycle through the update events + for (Iterator iter = updates.iterator(); iter.hasNext();) { + Event event = (Event) iter.next(); + Policy.checkCanceled(monitor); + if (event.getType() == REMOVAL) { + remove(event.getResource(), ((ResourceEvent)event).getDepth()); + } else if (event.getType() == CHANGE) { + change(event.getResource(), ((ResourceEvent)event).getDepth()); + } + // Use the iterator to remove so that updates will not be lost + // if the job is cancelled and then restarted. + iter.remove(); + } + } finally { + collectedInfos.endInput(monitor); + } + return true; + } - @Override + @Override public void shutdown() { - super.shutdown(); - collector.dispose(); - // Probably not necessary as GC would take care of it but we'll do it anyway - if (cacheReference != null) { - LogEntryCache cache = (LogEntryCache)cacheReference.get(); - if (cache != null) { - cache.clearEntries(); - } - } - collectedInfos.clear(); - - } - - private void remove(IResource resource, int depth) { - collectedInfos.remove(resource, depth); - } + super.shutdown(); + collector.dispose(); + // Probably not necessary as GC would take care of it but we'll do it anyway + if (cacheReference != null) { + LogEntryCache cache = (LogEntryCache)cacheReference.get(); + if (cache != null) { + cache.clearEntries(); + } + } + collectedInfos.clear(); + + } + + private void remove(IResource resource, int depth) { + collectedInfos.remove(resource, depth); + } - private void remove(SyncInfo info) { - if (info != null) { - collectedInfos.remove(info.getLocal()); - LogEntryCache cache = (LogEntryCache)cacheReference.get(); - if (cache != null) { + private void remove(SyncInfo info) { + if (info != null) { + collectedInfos.remove(info.getLocal()); + LogEntryCache cache = (LogEntryCache)cacheReference.get(); + if (cache != null) { ICVSRemoteResource remoteResource = getRemoteResource(info); if (remoteResource != null) cache.clearEntries(remoteResource); } - } - } + } + } - public ICVSRemoteResource getRemoteResource(SyncInfo info) { + public ICVSRemoteResource getRemoteResource(SyncInfo info) { try { ICVSRemoteResource remote = (ICVSRemoteResource) info.getRemote(); ICVSRemoteResource local = CVSWorkspaceRoot.getRemoteResourceFor(info.getLocal()); @@ -330,180 +330,180 @@ public class LogEntryCacheUpdateHandler extends BackgroundEventHandler { } } - private boolean useRemote(String localRevision, String remoteRevision) { - boolean useRemote; - if (remoteRevision == null && localRevision == null) { - useRemote = true; - } else if (localRevision == null) { - useRemote = true; - } else if (remoteRevision == null) { - useRemote = false; - } else { - useRemote = ResourceSyncInfo.isLaterRevision(remoteRevision, localRevision); - } - return useRemote; - } + private boolean useRemote(String localRevision, String remoteRevision) { + boolean useRemote; + if (remoteRevision == null && localRevision == null) { + useRemote = true; + } else if (localRevision == null) { + useRemote = true; + } else if (remoteRevision == null) { + useRemote = false; + } else { + useRemote = ResourceSyncInfo.isLaterRevision(remoteRevision, localRevision); + } + return useRemote; + } - private String getRevisionString(ICVSRemoteResource remoteFile) { + private String getRevisionString(ICVSRemoteResource remoteFile) { if(remoteFile instanceof RemoteFile) { return ((RemoteFile)remoteFile).getRevision(); } return null; } - - private void change(IResource resource, int depth) { - // We only need to remove collected log entries that don't apply - // any longer. They will be refetched when they are required. - SyncInfo[] collected = collectedInfos.getSyncInfos(resource, depth); - change(collected); - } - - private void change(SyncInfo[] collected) { - Subscriber subscriber = getSubscriber(); - for (int i = 0; i < collected.length; i++) { - try { - SyncInfo info = collected[i]; - SyncInfo newInfo = subscriber.getSyncInfo(info.getLocal()); - if (newInfo == null || !newInfo.equals(info)) { - // The cached log entry no longer applies to the new sync info. - // It will be refetched when required. - remove(info); - } - } catch (TeamException e) { - // Log and continue - CVSUIPlugin.log(e); - } - } - } + + private void change(IResource resource, int depth) { + // We only need to remove collected log entries that don't apply + // any longer. They will be refetched when they are required. + SyncInfo[] collected = collectedInfos.getSyncInfos(resource, depth); + change(collected); + } + + private void change(SyncInfo[] collected) { + Subscriber subscriber = getSubscriber(); + for (int i = 0; i < collected.length; i++) { + try { + SyncInfo info = collected[i]; + SyncInfo newInfo = subscriber.getSyncInfo(info.getLocal()); + if (newInfo == null || !newInfo.equals(info)) { + // The cached log entry no longer applies to the new sync info. + // It will be refetched when required. + remove(info); + } + } catch (TeamException e) { + // Log and continue + CVSUIPlugin.log(e); + } + } + } - /** - * Queue a request to fetch log entries for the given SyncInfo nodes. - * The event handler must be a non-system job when revision histories - * are fetched. - * @param infos the nodes whose log entries are to be fetched - */ - public void fetch(SyncInfo[] infos) throws CVSException { - synchronized(queueLock) { - Job job = getEventHandlerJob(); - if (job.isSystem() && job.getState() != Job.NONE) { - // queue an event to pause the processor - super.queueEvent(new Event(PAUSE), true /* put on the front of the queue */); - int count = 0; - while (job.getState() != Job.NONE && count < MAX_WAIT) { - count += WAIT_INCREMENT; - try { - Thread.sleep(WAIT_INCREMENT); // Wait a little while - } catch (InterruptedException e) { - // Ignore - } - } - if (job.getState() != Job.NONE) { - // The job never completed in the time aloted so throw an exception - throw new CVSException(CVSUIMessages.LogEntryCacheUpdateHandler_2); - } - } - // Queue the event even if the job didn't stop in the time aloted - queueEvent(new FetchRequest(infos), false /* don't place at the end */); - } - } - - @Override + /** + * Queue a request to fetch log entries for the given SyncInfo nodes. + * The event handler must be a non-system job when revision histories + * are fetched. + * @param infos the nodes whose log entries are to be fetched + */ + public void fetch(SyncInfo[] infos) throws CVSException { + synchronized(queueLock) { + Job job = getEventHandlerJob(); + if (job.isSystem() && job.getState() != Job.NONE) { + // queue an event to pause the processor + super.queueEvent(new Event(PAUSE), true /* put on the front of the queue */); + int count = 0; + while (job.getState() != Job.NONE && count < MAX_WAIT) { + count += WAIT_INCREMENT; + try { + Thread.sleep(WAIT_INCREMENT); // Wait a little while + } catch (InterruptedException e) { + // Ignore + } + } + if (job.getState() != Job.NONE) { + // The job never completed in the time aloted so throw an exception + throw new CVSException(CVSUIMessages.LogEntryCacheUpdateHandler_2); + } + } + // Queue the event even if the job didn't stop in the time aloted + queueEvent(new FetchRequest(infos), false /* don't place at the end */); + } + } + + @Override protected void queueEvent(Event event, boolean front) { - // Override to snure that queues by this handler are serialized - synchronized(queueLock) { - Job job = getEventHandlerJob(); - if (job.getState() == Job.NONE) { - job.setSystem(event.getType() != FETCH_REQUEST); - } - super.queueEvent(event, front); - } - } - - /* - * Method invoked during event dispatch to fetch log entries - */ - private boolean processQueuedFetches(IProgressMonitor monitor) { - if (fetches.isEmpty()) return false; - try { - // Now perform the fetching - Map projectMapping = getFetchesByProject(); - if (projectMapping.isEmpty()) return true; - LogEntryCache logEntriesCache = (LogEntryCache)cacheReference.get(); - if (logEntriesCache == null) { - logEntriesCache = new LogEntryCache(); - cacheReference = new SoftReference(logEntriesCache); - } - monitor.beginTask(CVSUIMessages.CVSChangeSetCollector_4, 100 * projectMapping.size()); - monitor.setTaskName(CVSUIMessages.CVSChangeSetCollector_4); - for (Iterator iter = projectMapping.values().iterator(); iter.hasNext();) { - SyncInfoSet set = (SyncInfoSet) iter.next(); - Policy.checkCanceled(monitor); - fetchLogEntries(logEntriesCache, set, Policy.subMonitorFor(monitor, 90)); - fireFetchedNotification(logEntriesCache, set, Policy.subMonitorFor(monitor, 10)); - } - } finally { - // Clear the fetches even if we were cancelled. - // Restarting will need to re-request all infos - fetches.clear(); - monitor.done(); - } - return true; - } + // Override to snure that queues by this handler are serialized + synchronized(queueLock) { + Job job = getEventHandlerJob(); + if (job.getState() == Job.NONE) { + job.setSystem(event.getType() != FETCH_REQUEST); + } + super.queueEvent(event, front); + } + } + + /* + * Method invoked during event dispatch to fetch log entries + */ + private boolean processQueuedFetches(IProgressMonitor monitor) { + if (fetches.isEmpty()) return false; + try { + // Now perform the fetching + Map projectMapping = getFetchesByProject(); + if (projectMapping.isEmpty()) return true; + LogEntryCache logEntriesCache = (LogEntryCache)cacheReference.get(); + if (logEntriesCache == null) { + logEntriesCache = new LogEntryCache(); + cacheReference = new SoftReference(logEntriesCache); + } + monitor.beginTask(CVSUIMessages.CVSChangeSetCollector_4, 100 * projectMapping.size()); + monitor.setTaskName(CVSUIMessages.CVSChangeSetCollector_4); + for (Iterator iter = projectMapping.values().iterator(); iter.hasNext();) { + SyncInfoSet set = (SyncInfoSet) iter.next(); + Policy.checkCanceled(monitor); + fetchLogEntries(logEntriesCache, set, Policy.subMonitorFor(monitor, 90)); + fireFetchedNotification(logEntriesCache, set, Policy.subMonitorFor(monitor, 10)); + } + } finally { + // Clear the fetches even if we were cancelled. + // Restarting will need to re-request all infos + fetches.clear(); + monitor.done(); + } + return true; + } - private void fireFetchedNotification(LogEntryCache logEntriesCache, SyncInfoSet set, IProgressMonitor monitor) { - if (listener != null) { - listener.logEntriesFetched(set, logEntriesCache, monitor); - } - } + private void fireFetchedNotification(LogEntryCache logEntriesCache, SyncInfoSet set, IProgressMonitor monitor) { + if (listener != null) { + listener.logEntriesFetched(set, logEntriesCache, monitor); + } + } - /* - * Return a map of IProject to SyncInfoSet as that is how entries are fetched. - * The set for each project includes all infos from the original set. - * This is one so that the completion notification contains all infos - * including those were a fetch was not required either because the - * entry was already cached or the resource has no history. - */ - private Map getFetchesByProject() { + /* + * Return a map of IProject to SyncInfoSet as that is how entries are fetched. + * The set for each project includes all infos from the original set. + * This is one so that the completion notification contains all infos + * including those were a fetch was not required either because the + * entry was already cached or the resource has no history. + */ + private Map getFetchesByProject() { Map<IProject, SyncInfoSet> result = new HashMap<>(); - for (Iterator iter = fetches.iterator(); iter.hasNext();) { - FetchRequest request = (FetchRequest) iter.next(); - SyncInfo[] infos = request.getInfos(); - for (int i = 0; i < infos.length; i++) { - SyncInfo info = infos[i]; - IProject project = info.getLocal().getProject(); - SyncInfoSet infoSet = result.get(project); - if (infoSet == null) { - infoSet = new SyncInfoSet(); - result.put(project, infoSet); - } - infoSet.add(info); - } - } - return result; - } + for (Iterator iter = fetches.iterator(); iter.hasNext();) { + FetchRequest request = (FetchRequest) iter.next(); + SyncInfo[] infos = request.getInfos(); + for (int i = 0; i < infos.length; i++) { + SyncInfo info = infos[i]; + IProject project = info.getLocal().getProject(); + SyncInfoSet infoSet = result.get(project); + if (infoSet == null) { + infoSet = new SyncInfoSet(); + result.put(project, infoSet); + } + infoSet.add(info); + } + } + return result; + } - private boolean isFetchRequired(SyncInfo info) { - // We only need to fetch if we don't have the log entry already - // and the change is a remote change - return info.getLocal().getType() == IResource.FILE && !isLogEntryCached(info) && isRemoteChange(info); - - } - + private boolean isFetchRequired(SyncInfo info) { + // We only need to fetch if we don't have the log entry already + // and the change is a remote change + return info.getLocal().getType() == IResource.FILE && !isLogEntryCached(info) && isRemoteChange(info); + + } + /* - * Return whether the given SyncInfo is cached. If there is - * an info for the resource that does not match the given info, - * it is removed and false is returned. - */ - private boolean isLogEntryCached(SyncInfo info) { - SyncInfo collectedInfo = collectedInfos.getSyncInfo(info.getLocal()); - if (collectedInfo != null && !collectedInfo.equals(info)) { - remove(collectedInfo); - collectedInfo = null; - } - return collectedInfo != null; - } + * Return whether the given SyncInfo is cached. If there is + * an info for the resource that does not match the given info, + * it is removed and false is returned. + */ + private boolean isLogEntryCached(SyncInfo info) { + SyncInfo collectedInfo = collectedInfos.getSyncInfo(info.getLocal()); + if (collectedInfo != null && !collectedInfo.equals(info)) { + remove(collectedInfo); + collectedInfo = null; + } + return collectedInfo != null; + } - /* + /* * Return if this sync info should be considered as part of a remote change * meaning that it can be placed inside an incoming commit set (i.e. the * set is determined using the comments from the log entry of the file). @@ -518,136 +518,136 @@ public class LogEntryCacheUpdateHandler extends BackgroundEventHandler { if (info.getRemote() != null) return true; ICVSFile file = CVSWorkspaceRoot.getCVSFileFor((IFile)info.getLocal()); try { - return file.getSyncBytes() != null; - } catch (CVSException e) { - // Log the error and exclude the file from consideration - CVSUIPlugin.log(e); - return false; - } - } - - /* - * Fetch the log entries for the info in the given set - */ - private void fetchLogEntries(LogEntryCache logEntriesCache, SyncInfoSet set, IProgressMonitor monitor) { - try { - if (subscriber instanceof CVSCompareSubscriber) { - CVSCompareSubscriber compareSubscriber = (CVSCompareSubscriber)subscriber; - fetchLogEntries(logEntriesCache, compareSubscriber, set, monitor); - } else { - // Run the log command once with no tags - fetchLogs(logEntriesCache, set, null, null, monitor); - } - } catch (CVSException e) { - handleException(e); - } catch (InterruptedException e) { - throw new OperationCanceledException(); - } - - } - - private void fetchLogEntries(LogEntryCache logEntriesCache, CVSCompareSubscriber compareSubscriber, SyncInfoSet set, IProgressMonitor monitor) throws CVSException, InterruptedException { - Map localTagMap = getLocalTagMap(set); - monitor.beginTask(null, 100 * localTagMap.size()); - for (Iterator iter = localTagMap.keySet().iterator(); iter.hasNext();) { - CVSTag localTag = (CVSTag) iter.next(); - fetchLogEntries(logEntriesCache, compareSubscriber, set, localTag, Policy.subMonitorFor(monitor, 100)); - } - Policy.checkCanceled(monitor); - monitor.done(); - } + return file.getSyncBytes() != null; + } catch (CVSException e) { + // Log the error and exclude the file from consideration + CVSUIPlugin.log(e); + return false; + } + } + + /* + * Fetch the log entries for the info in the given set + */ + private void fetchLogEntries(LogEntryCache logEntriesCache, SyncInfoSet set, IProgressMonitor monitor) { + try { + if (subscriber instanceof CVSCompareSubscriber) { + CVSCompareSubscriber compareSubscriber = (CVSCompareSubscriber)subscriber; + fetchLogEntries(logEntriesCache, compareSubscriber, set, monitor); + } else { + // Run the log command once with no tags + fetchLogs(logEntriesCache, set, null, null, monitor); + } + } catch (CVSException e) { + handleException(e); + } catch (InterruptedException e) { + throw new OperationCanceledException(); + } + + } + + private void fetchLogEntries(LogEntryCache logEntriesCache, CVSCompareSubscriber compareSubscriber, SyncInfoSet set, IProgressMonitor monitor) throws CVSException, InterruptedException { + Map localTagMap = getLocalTagMap(set); + monitor.beginTask(null, 100 * localTagMap.size()); + for (Iterator iter = localTagMap.keySet().iterator(); iter.hasNext();) { + CVSTag localTag = (CVSTag) iter.next(); + fetchLogEntries(logEntriesCache, compareSubscriber, set, localTag, Policy.subMonitorFor(monitor, 100)); + } + Policy.checkCanceled(monitor); + monitor.done(); + } - /* - * Return the resources grouped by the tag found in the - * workspace. The map is CVSTag->SyncInfoSet - */ - private Map getLocalTagMap(SyncInfoSet set) { + /* + * Return the resources grouped by the tag found in the + * workspace. The map is CVSTag->SyncInfoSet + */ + private Map getLocalTagMap(SyncInfoSet set) { Map<CVSTag, SyncInfoSet> result = new HashMap<>(); - for (Iterator iter = set.iterator(); iter.hasNext();) { - SyncInfo info = (SyncInfo) iter.next(); - CVSTag tag = getLocalTag(info); - SyncInfoSet tagSet = result.get(tag); - if (tagSet == null) { - tagSet = new SyncInfoSet(); - result.put(tag, tagSet); - } - tagSet.add(info); - } - return result; - } + for (Iterator iter = set.iterator(); iter.hasNext();) { + SyncInfo info = (SyncInfo) iter.next(); + CVSTag tag = getLocalTag(info); + SyncInfoSet tagSet = result.get(tag); + if (tagSet == null) { + tagSet = new SyncInfoSet(); + result.put(tag, tagSet); + } + tagSet.add(info); + } + return result; + } - private CVSTag getLocalTag(SyncInfo syncInfo) { + private CVSTag getLocalTag(SyncInfo syncInfo) { try { - IResource local = syncInfo.getLocal(); - ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(local); - CVSTag tag = null; - if(cvsResource.isFolder()) { - FolderSyncInfo info = ((ICVSFolder)cvsResource).getFolderSyncInfo(); - if(info != null) { - tag = info.getTag(); - } - if (tag != null && tag.getType() == CVSTag.BRANCH) { - tag = Util.getAccurateFolderTag(local, tag); - } - } else { - tag = CVSAction.getAccurateFileTag(cvsResource); - } - if(tag == null) { - tag = new CVSTag(); - } - return tag; - } catch (CVSException e) { - CVSUIPlugin.log(e); - return new CVSTag(); - } - } + IResource local = syncInfo.getLocal(); + ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(local); + CVSTag tag = null; + if(cvsResource.isFolder()) { + FolderSyncInfo info = ((ICVSFolder)cvsResource).getFolderSyncInfo(); + if(info != null) { + tag = info.getTag(); + } + if (tag != null && tag.getType() == CVSTag.BRANCH) { + tag = Util.getAccurateFolderTag(local, tag); + } + } else { + tag = CVSAction.getAccurateFileTag(cvsResource); + } + if(tag == null) { + tag = new CVSTag(); + } + return tag; + } catch (CVSException e) { + CVSUIPlugin.log(e); + return new CVSTag(); + } + } - private void fetchLogEntries(LogEntryCache logEntriesCache, CVSCompareSubscriber compareSubscriber, SyncInfoSet set, CVSTag localTag, IProgressMonitor monitor) throws CVSException, InterruptedException { - if (compareSubscriber.isMultipleTagComparison()) { - Map rootToInfoMap = getRootToInfoMap(compareSubscriber, set); - monitor.beginTask(null, 100 * rootToInfoMap.size()); - for (Iterator iterator = rootToInfoMap.keySet().iterator(); iterator.hasNext();) { - IResource root = (IResource) iterator.next(); - Policy.checkCanceled(monitor); - fetchLogs(logEntriesCache, set, localTag, compareSubscriber.getTag(root), Policy.subMonitorFor(monitor, 100)); - } - monitor.done(); - } else { - Policy.checkCanceled(monitor); - fetchLogs(logEntriesCache, set, localTag, compareSubscriber.getTag(), monitor); - } - } + private void fetchLogEntries(LogEntryCache logEntriesCache, CVSCompareSubscriber compareSubscriber, SyncInfoSet set, CVSTag localTag, IProgressMonitor monitor) throws CVSException, InterruptedException { + if (compareSubscriber.isMultipleTagComparison()) { + Map rootToInfoMap = getRootToInfoMap(compareSubscriber, set); + monitor.beginTask(null, 100 * rootToInfoMap.size()); + for (Iterator iterator = rootToInfoMap.keySet().iterator(); iterator.hasNext();) { + IResource root = (IResource) iterator.next(); + Policy.checkCanceled(monitor); + fetchLogs(logEntriesCache, set, localTag, compareSubscriber.getTag(root), Policy.subMonitorFor(monitor, 100)); + } + monitor.done(); + } else { + Policy.checkCanceled(monitor); + fetchLogs(logEntriesCache, set, localTag, compareSubscriber.getTag(), monitor); + } + } - private Map getRootToInfoMap(CVSCompareSubscriber compareSubscriber, SyncInfoSet set) { + private Map getRootToInfoMap(CVSCompareSubscriber compareSubscriber, SyncInfoSet set) { Map<IResource, SyncInfoSet> rootToInfosMap = new HashMap<>(); - IResource[] roots = compareSubscriber.roots(); - for (Iterator iter = set.iterator(); iter.hasNext();) { - SyncInfo info = (SyncInfo) iter.next(); - IPath localPath = info.getLocal().getFullPath(); - for (int j = 0; j < roots.length; j++) { - IResource resource = roots[j]; - if (resource.getFullPath().isPrefixOf(localPath)) { - SyncInfoSet infoList = rootToInfosMap.get(resource); - if (infoList == null) { - infoList = new SyncInfoSet(); - rootToInfosMap.put(resource, infoList); - } - infoList.add(info); - break; // out of inner loop - } - } - - } - return rootToInfosMap; - } + IResource[] roots = compareSubscriber.roots(); + for (Iterator iter = set.iterator(); iter.hasNext();) { + SyncInfo info = (SyncInfo) iter.next(); + IPath localPath = info.getLocal().getFullPath(); + for (int j = 0; j < roots.length; j++) { + IResource resource = roots[j]; + if (resource.getFullPath().isPrefixOf(localPath)) { + SyncInfoSet infoList = rootToInfosMap.get(resource); + if (infoList == null) { + infoList = new SyncInfoSet(); + rootToInfosMap.put(resource, infoList); + } + infoList.add(info); + break; // out of inner loop + } + } + + } + return rootToInfosMap; + } - private void fetchLogs(LogEntryCache logEntriesCache, SyncInfoSet set, CVSTag localTag, CVSTag remoteTag, IProgressMonitor monitor) throws CVSException, InterruptedException { - ICVSRemoteResource[] remoteResources = getRemotesToFetch(set.getSyncInfos()); - if (remoteResources.length > 0) { + private void fetchLogs(LogEntryCache logEntriesCache, SyncInfoSet set, CVSTag localTag, CVSTag remoteTag, IProgressMonitor monitor) throws CVSException, InterruptedException { + ICVSRemoteResource[] remoteResources = getRemotesToFetch(set.getSyncInfos()); + if (remoteResources.length > 0) { RemoteLogOperation logOperation = new RemoteLogOperation(getConfiguration().getSite().getPart(), remoteResources, localTag, remoteTag, logEntriesCache); logOperation.execute(monitor); - } - collectedInfos.addAll(set); + } + collectedInfos.addAll(set); } private ICVSRemoteResource[] getRemotesToFetch(SyncInfo[] infos) { @@ -664,14 +664,14 @@ public class LogEntryCacheUpdateHandler extends BackgroundEventHandler { return remotes.toArray(new ICVSRemoteResource[remotes.size()]); } - /** - * Stop any current fetch in process. - */ - public void stopFetching() { - try { - getEventHandlerJob().cancel(); - getEventHandlerJob().join(); - } catch (InterruptedException e) { - } - } + /** + * Stop any current fetch in process. + */ + public void stopFetching() { + try { + getEventHandlerJob().cancel(); + getEventHandlerJob().join(); + } catch (InterruptedException e) { + } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/MergeSynchronizeParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/MergeSynchronizeParticipant.java index e688683da..d8eeee466 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/MergeSynchronizeParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/MergeSynchronizeParticipant.java @@ -266,10 +266,10 @@ public class MergeSynchronizeParticipant extends CVSParticipant { protected String getShortTaskName() { return CVSUIMessages.Participant_merging; } - - @Override + + @Override protected CVSChangeSetCapability createChangeSetCapability() { - // See bug 84561 for a description of the problems with Merge Change Sets - return null; - } + // See bug 84561 for a description of the problems with Merge Change Sets + return null; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/OpenChangeSetAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/OpenChangeSetAction.java index 0973d88f7..c9a670084 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/OpenChangeSetAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/OpenChangeSetAction.java @@ -37,181 +37,181 @@ import com.ibm.icu.text.DateFormat; class OpenChangeSetAction extends SynchronizeModelAction { - protected OpenChangeSetAction(ISynchronizePageConfiguration configuration) { - super(CVSUIMessages.OpenCommitSetAction_20, configuration); - } - - @Override + protected OpenChangeSetAction(ISynchronizePageConfiguration configuration) { + super(CVSUIMessages.OpenCommitSetAction_20, configuration); + } + + @Override protected FastSyncInfoFilter getSyncInfoFilter() { - return new AndSyncInfoFilter(new FastSyncInfoFilter[] { - new FastSyncInfoFilter() { - @Override + return new AndSyncInfoFilter(new FastSyncInfoFilter[] { + new FastSyncInfoFilter() { + @Override public boolean select(SyncInfo info) { - return info.getLocal().getType() == IResource.FILE; - } - }, - new OrSyncInfoFilter(new FastSyncInfoFilter[] { - new SyncInfoDirectionFilter(new int[] { SyncInfo.INCOMING, SyncInfo.CONFLICTING }), - new FastSyncInfoFilter() { - @Override + return info.getLocal().getType() == IResource.FILE; + } + }, + new OrSyncInfoFilter(new FastSyncInfoFilter[] { + new SyncInfoDirectionFilter(new int[] { SyncInfo.INCOMING, SyncInfo.CONFLICTING }), + new FastSyncInfoFilter() { + @Override public boolean select(SyncInfo info) { - return !info.getComparator().isThreeWay(); - } - } - }) - }); - } - - private ChangeSet getChangeSet(IStructuredSelection selection) { - // First, check to see if a change set is selected directly - if (selection.size() == 1) { - Object o = selection.getFirstElement(); - if (o instanceof IAdaptable) { - ChangeSet set = ((IAdaptable)o).getAdapter(ChangeSet.class); - if (set != null) - return set; - } - } - // Failing that, check to see if all the selected elements and their childen are in the same change set - return getChangeSet(selection.toArray()); - } - - private ChangeSet getChangeSet(Object[] elements) { - ChangeSet foundSet = null; - for (int i = 0; i < elements.length; i++) { - Object object = elements[i]; - ChangeSet set = getChangeSet((ISynchronizeModelElement)object); - if (set == null) return null; - if (foundSet == null) { - foundSet = set; - } else if (foundSet != set) { - return null; - } - } - return foundSet; - } - - private ChangeSet getChangeSet(ISynchronizeModelElement element) { - if (element == null) return null; - if (element instanceof IAdaptable) { - ChangeSet set = ((IAdaptable)element).getAdapter(ChangeSet.class); - if (set != null) - return set; - } - return getChangeSet((ISynchronizeModelElement)element.getParent()); - } + return !info.getComparator().isThreeWay(); + } + } + }) + }); + } + + private ChangeSet getChangeSet(IStructuredSelection selection) { + // First, check to see if a change set is selected directly + if (selection.size() == 1) { + Object o = selection.getFirstElement(); + if (o instanceof IAdaptable) { + ChangeSet set = ((IAdaptable)o).getAdapter(ChangeSet.class); + if (set != null) + return set; + } + } + // Failing that, check to see if all the selected elements and their childen are in the same change set + return getChangeSet(selection.toArray()); + } + + private ChangeSet getChangeSet(Object[] elements) { + ChangeSet foundSet = null; + for (int i = 0; i < elements.length; i++) { + Object object = elements[i]; + ChangeSet set = getChangeSet((ISynchronizeModelElement)object); + if (set == null) return null; + if (foundSet == null) { + foundSet = set; + } else if (foundSet != set) { + return null; + } + } + return foundSet; + } + + private ChangeSet getChangeSet(ISynchronizeModelElement element) { + if (element == null) return null; + if (element instanceof IAdaptable) { + ChangeSet set = ((IAdaptable)element).getAdapter(ChangeSet.class); + if (set != null) + return set; + } + return getChangeSet((ISynchronizeModelElement)element.getParent()); + } - @Override + @Override protected boolean updateSelection(IStructuredSelection selection) { - boolean enabled = super.updateSelection(selection); - if (enabled) { - // The selection only contains appropriate files so - // only enable if the selection is contained within a single change set - ChangeSet set = getChangeSet(selection); - return set != null; - } - return false; - } + boolean enabled = super.updateSelection(selection); + if (enabled) { + // The selection only contains appropriate files so + // only enable if the selection is contained within a single change set + ChangeSet set = getChangeSet(selection); + return set != null; + } + return false; + } - @Override + @Override protected SynchronizeModelOperation getSubscriberOperation(ISynchronizePageConfiguration configuration, IDiffElement[] elements) { - return new SynchronizeModelOperation(configuration, elements) { - @Override + return new SynchronizeModelOperation(configuration, elements) { + @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - SyncInfoSet set = getSyncInfoSet(); - SyncInfo[] infos = set.getSyncInfos(); - if (infos.length > 0) { - ICVSRepositoryLocation location = getLocation(infos[0]); - if (location == null) { - handle(new CVSException(CVSUIMessages.OpenCommitSetAction_21)); - return; - } - CompareTreeBuilder builder = new CompareTreeBuilder(location, null, null); - if (buildTrees(builder, infos)) { - try { - builder.cacheContents(monitor); - builder.openCompareEditor(getConfiguration().getSite().getPart().getSite().getPage(), getCompareTitle(), getCompareToolTip()); - } catch (CVSException e) { - handle(e); - return; - } - } - } - } + SyncInfoSet set = getSyncInfoSet(); + SyncInfo[] infos = set.getSyncInfos(); + if (infos.length > 0) { + ICVSRepositoryLocation location = getLocation(infos[0]); + if (location == null) { + handle(new CVSException(CVSUIMessages.OpenCommitSetAction_21)); + return; + } + CompareTreeBuilder builder = new CompareTreeBuilder(location, null, null); + if (buildTrees(builder, infos)) { + try { + builder.cacheContents(monitor); + builder.openCompareEditor(getConfiguration().getSite().getPart().getSite().getPage(), getCompareTitle(), getCompareToolTip()); + } catch (CVSException e) { + handle(e); + return; + } + } + } + } - private String getCompareToolTip() { - IDiffElement[] elements = getSelectedDiffElements(); - for (int i = 0; i < elements.length; i++) { - IDiffElement element = elements[i]; - while (element != null) { - if (element instanceof ChangeSetDiffNode) { - return ((ChangeSetDiffNode)element).getName(); - } - element = element.getParent(); - } - } - return null; - } - - private String getCompareTitle() { - IDiffElement[] elements = getSelectedDiffElements(); - ChangeSet set = getChangeSet(elements); - if (set instanceof CheckedInChangeSet) { - CheckedInChangeSet cics = (CheckedInChangeSet)set; - String date = DateFormat.getDateTimeInstance().format(cics.getDate()); - return NLS.bind(CVSUIMessages.OpenChangeSetAction_0, new String[] {cics.getAuthor(), date}); - } - return CVSUIMessages.OpenChangeSetAction_1; - } + private String getCompareToolTip() { + IDiffElement[] elements = getSelectedDiffElements(); + for (int i = 0; i < elements.length; i++) { + IDiffElement element = elements[i]; + while (element != null) { + if (element instanceof ChangeSetDiffNode) { + return ((ChangeSetDiffNode)element).getName(); + } + element = element.getParent(); + } + } + return null; + } + + private String getCompareTitle() { + IDiffElement[] elements = getSelectedDiffElements(); + ChangeSet set = getChangeSet(elements); + if (set instanceof CheckedInChangeSet) { + CheckedInChangeSet cics = (CheckedInChangeSet)set; + String date = DateFormat.getDateTimeInstance().format(cics.getDate()); + return NLS.bind(CVSUIMessages.OpenChangeSetAction_0, new String[] {cics.getAuthor(), date}); + } + return CVSUIMessages.OpenChangeSetAction_1; + } - private ICVSRepositoryLocation getLocation(SyncInfo info) { - IResourceVariant remote = info.getRemote(); - if (remote == null) { - remote = info.getBase(); - } - if (remote != null) { - return ((ICVSRemoteResource)remote).getRepository(); - } - return null; - } + private ICVSRepositoryLocation getLocation(SyncInfo info) { + IResourceVariant remote = info.getRemote(); + if (remote == null) { + remote = info.getBase(); + } + if (remote != null) { + return ((ICVSRemoteResource)remote).getRepository(); + } + return null; + } - /* - * Build the trees that will be compared - */ - private boolean buildTrees(CompareTreeBuilder builder, SyncInfo[] infos) { - for (int i = 0; i < infos.length; i++) { - SyncInfo info = infos[i]; - IResourceVariant remote = info.getRemote(); - if (remote == null) { - IResourceVariant predecessor = info.getBase(); - if (predecessor instanceof ICVSRemoteFile) { - builder.addToTrees((ICVSRemoteFile)predecessor, null); - } - } else if (remote instanceof ICVSRemoteFile) { - try { - ICVSRemoteFile predecessor = getImmediatePredecessor(remote); - builder.addToTrees(predecessor, (ICVSRemoteFile)remote); - } catch (TeamException e) { - handle(e); - return false; - } - } - } - return true; - } - }; - } + /* + * Build the trees that will be compared + */ + private boolean buildTrees(CompareTreeBuilder builder, SyncInfo[] infos) { + for (int i = 0; i < infos.length; i++) { + SyncInfo info = infos[i]; + IResourceVariant remote = info.getRemote(); + if (remote == null) { + IResourceVariant predecessor = info.getBase(); + if (predecessor instanceof ICVSRemoteFile) { + builder.addToTrees((ICVSRemoteFile)predecessor, null); + } + } else if (remote instanceof ICVSRemoteFile) { + try { + ICVSRemoteFile predecessor = getImmediatePredecessor(remote); + builder.addToTrees(predecessor, (ICVSRemoteFile)remote); + } catch (TeamException e) { + handle(e); + return false; + } + } + } + return true; + } + }; + } - private ICVSRemoteFile getImmediatePredecessor(IResourceVariant remote) throws TeamException { - CVSChangeSetCollector changeSetCollector = getChangeSetCollector(); - if (changeSetCollector != null) { - return changeSetCollector.getImmediatePredecessor((ICVSRemoteFile)remote); - } - return null; - } + private ICVSRemoteFile getImmediatePredecessor(IResourceVariant remote) throws TeamException { + CVSChangeSetCollector changeSetCollector = getChangeSetCollector(); + if (changeSetCollector != null) { + return changeSetCollector.getImmediatePredecessor((ICVSRemoteFile)remote); + } + return null; + } - private CVSChangeSetCollector getChangeSetCollector() { - return (CVSChangeSetCollector)getConfiguration().getProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR); - } + private CVSChangeSetCollector getChangeSetCollector() { + return (CVSChangeSetCollector)getConfiguration().getProperty(CVSChangeSetCollector.CVS_CHECKED_IN_COLLECTOR); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/RefreshDirtyStateOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/RefreshDirtyStateOperation.java index 284a1923b..c12a06936 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/RefreshDirtyStateOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/RefreshDirtyStateOperation.java @@ -50,15 +50,15 @@ public class RefreshDirtyStateOperation extends CVSSubscriberOperation { protected void runWithProjectRule(IProject project, SyncInfoSet set, IProgressMonitor monitor) throws TeamException { final SyncInfo[] infos = set.getSyncInfos(); if (infos.length == 0) return; - monitor.beginTask(null, 200); - ensureBaseContentsCached(project, infos, Policy.subMonitorFor(monitor, 100)); - performCleanTimestamps(project, infos, monitor); - monitor.done(); + monitor.beginTask(null, 200); + ensureBaseContentsCached(project, infos, Policy.subMonitorFor(monitor, 100)); + performCleanTimestamps(project, infos, monitor); + monitor.done(); } private void performCleanTimestamps(IProject project, final SyncInfo[] infos, IProgressMonitor monitor) throws CVSException { ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project); - final ContentComparisonSyncInfoFilter comparator = new SyncInfoFilter.ContentComparisonSyncInfoFilter(false); + final ContentComparisonSyncInfoFilter comparator = new SyncInfoFilter.ContentComparisonSyncInfoFilter(false); folder.run(monitor1 -> { monitor1.beginTask(null, infos.length * 100); for (int i = 0; i < infos.length; i++) { @@ -116,9 +116,9 @@ public class RefreshDirtyStateOperation extends CVSSubscriberOperation { } catch (InterruptedException e) { throw new OperationCanceledException(); } - } - - @Override + } + + @Override protected String getErrorTitle() { return CVSUIMessages.RefreshDirtyStateOperation_0; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitAction.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitAction.java index 949518018..67f774500 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitAction.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitAction.java @@ -50,34 +50,34 @@ public class WorkspaceCommitAction extends CVSParticipantAction { protected SynchronizeModelOperation getSubscriberOperation(ISynchronizePageConfiguration configuration, IDiffElement[] elements) { return new WorkspaceCommitOperation(configuration, elements, false /* override */); } - - @Override + + @Override public void runOperation() { - final SyncInfoSet set = getSyncInfoSet(); - final Shell shell= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); - try { - // Include the subscriber operation as a job listener so that the busy feedback for the - // commit will appear in the synchronize view - CommitWizard.run(shell, set, getSubscriberOperation(getConfiguration(), getFilteredDiffElements())); - } catch (CVSException e) { - CVSUIPlugin.log(e); - } - } + final SyncInfoSet set = getSyncInfoSet(); + final Shell shell= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + try { + // Include the subscriber operation as a job listener so that the busy feedback for the + // commit will appear in the synchronize view + CommitWizard.run(shell, set, getSubscriberOperation(getConfiguration(), getFilteredDiffElements())); + } catch (CVSException e) { + CVSUIPlugin.log(e); + } + } - /* - * Return the selected SyncInfo for which this action is enabled. - * - * @return the selected SyncInfo for which this action is enabled. - */ - private SyncInfoSet getSyncInfoSet() { - IDiffElement [] elements= getFilteredDiffElements(); - SyncInfoSet filtered = new SyncInfoSet(); - for (int i = 0; i < elements.length; i++) { - IDiffElement e = elements[i]; - if (e instanceof SyncInfoModelElement) { - filtered.add(((SyncInfoModelElement)e).getSyncInfo()); - } - } - return filtered; - } + /* + * Return the selected SyncInfo for which this action is enabled. + * + * @return the selected SyncInfo for which this action is enabled. + */ + private SyncInfoSet getSyncInfoSet() { + IDiffElement [] elements= getFilteredDiffElements(); + SyncInfoSet filtered = new SyncInfoSet(); + for (int i = 0; i < elements.length; i++) { + IDiffElement e = elements[i]; + if (e instanceof SyncInfoModelElement) { + filtered.add(((SyncInfoModelElement)e).getSyncInfo()); + } + } + return filtered; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitOperation.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitOperation.java index 1cb5b6796..87dd5dcc2 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitOperation.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceCommitOperation.java @@ -270,37 +270,37 @@ public class WorkspaceCommitOperation extends CVSSubscriberOperation { * @return the comment, or null to cancel */ protected String promptForComment(RepositoryManager manager, IResource[] resourcesToCommit) { - String proposedComment = getProposedComment(resourcesToCommit); + String proposedComment = getProposedComment(resourcesToCommit); return manager.promptForComment(getShell(), resourcesToCommit, proposedComment); } - private String getProposedComment(IResource[] resourcesToCommit) { - StringBuffer comment = new StringBuffer(); - ChangeSet[] sets = CVSUIPlugin.getPlugin().getChangeSetManager().getSets(); - Arrays.sort(sets, new ChangeSetComparator()); - int numMatchedSets = 0; - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (containsOne(set, resourcesToCommit)) { - if(numMatchedSets > 0) comment.append(System.getProperty("line.separator")); //$NON-NLS-1$ - comment.append(set.getComment()); - numMatchedSets++; - } - } - return comment.toString(); - } - - private boolean containsOne(ChangeSet set, IResource[] resourcesToCommit) { - for (int j = 0; j < resourcesToCommit.length; j++) { - IResource resource = resourcesToCommit[j]; - if (set.contains(resource)) { - return true; - } - } - return false; - } + private String getProposedComment(IResource[] resourcesToCommit) { + StringBuffer comment = new StringBuffer(); + ChangeSet[] sets = CVSUIPlugin.getPlugin().getChangeSetManager().getSets(); + Arrays.sort(sets, new ChangeSetComparator()); + int numMatchedSets = 0; + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (containsOne(set, resourcesToCommit)) { + if(numMatchedSets > 0) comment.append(System.getProperty("line.separator")); //$NON-NLS-1$ + comment.append(set.getComment()); + numMatchedSets++; + } + } + return comment.toString(); + } + + private boolean containsOne(ChangeSet set, IResource[] resourcesToCommit) { + for (int j = 0; j < resourcesToCommit.length; j++) { + IResource resource = resourcesToCommit[j]; + if (set.contains(resource)) { + return true; + } + } + return false; + } - protected IResource[] promptForResourcesToBeAdded(RepositoryManager manager, IResource[] unadded) { + protected IResource[] promptForResourcesToBeAdded(RepositoryManager manager, IResource[] unadded) { return manager.promptForResourcesToBeAdded(getShell(), unadded); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceSynchronizeParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceSynchronizeParticipant.java index ec699627e..e0f53fc75 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceSynchronizeParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/subscriber/WorkspaceSynchronizeParticipant.java @@ -55,7 +55,7 @@ public class WorkspaceSynchronizeParticipant extends ScopableSubscriberParticipa public static final String CONTEXT_MENU_CONTRIBUTION_GROUP_3 = "context_group_3"; //$NON-NLS-1$ public static final String CONTEXT_MENU_CONTRIBUTION_GROUP_4 = "context_group_4"; //$NON-NLS-1$ - private WorkspaceChangeSetCapability capability; + private WorkspaceChangeSetCapability capability; /** * CVS workspace action contribution @@ -145,39 +145,39 @@ public class WorkspaceSynchronizeParticipant extends ScopableSubscriberParticipa } public class WorkspaceChangeSetCapability extends CVSChangeSetCapability { - @Override + @Override public ActiveChangeSet createChangeSet(ISynchronizePageConfiguration configuration, IDiff[] infos) { - ActiveChangeSet set = getActiveChangeSetManager().createSet(CVSUIMessages.WorkspaceChangeSetCapability_1, new IDiff[0]); + ActiveChangeSet set = getActiveChangeSetManager().createSet(CVSUIMessages.WorkspaceChangeSetCapability_1, new IDiff[0]); CommitSetDialog dialog = new CommitSetDialog(configuration.getSite().getShell(), set, getResources(infos), CommitSetDialog.NEW); dialog.open(); if (dialog.getReturnCode() != Window.OK) return null; set.add(infos); return set; - } + } - private IResource[] getResources(IDiff[] diffs) { + private IResource[] getResources(IDiff[] diffs) { Set<IResource> result = new HashSet<>(); - for (int i = 0; i < diffs.length; i++) { + for (int i = 0; i < diffs.length; i++) { IDiff diff = diffs[i]; IResource resource = ResourceDiffTree.getResourceFor(diff); if (resource != null) result.add(resource); } - return result.toArray(new IResource[result.size()]); - } - - @Override + return result.toArray(new IResource[result.size()]); + } + + @Override public void editChangeSet(ISynchronizePageConfiguration configuration, ActiveChangeSet set) { - CommitSetDialog dialog = new CommitSetDialog(configuration.getSite().getShell(), set, set.getResources(), CommitSetDialog.EDIT); + CommitSetDialog dialog = new CommitSetDialog(configuration.getSite().getShell(), set, set.getResources(), CommitSetDialog.EDIT); dialog.open(); if (dialog.getReturnCode() != Window.OK) return; // Nothing to do here as the set was updated by the dialog - } + } - @Override + @Override public ActiveChangeSetManager getActiveChangeSetManager() { - return CVSUIPlugin.getPlugin().getChangeSetManager(); - } + return CVSUIPlugin.getPlugin().getChangeSetManager(); + } } /** @@ -285,7 +285,7 @@ public class WorkspaceSynchronizeParticipant extends ScopableSubscriberParticipa } protected ILabelDecorator getLabelDecorator(ISynchronizePageConfiguration configuration) { - return new CVSParticipantLabelDecorator(configuration); + return new CVSParticipantLabelDecorator(configuration); } @Override @@ -293,36 +293,36 @@ public class WorkspaceSynchronizeParticipant extends ScopableSubscriberParticipa return TeamUI.getSynchronizeManager().getParticipantDescriptor(ID); } - @Override + @Override public void prepareCompareInput(ISynchronizeModelElement element, CompareConfiguration config, IProgressMonitor monitor) throws TeamException { - monitor.beginTask(null, 100); - CVSParticipant.deriveBaseContentsFromLocal(element, Policy.subMonitorFor(monitor, 10)); - super.prepareCompareInput(element, config, Policy.subMonitorFor(monitor, 80)); - CVSParticipant.updateLabelsForCVS(element, config, Policy.subMonitorFor(monitor, 10)); - monitor.done(); - } - - @Override + monitor.beginTask(null, 100); + CVSParticipant.deriveBaseContentsFromLocal(element, Policy.subMonitorFor(monitor, 10)); + super.prepareCompareInput(element, config, Policy.subMonitorFor(monitor, 80)); + CVSParticipant.updateLabelsForCVS(element, config, Policy.subMonitorFor(monitor, 10)); + monitor.done(); + } + + @Override public PreferencePage[] getPreferencePages() { - return CVSParticipant.addCVSPreferencePages(super.getPreferencePages()); - } - - @Override + return CVSParticipant.addCVSPreferencePages(super.getPreferencePages()); + } + + @Override public ChangeSetCapability getChangeSetCapability() { - if (capability == null) { - capability = new WorkspaceChangeSetCapability(); - } - return capability; - } - - @Override + if (capability == null) { + capability = new WorkspaceChangeSetCapability(); + } + return capability; + } + + @Override protected boolean isViewerContributionsSupported() { - return true; - } + return true; + } - public void refresh(IResource[] resources, IWorkbenchPartSite site) { - refresh(resources, getShortTaskName(), getLongTaskName(resources), site); - } + public void refresh(IResource[] resources, IWorkbenchPartSite site) { + refresh(resources, getShortTaskName(), getLongTaskName(resources), site); + } @Override public void dispose() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/BranchPromptDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/BranchPromptDialog.java index 3ba1123d6..a75a77502 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/BranchPromptDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/BranchPromptDialog.java @@ -44,13 +44,13 @@ public class BranchPromptDialog extends DetailsDialog { private static final int TAG_AREA_HEIGHT_HINT = 200; // widgets; - private TagSource tagSource; - private TagSelectionArea tagArea; - private final IResource[] resources; + private TagSource tagSource; + private TagSelectionArea tagArea; + private final IResource[] resources; public BranchPromptDialog(Shell parentShell, String title, IResource[] resources, boolean allResourcesSticky, String versionName) { super(parentShell, title); - this.resources = resources; + this.resources = resources; this.tagSource = TagSource.create(resources); this.allStickyResources = allResourcesSticky; this.versionName = versionName; @@ -62,14 +62,14 @@ public class BranchPromptDialog extends DetailsDialog { applyDialogFont(composite); initializeDialogUnits(composite); - final int areaWidth= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); - - final Label description= SWTUtils.createLabel(composite, allStickyResources ? CVSUIMessages.BranchWizardPage_pageDescriptionVersion : CVSUIMessages.BranchWizardPage_pageDescription); - description.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); - + final int areaWidth= convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); + + final Label description= SWTUtils.createLabel(composite, allStickyResources ? CVSUIMessages.BranchWizardPage_pageDescriptionVersion : CVSUIMessages.BranchWizardPage_pageDescription); + description.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); + final Label name= SWTUtils.createLabel(composite, CVSUIMessages.BranchWizardPage_branchName); - name.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); - + name.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); + branchText = CVSWizardPage.createTextField(composite); branchText.addListener(SWT.Modify, event -> { branchTag = branchText.getText(); @@ -84,11 +84,11 @@ public class BranchPromptDialog extends DetailsDialog { update = true; final Label versionLabel1= SWTUtils.createLabel(composite, CVSUIMessages.BranchWizardPage_specifyVersion); - versionLabel1.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); + versionLabel1.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); final Label versionLabel2= SWTUtils.createLabel(composite, CVSUIMessages.BranchWizardPage_versionName); versionLabel2.setLayoutData(SWTUtils.createGridData(areaWidth, SWT.DEFAULT, true, false)); - + versionText = CVSWizardPage.createTextField(composite); versionText.addListener(SWT.Modify, event -> { versionTag = versionText.getText(); @@ -104,21 +104,21 @@ public class BranchPromptDialog extends DetailsDialog { branchText.setFocus(); } - @Override + @Override protected String getHelpContextId() { - return IHelpContextIds.BRANCH_DIALOG; - } - private void addBranchContentAssist() { - TagSource projectTagSource = LocalProjectTagSource.create(getSeedProject()); - if (projectTagSource != null) - TagContentAssistProcessor.createContentAssistant(branchText, projectTagSource, TagSelectionArea.INCLUDE_BRANCHES); - } + return IHelpContextIds.BRANCH_DIALOG; + } + private void addBranchContentAssist() { + TagSource projectTagSource = LocalProjectTagSource.create(getSeedProject()); + if (projectTagSource != null) + TagContentAssistProcessor.createContentAssistant(branchText, projectTagSource, TagSelectionArea.INCLUDE_BRANCHES); + } - private IProject getSeedProject() { - return resources[0].getProject(); - } + private IProject getSeedProject() { + return resources[0].getProject(); + } - /** + /** * Updates version name */ protected void updateVersionName(String branchName) { @@ -198,9 +198,9 @@ public class BranchPromptDialog extends DetailsDialog { return update; } - @Override + @Override protected boolean isMainGrabVertical() { - return false; - } + return false; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/FilteredTagList.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/FilteredTagList.java index de826969e..1669f2c5e 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/FilteredTagList.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/FilteredTagList.java @@ -27,75 +27,75 @@ import org.eclipse.ui.model.IWorkbenchAdapter; */ public class FilteredTagList implements IWorkbenchAdapter, IAdaptable { - private final TagSource tagSource; - private final int[] types; - private StringMatcher matcher; + private final TagSource tagSource; + private final int[] types; + private StringMatcher matcher; - public FilteredTagList(TagSource tagSource, int[] types) { - this.tagSource = tagSource; - this.types = types; - } - - @Override + public FilteredTagList(TagSource tagSource, int[] types) { + this.tagSource = tagSource; + this.types = types; + } + + @Override public Object[] getChildren(Object o) { - CVSTag[] tags = getTags(); + CVSTag[] tags = getTags(); List<TagElement> filtered = new ArrayList<>(); - for (int i = 0; i < tags.length; i++) { - CVSTag tag = tags[i]; - if (select(tag)) { - filtered.add(new TagElement(this, tag)); - } - } - return filtered.toArray(new Object[filtered.size()]); - } + for (int i = 0; i < tags.length; i++) { + CVSTag tag = tags[i]; + if (select(tag)) { + filtered.add(new TagElement(this, tag)); + } + } + return filtered.toArray(new Object[filtered.size()]); + } - private boolean select(CVSTag tag) { - if (matcher == null) return true; - return matcher.match(tag.getName()); - } + private boolean select(CVSTag tag) { + if (matcher == null) return true; + return matcher.match(tag.getName()); + } - private CVSTag[] getTags() { - return tagSource.getTags(types); - } + private CVSTag[] getTags() { + return tagSource.getTags(types); + } - @Override + @Override public ImageDescriptor getImageDescriptor(Object object) { - return null; - } + return null; + } - @Override + @Override public String getLabel(Object o) { - return null; - } + return null; + } - @Override + @Override public Object getParent(Object o) { - return null; - } + return null; + } - @Override + @Override public <T> T getAdapter(Class<T> adapter) { if (adapter == IWorkbenchAdapter.class) return adapter.cast(this); return null; - } - - public void setPattern(String pattern) { - if (!pattern.endsWith("*")) { //$NON-NLS-1$ - pattern += "*"; //$NON-NLS-1$ - } - matcher = new StringMatcher(pattern, true, false); - } + } + + public void setPattern(String pattern) { + if (!pattern.endsWith("*")) { //$NON-NLS-1$ + pattern += "*"; //$NON-NLS-1$ + } + matcher = new StringMatcher(pattern, true, false); + } - public CVSTag[] getMatchingTags() { - CVSTag[] tags = getTags(); + public CVSTag[] getMatchingTags() { + CVSTag[] tags = getTags(); List<CVSTag> filtered = new ArrayList<>(); - for (int i = 0; i < tags.length; i++) { - CVSTag tag = tags[i]; - if (select(tag)) { - filtered.add(tag); - } - } - return filtered.toArray(new CVSTag[filtered.size()]); - } + for (int i = 0; i < tags.length; i++) { + CVSTag tag = tags[i]; + if (select(tag)) { + filtered.add(tag); + } + } + return filtered.toArray(new CVSTag[filtered.size()]); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/LocalProjectTagSource.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/LocalProjectTagSource.java index efc2e6e90..b679a7530 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/LocalProjectTagSource.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/LocalProjectTagSource.java @@ -30,96 +30,96 @@ import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin; * Tag source that gets its tags from the projects exist in the workspace */ public class LocalProjectTagSource extends TagSource { - - public static TagSource create(IProject seedProject) { - try { - ICVSRemoteFolder seedFolder = ((ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(seedProject)); - ICVSRemoteFolder[] remoteFolders = getProjectRemoteFolders(); - if (remoteFolders.length == 1) { - // There are no other projects to get tags from so return null - return null; - } - return new LocalProjectTagSource(seedFolder, remoteFolders); - } catch (CVSException e) { - // Log and return null - CVSUIPlugin.log(e); - return null; - } - } - - private ICVSRemoteFolder seedFolder; - private ICVSRemoteFolder[] remoteFolders; + + public static TagSource create(IProject seedProject) { + try { + ICVSRemoteFolder seedFolder = ((ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(seedProject)); + ICVSRemoteFolder[] remoteFolders = getProjectRemoteFolders(); + if (remoteFolders.length == 1) { + // There are no other projects to get tags from so return null + return null; + } + return new LocalProjectTagSource(seedFolder, remoteFolders); + } catch (CVSException e) { + // Log and return null + CVSUIPlugin.log(e); + return null; + } + } + + private ICVSRemoteFolder seedFolder; + private ICVSRemoteFolder[] remoteFolders; - private LocalProjectTagSource(ICVSRemoteFolder seedFolder, ICVSRemoteFolder[] remoteFolders) { - this.seedFolder = seedFolder; - this.remoteFolders = remoteFolders; - } + private LocalProjectTagSource(ICVSRemoteFolder seedFolder, ICVSRemoteFolder[] remoteFolders) { + this.seedFolder = seedFolder; + this.remoteFolders = remoteFolders; + } - /* - * Return the list of remote folders for the projects in the workspace mapped to the given repository - */ - private static ICVSRemoteFolder[] getProjectRemoteFolders() { - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); + /* + * Return the list of remote folders for the projects in the workspace mapped to the given repository + */ + private static ICVSRemoteFolder[] getProjectRemoteFolders() { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); List<ICVSRemoteFolder> result = new ArrayList<>(); - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - try { - if (project.isAccessible() && RepositoryProvider.isShared(project)) { - ICVSRemoteFolder remote = (ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(project); - if (remote != null) { - result.add(remote); - } - } - } catch (CVSException e) { - // Log and continue - CVSUIPlugin.log(e); - } - } - return result.toArray(new ICVSRemoteFolder[result.size()]); - } + for (int i = 0; i < projects.length; i++) { + IProject project = projects[i]; + try { + if (project.isAccessible() && RepositoryProvider.isShared(project)) { + ICVSRemoteFolder remote = (ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(project); + if (remote != null) { + result.add(remote); + } + } + } catch (CVSException e) { + // Log and continue + CVSUIPlugin.log(e); + } + } + return result.toArray(new ICVSRemoteFolder[result.size()]); + } - @Override + @Override public CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException { - // This tag source should not be refreshed - return new CVSTag[0]; - } + // This tag source should not be refreshed + return new CVSTag[0]; + } - @Override + @Override public ICVSRepositoryLocation getLocation() { - return seedFolder.getRepository(); - } + return seedFolder.getRepository(); + } - @Override + @Override public String getShortDescription() { - return NLS.bind(CVSUIMessages.LocalProjectTagSource_0, new String[] { Integer.toString(remoteFolders.length) }); - } + return NLS.bind(CVSUIMessages.LocalProjectTagSource_0, new String[] { Integer.toString(remoteFolders.length) }); + } - @Override + @Override public void commit(CVSTag[] tags, boolean replace, IProgressMonitor monitor) throws CVSException { - // Does not commit tags - } + // Does not commit tags + } - @Override + @Override public ICVSResource[] getCVSResources() { - return remoteFolders; - } - - @Override + return remoteFolders; + } + + @Override public CVSTag[] getTags(int type) { - if (type == CVSTag.HEAD || type == BASE) { - return super.getTags(type); - } - // Accumulate the tags for all folders + if (type == CVSTag.HEAD || type == BASE) { + return super.getTags(type); + } + // Accumulate the tags for all folders Set<CVSTag> allTags = new HashSet<>(); - for (int i = 0; i < remoteFolders.length; i++) { - ICVSRemoteFolder folder = remoteFolders[i]; - CVSTag[] tags = SingleFolderTagSource.getTags(folder, type); - allTags.addAll(Arrays.asList(tags)); - } - // Exclude the tags for the seedFolder - CVSTag[] tags = SingleFolderTagSource.getTags(seedFolder, type); - allTags.removeAll(Arrays.asList(tags)); - return allTags.toArray(new CVSTag[allTags.size()]); - } + for (int i = 0; i < remoteFolders.length; i++) { + ICVSRemoteFolder folder = remoteFolders[i]; + CVSTag[] tags = SingleFolderTagSource.getTags(folder, type); + allTags.addAll(Arrays.asList(tags)); + } + // Exclude the tags for the seedFolder + CVSTag[] tags = SingleFolderTagSource.getTags(seedFolder, type); + allTags.removeAll(Arrays.asList(tags)); + return allTags.toArray(new CVSTag[allTags.size()]); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/MultiFolderTagSource.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/MultiFolderTagSource.java index 393e4265e..6fd4f1600 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/MultiFolderTagSource.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/MultiFolderTagSource.java @@ -32,57 +32,57 @@ import org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager; */ public class MultiFolderTagSource extends SingleFolderTagSource { - private final ICVSFolder[] folders; + private final ICVSFolder[] folders; - /* package */ MultiFolderTagSource(ICVSFolder[] folders) { - super(folders[0]); - this.folders = folders; - } - - @Override + /* package */ MultiFolderTagSource(ICVSFolder[] folders) { + super(folders[0]); + this.folders = folders; + } + + @Override public String getShortDescription() { - return NLS.bind(CVSUIMessages.MultiFolderTagSource_0, new String[] { Integer.toString(folders.length) }); - } - - @Override + return NLS.bind(CVSUIMessages.MultiFolderTagSource_0, new String[] { Integer.toString(folders.length) }); + } + + @Override public CVSTag[] getTags(int type) { - if (type == CVSTag.HEAD || type == BASE) { - return super.getTags(type); - } + if (type == CVSTag.HEAD || type == BASE) { + return super.getTags(type); + } Set<CVSTag> tags = new HashSet<>(); - for (int i= 0; i < folders.length; i++) { + for (int i= 0; i < folders.length; i++) { tags.addAll(Arrays.asList(getTags(folders[i], type))); } - return tags.toArray(new CVSTag[tags.size()]); - } - - @Override + return tags.toArray(new CVSTag[tags.size()]); + } + + @Override public CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException { monitor.beginTask("", folders.length); //$NON-NLS-1$ Set<CVSTag> result = new HashSet<>(); - for (int i= 0; i < folders.length; i++) { + for (int i= 0; i < folders.length; i++) { ICVSFolder folder= folders[i]; CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager().refreshDefinedTags(folder, bestEffort /* recurse */, true /* notify */, Policy.subMonitorFor(monitor, 1)); result.addAll(Arrays.asList(tags)); } - monitor.done(); - fireChange(); - return result.toArray(new CVSTag[result.size()]); - } - - @Override + monitor.done(); + fireChange(); + return result.toArray(new CVSTag[result.size()]); + } + + @Override public ICVSResource[] getCVSResources() { - return folders; - } - - public ICVSFolder[] getFolders(){ - return folders; - } - - @Override + return folders; + } + + public ICVSFolder[] getFolders(){ + return folders; + } + + @Override public void commit(final CVSTag[] tags, final boolean replace, IProgressMonitor monitor) throws CVSException { try { - final RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager(); + final RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager(); manager.run(monitor1 -> { try { ICVSFolder[] folders = getFolders(); @@ -97,11 +97,11 @@ public class MultiFolderTagSource extends SingleFolderTagSource { throw new InvocationTargetException(e); } }, monitor); - } catch (InvocationTargetException e) { - throw CVSException.wrapException(e); - } catch (InterruptedException e) { - // Ignore - } - fireChange(); - } + } catch (InvocationTargetException e) { + throw CVSException.wrapException(e); + } catch (InterruptedException e) { + // Ignore + } + fireChange(); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFileTagSource.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFileTagSource.java index 42b58e19d..a469a84b7 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFileTagSource.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFileTagSource.java @@ -26,7 +26,7 @@ import org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager; * A tag source for a single ICVSFile */ public class SingleFileTagSource extends TagSource { - + public static CVSTag[] fetchTagsFor(ICVSFile file, IProgressMonitor monitor) throws TeamException { Set<CVSTag> tagSet = new HashSet<>(); ILogEntry[] entries = file.getLogEntries(monitor); @@ -39,51 +39,51 @@ public class SingleFileTagSource extends TagSource { return tagSet.toArray(new CVSTag[tagSet.size()]); } - private ICVSFile file; - private TagSource parentFolderTagSource; - - /* package */ /** - * - */ - public SingleFileTagSource(ICVSFile file) { - this.file = file; - parentFolderTagSource = TagSource.create(new ICVSResource[] { file.getParent() }); - } + private ICVSFile file; + private TagSource parentFolderTagSource; + + /* package */ /** + * + */ + public SingleFileTagSource(ICVSFile file) { + this.file = file; + parentFolderTagSource = TagSource.create(new ICVSResource[] { file.getParent() }); + } - @Override + @Override public CVSTag[] getTags(int type) { - return parentFolderTagSource.getTags(type); - } + return parentFolderTagSource.getTags(type); + } - @Override + @Override public CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException { - CVSTag[] tags = fetchTagsFor(file, monitor); - commit(tags, false, monitor); - fireChange(); - return tags; - } + CVSTag[] tags = fetchTagsFor(file, monitor); + commit(tags, false, monitor); + fireChange(); + return tags; + } - @Override + @Override public ICVSRepositoryLocation getLocation() { RepositoryManager mgr = CVSUIPlugin.getPlugin().getRepositoryManager(); ICVSRepositoryLocation location = mgr.getRepositoryLocationFor(file); return location; - } + } - @Override + @Override public String getShortDescription() { - return file.getName(); - } + return file.getName(); + } - @Override + @Override public void commit(CVSTag[] tags, boolean replace, IProgressMonitor monitor) throws CVSException { - parentFolderTagSource.commit(tags, replace, monitor); - fireChange(); - } + parentFolderTagSource.commit(tags, replace, monitor); + fireChange(); + } - @Override + @Override public ICVSResource[] getCVSResources() { - return new ICVSResource[] { file }; - } + return new ICVSResource[] { file }; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFolderTagSource.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFolderTagSource.java index 330ea088f..e9d17f13d 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFolderTagSource.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/SingleFolderTagSource.java @@ -28,57 +28,57 @@ import org.eclipse.ui.PlatformUI; */ public class SingleFolderTagSource extends TagSource { - public static CVSTag[] getTags(ICVSFolder folder, int type) { - if (type == CVSTag.HEAD) - return new CVSTag[] { CVSTag.DEFAULT } ; - return CVSUIPlugin.getPlugin().getRepositoryManager().getKnownTags(folder, type); - } - - private ICVSFolder folder; - - /* package */ SingleFolderTagSource(ICVSFolder folder) { - this.folder = folder; - } + public static CVSTag[] getTags(ICVSFolder folder, int type) { + if (type == CVSTag.HEAD) + return new CVSTag[] { CVSTag.DEFAULT } ; + return CVSUIPlugin.getPlugin().getRepositoryManager().getKnownTags(folder, type); + } + + private ICVSFolder folder; + + /* package */ SingleFolderTagSource(ICVSFolder folder) { + this.folder = folder; + } - @Override + @Override public CVSTag[] getTags(int type) { - if (type == CVSTag.HEAD || type == BASE) { - return super.getTags(type); - } - return getTags(getFolder(), type); - } + if (type == CVSTag.HEAD || type == BASE) { + return super.getTags(type); + } + return getTags(getFolder(), type); + } - /** - * Return the folder the tags are obtained from - * @return the folder the tags are obtained from - */ - public ICVSFolder getFolder() { - return folder; - } + /** + * Return the folder the tags are obtained from + * @return the folder the tags are obtained from + */ + public ICVSFolder getFolder() { + return folder; + } - @Override + @Override public CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException { - CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager().refreshDefinedTags(getFolder(), bestEffort /* recurse */, true /* notify */, monitor); - fireChange(); - return tags; - } + CVSTag[] tags = CVSUIPlugin.getPlugin().getRepositoryManager().refreshDefinedTags(getFolder(), bestEffort /* recurse */, true /* notify */, monitor); + fireChange(); + return tags; + } - @Override + @Override public ICVSRepositoryLocation getLocation() { RepositoryManager mgr = CVSUIPlugin.getPlugin().getRepositoryManager(); ICVSRepositoryLocation location = mgr.getRepositoryLocationFor(getFolder()); return location; - } + } - @Override + @Override public String getShortDescription() { - return getFolder().getName(); - } + return getFolder().getName(); + } - @Override + @Override public void commit(final CVSTag[] tags, final boolean replace, IProgressMonitor monitor) throws CVSException { try { - final RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager(); + final RepositoryManager manager = CVSUIPlugin.getPlugin().getRepositoryManager(); manager.run(monitor1 -> { try { ICVSFolder folder = getFolder(); @@ -91,17 +91,17 @@ public class SingleFolderTagSource extends TagSource { throw new InvocationTargetException(e); } }, monitor); - } catch (InvocationTargetException e) { - throw CVSException.wrapException(e); - } catch (InterruptedException e) { - // Ignore - } - fireChange(); - } + } catch (InvocationTargetException e) { + throw CVSException.wrapException(e); + } catch (InterruptedException e) { + // Ignore + } + fireChange(); + } - @Override + @Override public ICVSResource[] getCVSResources() { - final ICVSResource[][] resources = new ICVSResource[][] { null }; + final ICVSResource[][] resources = new ICVSResource[][] { null }; try { getRunnableContext().run(true, true, monitor -> { try { @@ -112,17 +112,17 @@ public class SingleFolderTagSource extends TagSource { monitor.done(); } }); - return resources[0]; - } catch (InvocationTargetException e) { - CVSUIPlugin.log(CVSException.wrapException(e)); - } catch (InterruptedException e) { - // Ignore - } - return new ICVSResource[] { folder }; - } - - private IRunnableContext getRunnableContext() { - return PlatformUI.getWorkbench().getProgressService(); - } + return resources[0]; + } catch (InvocationTargetException e) { + CVSUIPlugin.log(CVSException.wrapException(e)); + } catch (InterruptedException e) { + // Ignore + } + return new ICVSResource[] { folder }; + } + + private IRunnableContext getRunnableContext() { + return PlatformUI.getWorkbench().getProgressService(); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagAsVersionDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagAsVersionDialog.java index 3b46a4526..1aed84c71 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagAsVersionDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagAsVersionDialog.java @@ -33,7 +33,7 @@ import org.eclipse.team.internal.ui.dialogs.DetailsDialog; public class TagAsVersionDialog extends DetailsDialog { - private static final int TAG_AREA_HEIGHT_HINT = 200; + private static final int TAG_AREA_HEIGHT_HINT = 200; private static final int HISTORY_LENGTH = 10; @@ -51,9 +51,9 @@ public class TagAsVersionDialog extends DetailsDialog { private String tagName = ""; //$NON-NLS-1$ private boolean moveTag = false; - private TagSource tagSource; + private TagSource tagSource; - private TagSelectionArea tagArea; + private TagSelectionArea tagArea; public TagAsVersionDialog(Shell parentShell, String title, ITagOperation operation) { super(parentShell, title); @@ -90,10 +90,10 @@ public class TagAsVersionDialog extends DetailsDialog { } - @Override + @Override protected String getHelpContextId() { - return IHelpContextIds.TAG_AS_VERSION_DIALOG; - } + return IHelpContextIds.TAG_AS_VERSION_DIALOG; + } public boolean shouldMoveTag() { return moveTag; @@ -105,11 +105,11 @@ public class TagAsVersionDialog extends DetailsDialog { final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent); final Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DIALOG)); - - final GridData gridData = new GridData(GridData.FILL_BOTH); - gridData.heightHint = TAG_AREA_HEIGHT_HINT; - composite.setLayoutData(gridData); + composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DIALOG)); + + final GridData gridData = new GridData(GridData.FILL_BOTH); + gridData.heightHint = TAG_AREA_HEIGHT_HINT; + composite.setLayoutData(gridData); tagArea = new TagSelectionArea(getShell(), tagSource, TagSelectionArea.INCLUDE_VERSIONS, null); tagArea.setTagAreaLabel(CVSUIMessages.TagAction_existingVersions); @@ -149,7 +149,7 @@ public class TagAsVersionDialog extends DetailsDialog { setPageComplete(message == null); setErrorMessage(message); if (tagArea != null) { - tagArea.setFilter(tagName); + tagArea.setFilter(tagName); } } @@ -171,10 +171,10 @@ public class TagAsVersionDialog extends DetailsDialog { return operation; } - @Override + @Override protected boolean isMainGrabVertical() { - return false; - } + return false; + } protected Combo createDropDownCombo(Composite parent) { Combo combo = new Combo(parent, SWT.DROP_DOWN); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagConfigurationDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagConfigurationDialog.java index cf74e7e98..8ad20ec49 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagConfigurationDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagConfigurationDialog.java @@ -80,9 +80,9 @@ public class TagConfigurationDialog extends TrayDialog { // dialogs settings that are persistent between workbench sessions private IDialogSettings settings; - private final TagSource tagSource; + private final TagSource tagSource; - private final TagSourceWrapper wrappedTagSource; + private final TagSourceWrapper wrappedTagSource; class FileComparator extends ViewerComparator { @Override @@ -103,105 +103,105 @@ public class TagConfigurationDialog extends TrayDialog { */ class TagSourceWrapper extends TagSource { - private final TagSource tagSource; + private final TagSource tagSource; private final List<CVSTag> branches = new ArrayList<>(); private final List<CVSTag> versions = new ArrayList<>(); private final List<CVSTag> dates = new ArrayList<>(); - public TagSourceWrapper(TagSource tagSource) { - this.tagSource = tagSource; - branches.addAll(Arrays.asList(tagSource.getTags(CVSTag.BRANCH))); - versions.addAll(Arrays.asList(tagSource.getTags(CVSTag.VERSION))); - dates.addAll(Arrays.asList(tagSource.getTags(CVSTag.DATE))); - } - - @Override + public TagSourceWrapper(TagSource tagSource) { + this.tagSource = tagSource; + branches.addAll(Arrays.asList(tagSource.getTags(CVSTag.BRANCH))); + versions.addAll(Arrays.asList(tagSource.getTags(CVSTag.VERSION))); + dates.addAll(Arrays.asList(tagSource.getTags(CVSTag.DATE))); + } + + @Override public CVSTag[] getTags(int type) { - if (type == CVSTag.HEAD || type == BASE) { - return super.getTags(type); - } + if (type == CVSTag.HEAD || type == BASE) { + return super.getTags(type); + } List<CVSTag> list = getTagList(type); - if (list != null) - return list.toArray(new CVSTag[list.size()]); - return tagSource.getTags(type); - } + if (list != null) + return list.toArray(new CVSTag[list.size()]); + return tagSource.getTags(type); + } private List<CVSTag> getTagList(int type) { - switch (type) { - case CVSTag.VERSION: - return versions; - case CVSTag.BRANCH: - return branches; - case CVSTag.DATE: - return dates; - } - return null; - } - - @Override + switch (type) { + case CVSTag.VERSION: + return versions; + case CVSTag.BRANCH: + return branches; + case CVSTag.DATE: + return dates; + } + return null; + } + + @Override public CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException { - // The wrapper is never refreshed - return new CVSTag[0]; - } + // The wrapper is never refreshed + return new CVSTag[0]; + } - @Override + @Override public ICVSRepositoryLocation getLocation() { - return tagSource.getLocation(); - } + return tagSource.getLocation(); + } - @Override + @Override public String getShortDescription() { - return tagSource.getShortDescription(); - } + return tagSource.getShortDescription(); + } - public void remove(CVSTag[] tags) { - for (int i = 0; i < tags.length; i++) { - CVSTag tag = tags[i]; - List list = getTagList(tag.getType()); - if (list != null) - list.remove(tag); - } - } + public void remove(CVSTag[] tags) { + for (int i = 0; i < tags.length; i++) { + CVSTag tag = tags[i]; + List list = getTagList(tag.getType()); + if (list != null) + list.remove(tag); + } + } - public void add(CVSTag[] tags) { - for (int i = 0; i < tags.length; i++) { - CVSTag tag = tags[i]; + public void add(CVSTag[] tags) { + for (int i = 0; i < tags.length; i++) { + CVSTag tag = tags[i]; List<CVSTag> list = getTagList(tag.getType()); - if (list != null) - list.add(tag); - } - } + if (list != null) + list.add(tag); + } + } - public void removeAll() { - versions.clear(); - branches.clear(); - dates.clear(); - } + public void removeAll() { + versions.clear(); + branches.clear(); + dates.clear(); + } - /** - * Remember the state that has been accumulated - * @param monitor - * @throws CVSException - */ - public void commit(IProgressMonitor monitor) throws CVSException { - tagSource.commit(getTags(new int[] { CVSTag.VERSION, CVSTag.BRANCH, CVSTag.DATE }), true /* replace */, monitor); - } + /** + * Remember the state that has been accumulated + * @param monitor + * @throws CVSException + */ + public void commit(IProgressMonitor monitor) throws CVSException { + tagSource.commit(getTags(new int[] { CVSTag.VERSION, CVSTag.BRANCH, CVSTag.DATE }), true /* replace */, monitor); + } - @Override + @Override public void commit(CVSTag[] tags, boolean replace, IProgressMonitor monitor) throws CVSException { - // Not invoked - } + // Not invoked + } - @Override + @Override public ICVSResource[] getCVSResources() { - return tagSource.getCVSResources(); - } + return tagSource.getCVSResources(); + } } public TagConfigurationDialog(Shell shell, TagSource tagSource) { super(shell); - this.tagSource = tagSource; - wrappedTagSource = new TagSourceWrapper(tagSource); + this.tagSource = tagSource; + wrappedTagSource = new TagSourceWrapper(tagSource); setShellStyle(SWT.CLOSE|SWT.RESIZE|SWT.APPLICATION_MODAL); allowSettingAutoRefreshFiles = getSingleFolder(tagSource, false) != null; IDialogSettings workbenchSettings = CVSUIPlugin.getPlugin().getDialogSettings(); @@ -225,8 +225,8 @@ public class TagConfigurationDialog extends TrayDialog { GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.makeColumnsEqualWidth = true; - gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); shell.setLayout (gridLayout); Composite comp = new Composite(shell, SWT.NULL); @@ -467,7 +467,7 @@ public class TagConfigurationDialog extends TrayDialog { autoRefreshFileList.setFocus(); } }); - PlatformUI.getWorkbench().getHelpSystem().setHelp(autoRefreshFileList, IHelpContextIds.TAG_CONFIGURATION_REFRESHLIST); + PlatformUI.getWorkbench().getHelpSystem().setHelp(autoRefreshFileList, IHelpContextIds.TAG_CONFIGURATION_REFRESHLIST); } Label seperator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); @@ -475,14 +475,14 @@ public class TagConfigurationDialog extends TrayDialog { data.horizontalSpan = 2; seperator.setLayoutData(data); - PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW); + PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW); updateEnablements(); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); return shell; } - private void updateShownTags() { + private void updateShownTags() { final CVSFileElement[] filesSelection = getSelectedFiles(); final Set<CVSTag> tags = new HashSet<>(); if(filesSelection.length!=0) { @@ -576,7 +576,7 @@ public class TagConfigurationDialog extends TrayDialog { tagsToAdd.add(tag); } if (!tagsToAdd.isEmpty()) { - wrappedTagSource.add(tagsToAdd.toArray(new CVSTag[tagsToAdd.size()])); + wrappedTagSource.add(tagsToAdd.toArray(new CVSTag[tagsToAdd.size()])); cvsDefinedTagsTree.refresh(); } } @@ -595,7 +595,7 @@ public class TagConfigurationDialog extends TrayDialog { } } if (!tagsToRemove.isEmpty()) { - wrappedTagSource.remove(tagsToRemove.toArray(new CVSTag[tagsToRemove.size()])); + wrappedTagSource.remove(tagsToRemove.toArray(new CVSTag[tagsToRemove.size()])); cvsDefinedTagsTree.refresh(); cvsDefinedTagsTree.getTree().setFocus(); } @@ -662,16 +662,16 @@ public class TagConfigurationDialog extends TrayDialog { CVSUIPlugin.openError(getShell(), null, null, e); } } - - protected ICVSFolder getSingleFolder(TagSource tagSource, boolean bestEffort) { - if (!bestEffort && tagSource instanceof MultiFolderTagSource) - return null; - if (tagSource instanceof SingleFolderTagSource) - return ((SingleFolderTagSource)tagSource).getFolder(); - return null; - } + + protected ICVSFolder getSingleFolder(TagSource tagSource, boolean bestEffort) { + if (!bestEffort && tagSource instanceof MultiFolderTagSource) + return null; + if (tagSource instanceof SingleFolderTagSource) + return ((SingleFolderTagSource)tagSource).getFolder(); + return null; + } - @Override + @Override protected Point getInitialSize() { int width, height; if(allowSettingAutoRefreshFiles) { @@ -700,7 +700,7 @@ public class TagConfigurationDialog extends TrayDialog { private GridData getStandardButtonData(Button button) { GridData data = new GridData(); data.heightHint = convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); - //don't crop labels with large font + //don't crop labels with large font //int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); //data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); return data; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagContentAssistProcessor.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagContentAssistProcessor.java index 92f71d777..fb8e75424 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagContentAssistProcessor.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagContentAssistProcessor.java @@ -31,16 +31,16 @@ import org.eclipse.ui.contentassist.ContentAssistHandler; */ public class TagContentAssistProcessor implements ISubjectControlContentAssistProcessor { - private FilteredTagList tags; + private FilteredTagList tags; private Map<ImageDescriptor, Image> images = new HashMap<>(); - public static void createContentAssistant(Text text, TagSource tagSource, int includeFlags) { + public static void createContentAssistant(Text text, TagSource tagSource, int includeFlags) { final TagContentAssistProcessor tagContentAssistProcessor = new TagContentAssistProcessor(tagSource, includeFlags); text.addDisposeListener(e -> tagContentAssistProcessor.dispose()); - ContentAssistHandler.createHandlerForText(text, createSubjectContentAssistant(tagContentAssistProcessor)); + ContentAssistHandler.createHandlerForText(text, createSubjectContentAssistant(tagContentAssistProcessor)); } - private static SubjectControlContentAssistant createSubjectContentAssistant(IContentAssistProcessor processor) { + private static SubjectControlContentAssistant createSubjectContentAssistant(IContentAssistProcessor processor) { final SubjectControlContentAssistant contentAssistant= new SubjectControlContentAssistant(); contentAssistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); @@ -53,86 +53,86 @@ public class TagContentAssistProcessor implements ISubjectControlContentAssistPr return contentAssistant; } - public TagContentAssistProcessor(TagSource tagSource, int includeFlags) { - tags = new FilteredTagList(tagSource, TagSource.convertIncludeFlaqsToTagTypes(includeFlags)); - } - - @Override + public TagContentAssistProcessor(TagSource tagSource, int includeFlags) { + tags = new FilteredTagList(tagSource, TagSource.convertIncludeFlaqsToTagTypes(includeFlags)); + } + + @Override public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) { - Control c = contentAssistSubjectControl.getControl(); - int docLength = contentAssistSubjectControl.getDocument().getLength(); - if (c instanceof Text) { - Text t = (Text)c; - String filter = t.getText(); - tags.setPattern(filter); - CVSTag[] matching = tags.getMatchingTags(); - if (matching.length > 0) { + Control c = contentAssistSubjectControl.getControl(); + int docLength = contentAssistSubjectControl.getDocument().getLength(); + if (c instanceof Text) { + Text t = (Text)c; + String filter = t.getText(); + tags.setPattern(filter); + CVSTag[] matching = tags.getMatchingTags(); + if (matching.length > 0) { List<CompletionProposal> proposals = new ArrayList<>(); - for (int i = 0; i < matching.length; i++) { - CVSTag tag = matching[i]; - String name = tag.getName(); - ImageDescriptor desc = TagElement.getImageDescriptor(tag); - Image image = null; - if (desc != null) { - image = images.get(desc); - if (image == null) { - image = desc.createImage(); - images.put(desc, image); - } - } - CompletionProposal proposal = new CompletionProposal(name, 0, docLength, name.length(), image, name, null, null); - proposals.add(proposal); - } - return proposals.toArray(new ICompletionProposal[proposals.size()]); - } - } - return null; - } + for (int i = 0; i < matching.length; i++) { + CVSTag tag = matching[i]; + String name = tag.getName(); + ImageDescriptor desc = TagElement.getImageDescriptor(tag); + Image image = null; + if (desc != null) { + image = images.get(desc); + if (image == null) { + image = desc.createImage(); + images.put(desc, image); + } + } + CompletionProposal proposal = new CompletionProposal(name, 0, docLength, name.length(), image, name, null, null); + proposals.add(proposal); + } + return proposals.toArray(new ICompletionProposal[proposals.size()]); + } + } + return null; + } - @Override + @Override public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) { - return null; - } + return null; + } - @Override + @Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { - Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$ - return null; - } + Assert.isTrue(false, "ITextViewer not supported"); //$NON-NLS-1$ + return null; + } - @Override + @Override public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { - return null; - } + return null; + } - @Override + @Override public char[] getCompletionProposalAutoActivationCharacters() { - return null; - } + return null; + } - @Override + @Override public char[] getContextInformationAutoActivationCharacters() { - return null; - } + return null; + } - @Override + @Override public String getErrorMessage() { - return null; - } + return null; + } - @Override + @Override public IContextInformationValidator getContextInformationValidator() { - return null; - } - + return null; + } + /** - * Dispose of any images created by the assistant - */ - public void dispose() { - for (Iterator iter = images.values().iterator(); iter.hasNext();) { - Image image = (Image) iter.next(); - image.dispose(); - } - } - + * Dispose of any images created by the assistant + */ + public void dispose() { + for (Iterator iter = images.values().iterator(); iter.hasNext();) { + Image image = (Image) iter.next(); + image.dispose(); + } + } + } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagElement.java index 9f7e93454..5604ae0bd 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagElement.java @@ -24,18 +24,18 @@ import org.eclipse.team.internal.ccvs.ui.model.CVSTagElement; import org.eclipse.ui.model.IWorkbenchAdapter; public class TagElement implements IWorkbenchAdapter, IAdaptable { - Object parent; + Object parent; CVSTag tag; public static ImageDescriptor getImageDescriptor(CVSTag tag) { - if (tag.getType() == CVSTag.BRANCH || tag.equals(CVSTag.DEFAULT)) { + if (tag.getType() == CVSTag.BRANCH || tag.equals(CVSTag.DEFAULT)) { return CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_TAG); } else if (tag.getType() == CVSTag.DATE){ return CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_DATE); }else { return CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_PROJECT_VERSION); } - } + } /** * @deprecated @@ -46,7 +46,7 @@ public class TagElement implements IWorkbenchAdapter, IAdaptable { this(null, tag); } public TagElement(Object parent, CVSTag tag) { - this.parent = parent; + this.parent = parent; this.tag = tag; } @Override @@ -62,7 +62,7 @@ public class TagElement implements IWorkbenchAdapter, IAdaptable { public ImageDescriptor getImageDescriptor(Object object) { return getImageDescriptor(tag); } - @Override + @Override public String getLabel(Object o) { if(tag.getType() == CVSTag.DATE){ Date date = tag.asDate(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java index 7366075b8..686ffa7ed 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java @@ -34,69 +34,69 @@ import org.eclipse.ui.PlatformUI; * An area that displays the Refresh and Configure Tags buttons */ public class TagRefreshButtonArea extends DialogArea { - - private TagSource tagSource; - private final Shell shell; - private Button refreshButton; - private IRunnableContext context; + + private TagSource tagSource; + private final Shell shell; + private Button refreshButton; + private IRunnableContext context; private Label fMessageLabel; - private final Listener addDateTagListener; + private final Listener addDateTagListener; - public TagRefreshButtonArea(Shell shell, TagSource tagSource, Listener addDateTagListener) { - this.addDateTagListener = addDateTagListener; - Assert.isNotNull(shell); - Assert.isNotNull(tagSource); - this.shell = shell; - this.tagSource = tagSource; - } - - @Override + public TagRefreshButtonArea(Shell shell, TagSource tagSource, Listener addDateTagListener) { + this.addDateTagListener = addDateTagListener; + Assert.isNotNull(shell); + Assert.isNotNull(tagSource); + this.shell = shell; + this.tagSource = tagSource; + } + + @Override public void createArea(Composite parent) { - - final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent); - - final Composite buttonComp = new Composite(parent, SWT.NONE); - buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false)); - buttonComp.setLayout(SWTUtils.createGridLayout(4, converter, SWTUtils.MARGINS_NONE)); - + + final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent); + + final Composite buttonComp = new Composite(parent, SWT.NONE); + buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false)); + buttonComp.setLayout(SWTUtils.createGridLayout(4, converter, SWTUtils.MARGINS_NONE)); + fMessageLabel= SWTUtils.createLabel(buttonComp, null); refreshButton = new Button(buttonComp, SWT.PUSH); refreshButton.setText (CVSUIMessages.TagConfigurationDialog_20); final Button configureTagsButton = new Button(buttonComp, SWT.PUSH); configureTagsButton.setText (CVSUIMessages.TagConfigurationDialog_21); - - Button addDateTagButton = null; - int buttonWidth; - if (addDateTagListener != null) { - addDateTagButton = new Button(buttonComp, SWT.PUSH); - addDateTagButton.setText (CVSUIMessages.TagConfigurationDialog_AddDateTag); - Dialog.applyDialogFont(buttonComp); - buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addDateTagButton, configureTagsButton, refreshButton }); - addDateTagButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false)); - addDateTagButton.addListener(SWT.Selection, addDateTagListener); - } else { - Dialog.applyDialogFont(buttonComp); - buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { configureTagsButton, refreshButton }); - } + + Button addDateTagButton = null; + int buttonWidth; + if (addDateTagListener != null) { + addDateTagButton = new Button(buttonComp, SWT.PUSH); + addDateTagButton.setText (CVSUIMessages.TagConfigurationDialog_AddDateTag); + Dialog.applyDialogFont(buttonComp); + buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addDateTagButton, configureTagsButton, refreshButton }); + addDateTagButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false)); + addDateTagButton.addListener(SWT.Selection, addDateTagListener); + } else { + Dialog.applyDialogFont(buttonComp); + buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { configureTagsButton, refreshButton }); + } refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false)); configureTagsButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false)); refreshButton.addListener(SWT.Selection, event -> refresh(false)); - + configureTagsButton.addListener(SWT.Selection, event -> { TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource); d.open(); }); - PlatformUI.getWorkbench().getHelpSystem().setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION); - PlatformUI.getWorkbench().getHelpSystem().setHelp(configureTagsButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW); + PlatformUI.getWorkbench().getHelpSystem().setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(configureTagsButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW); Dialog.applyDialogFont(buttonComp); - } - - - public void refresh(final boolean background) { + } + + + public void refresh(final boolean background) { try { getRunnableContext().run(true, true, monitor -> { try { @@ -128,17 +128,17 @@ public class TagRefreshButtonArea extends DialogArea { CVSUIPlugin.openError(shell, CVSUIMessages.TagConfigurationDialog_14, null, e); } } - - private void setBusy(final boolean busy) { - if (shell != null && !shell.isDisposed()) + + private void setBusy(final boolean busy) { + if (shell != null && !shell.isDisposed()) shell.getDisplay().asyncExec(() -> { if (!refreshButton.isDisposed()) refreshButton.setEnabled(!busy); }); - } + } - private boolean promptForBestEffort() { - final boolean[] prompt = new boolean[] { false }; + private boolean promptForBestEffort() { + final boolean[] prompt = new boolean[] { false }; shell.getDisplay().syncExec(() -> { MessageDialog dialog = new MessageDialog(shell, CVSUIMessages.TagRefreshButtonArea_0, null, getNoTagsFoundMessage(), MessageDialog.INFORMATION, @@ -154,25 +154,25 @@ public class TagRefreshButtonArea extends DialogArea { } }); - return prompt[0]; - } - - private String getNoTagsFoundMessage() { - return NLS.bind(CVSUIMessages.TagRefreshButtonArea_4, new String[] { tagSource.getShortDescription() }); - } - - public void setTagSource(TagSource tagSource) { - Assert.isNotNull(tagSource); - this.tagSource = tagSource; - } + return prompt[0]; + } + + private String getNoTagsFoundMessage() { + return NLS.bind(CVSUIMessages.TagRefreshButtonArea_4, new String[] { tagSource.getShortDescription() }); + } + + public void setTagSource(TagSource tagSource) { + Assert.isNotNull(tagSource); + this.tagSource = tagSource; + } - public IRunnableContext getRunnableContext() { - if (context == null) - return PlatformUI.getWorkbench().getProgressService(); - return context; - } - - public void setRunnableContext(IRunnableContext context) { - this.context = context; - } + public IRunnableContext getRunnableContext() { + if (context == null) + return PlatformUI.getWorkbench().getProgressService(); + return context; + } + + public void setRunnableContext(IRunnableContext context) { + this.context = context; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRootElement.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRootElement.java index 8b88194d9..a9c48a6cf 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRootElement.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRootElement.java @@ -26,11 +26,11 @@ import org.eclipse.ui.model.IWorkbenchAdapter; public class TagRootElement implements IWorkbenchAdapter, IAdaptable { private TagSource tagSource; private int typeOfTagRoot; - private final Object parent; + private final Object parent; public TagRootElement(Object parent, TagSource tagSource, int typeOfTagRoot) { this.parent = parent; - this.typeOfTagRoot = typeOfTagRoot; + this.typeOfTagRoot = typeOfTagRoot; this.tagSource = tagSource; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionArea.java index 86882b381..c06143fb8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionArea.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionArea.java @@ -48,30 +48,30 @@ import org.eclipse.ui.part.PageBook; */ public class TagSelectionArea extends DialogArea { - private static int COLUMN_TRIM = "carbon".equals(SWT.getPlatform()) ? 24 : 3; //$NON-NLS-1$ - - private static int ICON_WIDTH = 40; - - /* - * Please see bug 184660 - */ - private static final int SAFETY_MARGIN = 50; - - /* - * Property constant which identifies the selected tag or - * null if no tag is selected - */ - public static final String SELECTED_TAG = "selectedTag"; //$NON-NLS-1$ - - /* - * Property constant which indicates that a tag has been selected in such - * a way as to indicate that this is the desired tag (e.g double-click) - */ - public static final String OPEN_SELECTED_TAG = "openSelectedTag"; //$NON-NLS-1$ - - /* - * Constants used to configure which tags are shown - */ + private static int COLUMN_TRIM = "carbon".equals(SWT.getPlatform()) ? 24 : 3; //$NON-NLS-1$ + + private static int ICON_WIDTH = 40; + + /* + * Please see bug 184660 + */ + private static final int SAFETY_MARGIN = 50; + + /* + * Property constant which identifies the selected tag or + * null if no tag is selected + */ + public static final String SELECTED_TAG = "selectedTag"; //$NON-NLS-1$ + + /* + * Property constant which indicates that a tag has been selected in such + * a way as to indicate that this is the desired tag (e.g double-click) + */ + public static final String OPEN_SELECTED_TAG = "openSelectedTag"; //$NON-NLS-1$ + + /* + * Constants used to configure which tags are shown + */ public static final int INCLUDE_HEAD_TAG = TagSourceWorkbenchAdapter.INCLUDE_HEAD_TAG; public static final int INCLUDE_BASE_TAG = TagSourceWorkbenchAdapter.INCLUDE_BASE_TAG; public static final int INCLUDE_BRANCHES = TagSourceWorkbenchAdapter.INCLUDE_BRANCHES; @@ -79,56 +79,56 @@ public class TagSelectionArea extends DialogArea { public static final int INCLUDE_DATES = TagSourceWorkbenchAdapter.INCLUDE_DATES; public static final int INCLUDE_ALL_TAGS = TagSourceWorkbenchAdapter.INCLUDE_ALL_TAGS; - private String tagAreaLabel; - private final int includeFlags; - private CVSTag selection; - private String helpContext; - private Text filterText; - private TagSource tagSource; - private final Shell shell; - private TagRefreshButtonArea tagRefreshArea; - private final TagSource.ITagSourceChangeListener listener = source -> { + private String tagAreaLabel; + private final int includeFlags; + private CVSTag selection; + private String helpContext; + private Text filterText; + private TagSource tagSource; + private final Shell shell; + private TagRefreshButtonArea tagRefreshArea; + private final TagSource.ITagSourceChangeListener listener = source -> { Shell shell = getShell(); if (!shell.isDisposed()) { - shell.getDisplay().syncExec(() -> refresh()); + shell.getDisplay().syncExec(() -> refresh()); } }; - private final DisposeListener disposeListener = e -> { - if (tagSource != null) - tagSource.removeListener(listener); + private final DisposeListener disposeListener = e -> { + if (tagSource != null) + tagSource.removeListener(listener); }; - private PageBook switcher; - private TreeViewer tagTree; - private TableViewer tagTable; - private boolean treeVisible = true; - private boolean includeFilterInputArea = true; - private String filterPattern = ""; //$NON-NLS-1$ + private PageBook switcher; + private TreeViewer tagTree; + private TableViewer tagTable; + private boolean treeVisible = true; + private boolean includeFilterInputArea = true; + private String filterPattern = ""; //$NON-NLS-1$ - private IRunnableContext context; - - public TagSelectionArea(Shell shell, TagSource tagSource, int includeFlags, String helpContext) { - this.shell = shell; - this.includeFlags = includeFlags; - this.helpContext = helpContext; - this.tagSource = tagSource; - setSelection(null); - } + private IRunnableContext context; + + public TagSelectionArea(Shell shell, TagSource tagSource, int includeFlags, String helpContext) { + this.shell = shell; + this.includeFlags = includeFlags; + this.helpContext = helpContext; + this.tagSource = tagSource; + setSelection(null); + } - @Override + @Override public void createArea(Composite parent) { - initializeDialogUnits(parent); - Dialog.applyDialogFont(parent); - final PixelConverter converter= new PixelConverter(parent); - - // Create a composite for the entire area - Composite composite= new Composite(parent, SWT.NONE); - composite.setLayoutData(SWTUtils.createHVFillGridData()); - composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); - + initializeDialogUnits(parent); + Dialog.applyDialogFont(parent); + final PixelConverter converter= new PixelConverter(parent); + + // Create a composite for the entire area + Composite composite= new Composite(parent, SWT.NONE); + composite.setLayoutData(SWTUtils.createHVFillGridData()); + composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); + // Add F1 help if (helpContext != null) { - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContext); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContext); } // Create the tree area and refresh buttons with the possibility to add stuff in between @@ -136,209 +136,209 @@ public class TagSelectionArea extends DialogArea { createCustomArea(composite); createRefreshButtons(composite); - Dialog.applyDialogFont(parent); - updateTagDisplay(true); - } + Dialog.applyDialogFont(parent); + updateTagDisplay(true); + } - private void createTagDisplayArea(Composite parent) { - Composite inner = createGrabbingComposite(parent, 1); - if (isIncludeFilterInputArea()) { - createFilterInput(inner); - createWrappingLabel(inner, CVSUIMessages.TagSelectionArea_0, 1); - } else { - createWrappingLabel(inner, NLS.bind(CVSUIMessages.TagSelectionArea_1, new String[] { getTagAreaLabel() }), 1); - } + private void createTagDisplayArea(Composite parent) { + Composite inner = createGrabbingComposite(parent, 1); + if (isIncludeFilterInputArea()) { + createFilterInput(inner); + createWrappingLabel(inner, CVSUIMessages.TagSelectionArea_0, 1); + } else { + createWrappingLabel(inner, NLS.bind(CVSUIMessages.TagSelectionArea_1, new String[] { getTagAreaLabel() }), 1); + } switcher = new PageBook(inner, SWT.NONE); GridData gridData = new GridData(GridData.FILL_BOTH); gridData.heightHint = 0; gridData.widthHint = 0; - switcher.setLayoutData(gridData); + switcher.setLayoutData(gridData); tagTree = createTree(switcher); tagTable = createTable(switcher); - } + } - private void createFilterInput(Composite inner) { - createWrappingLabel(inner, NLS.bind(CVSUIMessages.TagSelectionArea_2, new String[] { getTagAreaLabel() }), 1); - filterText = createText(inner, 1); - filterText.addModifyListener(e -> setFilter(filterText.getText())); - filterText.addKeyListener(new KeyListener() { - @Override + private void createFilterInput(Composite inner) { + createWrappingLabel(inner, NLS.bind(CVSUIMessages.TagSelectionArea_2, new String[] { getTagAreaLabel() }), 1); + filterText = createText(inner, 1); + filterText.addModifyListener(e -> setFilter(filterText.getText())); + filterText.addKeyListener(new KeyListener() { + @Override public void keyPressed(KeyEvent e) { - if (e.keyCode == SWT.ARROW_DOWN && e.stateMask == 0) { - tagTable.getControl().setFocus(); - } - } - @Override + if (e.keyCode == SWT.ARROW_DOWN && e.stateMask == 0) { + tagTable.getControl().setFocus(); + } + } + @Override public void keyReleased(KeyEvent e) { - // Ignore - } - }); - } + // Ignore + } + }); + } - /** - * Return the label that should be used for the tag area. - * It should not have any trailing punctuations as the tag area - * may position it differently depending on whether the filter - * text input is included in the area. - * @return the tag area label - */ - public String getTagAreaLabel() { - if (tagAreaLabel == null) - tagAreaLabel = CVSUIMessages.TagSelectionArea_3; - return tagAreaLabel; - } + /** + * Return the label that should be used for the tag area. + * It should not have any trailing punctuations as the tag area + * may position it differently depending on whether the filter + * text input is included in the area. + * @return the tag area label + */ + public String getTagAreaLabel() { + if (tagAreaLabel == null) + tagAreaLabel = CVSUIMessages.TagSelectionArea_3; + return tagAreaLabel; + } - /** - * Set the label that should be used for the tag area. - * It should not have any trailing punctuations as the tag area - * may position it differently depending on whether the filter - * text input is included in the area. - * @param tagAreaLabel the tag area label - */ - public void setTagAreaLabel(String tagAreaLabel) { - this.tagAreaLabel = tagAreaLabel; - } - - /** - * Update the tag display to show the tags that match the - * include flags and the filter entered by the user. - */ - protected void updateTagDisplay(boolean firstTime) { - String filter = getFilterString(); - if ((filter != null && filter.length() > 0) || isTableOnly()) { - // Show the table and filter it accordingly - try { - switcher.setRedraw(false); - treeVisible = false; - switcher.showPage(tagTable.getControl()); - FilteredTagList list = (FilteredTagList)tagTable.getInput(); - list.setPattern(filter); - tagTable.refresh(); - int maxWidth = getMaxWidth(list.getChildren(null)); - if (maxWidth > 0) { - maxWidth = maxWidth + ICON_WIDTH + COLUMN_TRIM + SAFETY_MARGIN; /* space for the tag icon */ - tagTable.getTable().getColumn(0).setWidth(maxWidth); - } - if (filterText == null || filter == null || filter.length() == 0) { - setSelection(selection); - } else { - // Only set the top selection if there is a filter from the filter text - // of this area. This is done to avoid selection loops - selectTopElement(); - } - } finally { - switcher.setRedraw(true); - } - } else { - // Show the tree - if (!isTreeVisible() || firstTime) { - try { - switcher.setRedraw(false); - treeVisible = true; - switcher.showPage(tagTree.getControl()); - tagTree.refresh(); - setSelection(selection); - } finally { - switcher.setRedraw(true); - } - } - } - } - - private int getMaxWidth(Object[] children) { - PixelConverter converter = new PixelConverter(tagTable.getTable()); - int maxWidth = 0; - for (int i = 0; i < children.length; i++) { - Object object = children[i]; - if (object instanceof TagElement) { - TagElement tag = (TagElement) object; - int width = tag.getTag().getName().length(); - if (width > maxWidth) { - maxWidth = width; - } - } - } - return converter.convertWidthInCharsToPixels(maxWidth); - } + /** + * Set the label that should be used for the tag area. + * It should not have any trailing punctuations as the tag area + * may position it differently depending on whether the filter + * text input is included in the area. + * @param tagAreaLabel the tag area label + */ + public void setTagAreaLabel(String tagAreaLabel) { + this.tagAreaLabel = tagAreaLabel; + } + + /** + * Update the tag display to show the tags that match the + * include flags and the filter entered by the user. + */ + protected void updateTagDisplay(boolean firstTime) { + String filter = getFilterString(); + if ((filter != null && filter.length() > 0) || isTableOnly()) { + // Show the table and filter it accordingly + try { + switcher.setRedraw(false); + treeVisible = false; + switcher.showPage(tagTable.getControl()); + FilteredTagList list = (FilteredTagList)tagTable.getInput(); + list.setPattern(filter); + tagTable.refresh(); + int maxWidth = getMaxWidth(list.getChildren(null)); + if (maxWidth > 0) { + maxWidth = maxWidth + ICON_WIDTH + COLUMN_TRIM + SAFETY_MARGIN; /* space for the tag icon */ + tagTable.getTable().getColumn(0).setWidth(maxWidth); + } + if (filterText == null || filter == null || filter.length() == 0) { + setSelection(selection); + } else { + // Only set the top selection if there is a filter from the filter text + // of this area. This is done to avoid selection loops + selectTopElement(); + } + } finally { + switcher.setRedraw(true); + } + } else { + // Show the tree + if (!isTreeVisible() || firstTime) { + try { + switcher.setRedraw(false); + treeVisible = true; + switcher.showPage(tagTree.getControl()); + tagTree.refresh(); + setSelection(selection); + } finally { + switcher.setRedraw(true); + } + } + } + } + + private int getMaxWidth(Object[] children) { + PixelConverter converter = new PixelConverter(tagTable.getTable()); + int maxWidth = 0; + for (int i = 0; i < children.length; i++) { + Object object = children[i]; + if (object instanceof TagElement) { + TagElement tag = (TagElement) object; + int width = tag.getTag().getName().length(); + if (width > maxWidth) { + maxWidth = width; + } + } + } + return converter.convertWidthInCharsToPixels(maxWidth); + } - /** - * Return whether only a table should be used - * @return whether only a table should be used - */ - protected boolean isTableOnly() { - return (includeFlags == INCLUDE_VERSIONS) || (includeFlags == INCLUDE_BRANCHES); - } + /** + * Return whether only a table should be used + * @return whether only a table should be used + */ + protected boolean isTableOnly() { + return (includeFlags == INCLUDE_VERSIONS) || (includeFlags == INCLUDE_BRANCHES); + } - private String getFilterString() { - return filterPattern; - } + private String getFilterString() { + return filterPattern; + } - /* - * Select the top element in the tag table - */ - private void selectTopElement() { - if (tagTable.getTable().getItemCount() > 0) { - TableItem item = tagTable.getTable().getItem(0); - tagTable.getTable().setSelection(new TableItem[] { item }); - tagTable.setSelection(tagTable.getSelection()); - } - } + /* + * Select the top element in the tag table + */ + private void selectTopElement() { + if (tagTable.getTable().getItemCount() > 0) { + TableItem item = tagTable.getTable().getItem(0); + tagTable.getTable().setSelection(new TableItem[] { item }); + tagTable.setSelection(tagTable.getSelection()); + } + } - private FilteredTagList createFilteredInput() { - return new FilteredTagList(tagSource, TagSource.convertIncludeFlaqsToTagTypes(includeFlags)); - } - - private Text createText(Composite parent, int horizontalSpan) { - Text text = new Text(parent, SWT.SEARCH); + private FilteredTagList createFilteredInput() { + return new FilteredTagList(tagSource, TagSource.convertIncludeFlaqsToTagTypes(includeFlags)); + } + + private Text createText(Composite parent, int horizontalSpan) { + Text text = new Text(parent, SWT.SEARCH); GridData data = new GridData(); data.horizontalSpan = horizontalSpan; data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; data.widthHint= 0; text.setLayoutData(data); - return text; - } + return text; + } - protected void createRefreshButtons(Composite parent) { - tagSource.addListener(listener); - parent.addDisposeListener(disposeListener); - Listener listener = null; - if ((includeFlags & TagSourceWorkbenchAdapter.INCLUDE_DATES) != 0) { - listener = event -> { - CVSTag dateTag = NewDateTagAction.getDateTag(getShell(), getLocation()); - addDateTag(dateTag); + protected void createRefreshButtons(Composite parent) { + tagSource.addListener(listener); + parent.addDisposeListener(disposeListener); + Listener listener = null; + if ((includeFlags & TagSourceWorkbenchAdapter.INCLUDE_DATES) != 0) { + listener = event -> { + CVSTag dateTag = NewDateTagAction.getDateTag(getShell(), getLocation()); + addDateTag(dateTag); }; - } - tagRefreshArea = new TagRefreshButtonArea(shell, tagSource, listener); - if (context != null) - tagRefreshArea.setRunnableContext(context); - tagRefreshArea.createArea(parent); - } + } + tagRefreshArea = new TagRefreshButtonArea(shell, tagSource, listener); + if (context != null) + tagRefreshArea.setRunnableContext(context); + tagRefreshArea.createArea(parent); + } - protected void createTreeMenu(TreeViewer tagTree) { - if ((includeFlags & TagSourceWorkbenchAdapter.INCLUDE_DATES) != 0) { - // Create the popup menu + protected void createTreeMenu(TreeViewer tagTree) { + if ((includeFlags & TagSourceWorkbenchAdapter.INCLUDE_DATES) != 0) { + // Create the popup menu MenuManager menuMgr = new MenuManager(); Tree tree = tagTree.getTree(); Menu menu = menuMgr.createContextMenu(tree); menuMgr.addMenuListener(manager -> addMenuItemActions(manager)); menuMgr.setRemoveAllWhenShown(true); tree.setMenu(menu); - } - } + } + } - /** - * Create aq custom area that is below the tag selection area but above the refresh busson group - * @param parent - */ + /** + * Create aq custom area that is below the tag selection area but above the refresh busson group + * @param parent + */ protected void createCustomArea(Composite parent) { // No default custom area - } + } - protected TreeViewer createTree(Composite parent) { + protected TreeViewer createTree(Composite parent) { Tree tree = new Tree(parent, SWT.SINGLE | SWT.BORDER); GridData data = new GridData(GridData.FILL_BOTH); - tree.setLayoutData(data); + tree.setLayoutData(data); TreeViewer result = new TreeViewer(tree); initialize(result); result.getControl().addKeyListener(new KeyListener() { @@ -356,7 +356,7 @@ public class TagSelectionArea extends DialogArea { return result; } - protected TableViewer createTable(Composite parent) { + protected TableViewer createTable(Composite parent) { Table table = new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION); GridData data = new GridData(GridData.FILL_BOTH); table.setLayoutData(data); @@ -371,8 +371,8 @@ public class TagSelectionArea extends DialogArea { } - private void initialize(StructuredViewer viewer) { - viewer.setContentProvider(new WorkbenchContentProvider()); + private void initialize(StructuredViewer viewer) { + viewer.setContentProvider(new WorkbenchContentProvider()); viewer.setLabelProvider(new WorkbenchLabelProvider()); viewer.setComparator(new ProjectElementComparator()); viewer.addSelectionChangedListener(event -> handleSelectionChange()); @@ -381,19 +381,19 @@ public class TagSelectionArea extends DialogArea { viewer.getControl().addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { - CVSTag tag = internalGetSelectedTag(); - if (tag != null) { - firePropertyChangeChange(OPEN_SELECTED_TAG, null, tag); - } + CVSTag tag = internalGetSelectedTag(); + if (tag != null) { + firePropertyChangeChange(OPEN_SELECTED_TAG, null, tag); + } } }); - } + } - private Object createUnfilteredInput() { - return TagSourceWorkbenchAdapter.createInput(tagSource, includeFlags); - } + private Object createUnfilteredInput() { + return TagSourceWorkbenchAdapter.createInput(tagSource, includeFlags); + } - public void handleKeyPressed(KeyEvent event) { + public void handleKeyPressed(KeyEvent event) { if (event.character == SWT.DEL && event.stateMask == 0) { deleteDateTag(); } @@ -443,7 +443,7 @@ public class TagSelectionArea extends DialogArea { ICVSRepositoryLocation location = getLocation(); dateTags.addAll(Arrays.asList(CVSUIPlugin.getPlugin().getRepositoryManager().getDateTags(location))); if(!dateTags.contains( tag)){ - CVSUIPlugin.getPlugin().getRepositoryManager().addDateTag(location, tag); + CVSUIPlugin.getPlugin().getRepositoryManager().addDateTag(location, tag); } try { tagTree.getControl().setRedraw(false); @@ -480,62 +480,62 @@ public class TagSelectionArea extends DialogArea { * (which could be either the table or the tree). */ protected void handleSelectionChange() { - CVSTag newSelection = internalGetSelectedTag(); - if (selection != null && newSelection != null && selection.equals(newSelection)) { - // the selection hasn't change so return - return; - } - CVSTag oldSelection = selection; - selection = newSelection; - firePropertyChangeChange(SELECTED_TAG, oldSelection, selection); + CVSTag newSelection = internalGetSelectedTag(); + if (selection != null && newSelection != null && selection.equals(newSelection)) { + // the selection hasn't change so return + return; + } + CVSTag oldSelection = selection; + selection = newSelection; + firePropertyChangeChange(SELECTED_TAG, oldSelection, selection); } private CVSTag internalGetSelectedTag() { - IStructuredSelection selection; - if (isTreeVisible()) { - selection = tagTree.getStructuredSelection(); - } else { - selection = tagTable.getStructuredSelection(); - } + IStructuredSelection selection; + if (isTreeVisible()) { + selection = tagTree.getStructuredSelection(); + } else { + selection = tagTable.getStructuredSelection(); + } Object o = selection.getFirstElement(); if (o instanceof TagElement) - return ((TagElement)o).getTag(); + return ((TagElement)o).getTag(); return null; } - private boolean isTreeVisible() { - return treeVisible; - } + private boolean isTreeVisible() { + return treeVisible; + } - private ICVSRepositoryLocation getLocation(){ + private ICVSRepositoryLocation getLocation(){ return tagSource.getLocation(); } - public CVSTag getSelection() { - return selection; - } - public Shell getShell() { - return shell; - } + public CVSTag getSelection() { + return selection; + } + public Shell getShell() { + return shell; + } - /** - * Set the focus to the filter text widget - */ - public void setFocus() { - if (filterText != null) - filterText.setFocus(); - else if (switcher != null) - switcher.setFocus(); - - // Refresh in case tags were added since the last time the area had focus - refresh(); - } + /** + * Set the focus to the filter text widget + */ + public void setFocus() { + if (filterText != null) + filterText.setFocus(); + else if (switcher != null) + switcher.setFocus(); + + // Refresh in case tags were added since the last time the area had focus + refresh(); + } - /** - * Select the given tag - * @param selectedTag the tag to be selected - */ - public void setSelection(CVSTag selectedTag) { - if (isTreeVisible()) + /** + * Select the given tag + * @param selectedTag the tag to be selected + */ + public void setSelection(CVSTag selectedTag) { + if (isTreeVisible()) if (tagTree != null && !tagTree.getControl().isDisposed()) { // TODO: Hack to instantiate the model before revealing the selection tagTree.expandToLevel(2); @@ -545,97 +545,97 @@ public class TagSelectionArea extends DialogArea { tagTree.setSelection(new StructuredSelection(new TagElement(selectedTag))); } else - if (tagTable != null && !tagTable.getControl().isDisposed()) { - tagTable.setSelection(new StructuredSelection(new TagElement(selectedTag))); - } - } + if (tagTable != null && !tagTable.getControl().isDisposed()) { + tagTable.setSelection(new StructuredSelection(new TagElement(selectedTag))); + } + } - /** - * Refresh the state of the tag selection area - */ - public void refresh() { - if (isTreeVisible()) { - if (tagTree != null && !tagTree.getControl().isDisposed()) { - tagTree.refresh(); - } - } else { - if (tagTable != null && !tagTable.getControl().isDisposed()) { - tagTable.refresh(); - } - } - } - - public void refreshTagList() { - tagRefreshArea.refresh(true); - } + /** + * Refresh the state of the tag selection area + */ + public void refresh() { + if (isTreeVisible()) { + if (tagTree != null && !tagTree.getControl().isDisposed()) { + tagTree.refresh(); + } + } else { + if (tagTable != null && !tagTable.getControl().isDisposed()) { + tagTable.refresh(); + } + } + } + + public void refreshTagList() { + tagRefreshArea.refresh(true); + } - /** - * Set the enablement state of the area - * @param enabled the enablement state - */ - public void setEnabled(boolean enabled) { - if (filterText != null) - filterText.setEnabled(enabled); - tagTree.getControl().setEnabled(enabled); - tagTable.getControl().setEnabled(enabled); - } - - /** - * Set the tag source from which the displayed tags are determined - * @param tagSource the source of the tags being displayed - */ - public void setTagSource(TagSource tagSource) { - if (this.tagSource != null) { - this.tagSource.removeListener(listener); - } - this.tagSource = tagSource; - this.tagSource.addListener(listener); - tagRefreshArea.setTagSource(this.tagSource); - setTreeAndTableInput(); - } + /** + * Set the enablement state of the area + * @param enabled the enablement state + */ + public void setEnabled(boolean enabled) { + if (filterText != null) + filterText.setEnabled(enabled); + tagTree.getControl().setEnabled(enabled); + tagTable.getControl().setEnabled(enabled); + } + + /** + * Set the tag source from which the displayed tags are determined + * @param tagSource the source of the tags being displayed + */ + public void setTagSource(TagSource tagSource) { + if (this.tagSource != null) { + this.tagSource.removeListener(listener); + } + this.tagSource = tagSource; + this.tagSource.addListener(listener); + tagRefreshArea.setTagSource(this.tagSource); + setTreeAndTableInput(); + } - private void setTreeAndTableInput() { - if (tagTree != null) { - tagTree.setInput(createUnfilteredInput()); - } - if (tagTable != null) { - tagTable.setInput(createFilteredInput()); - } - - } + private void setTreeAndTableInput() { + if (tagTree != null) { + tagTree.setInput(createUnfilteredInput()); + } + if (tagTable != null) { + tagTable.setInput(createFilteredInput()); + } + + } - /** - * Set whether the input filter text is to be included in the tag selection area. - * If excluded, clientscan still set the filter text directly using - * <code>setFilter</code>. - * @param include whether filter text input should be included - */ - public void setIncludeFilterInputArea(boolean include) { - includeFilterInputArea = include; - } - - /** - * Return whether the input filter text is to be included in the tag selection area. - * If excluded, clientscan still set the filter text directly using - * <code>setFilter</code>. - * @return whether filter text input should be included - */ - public boolean isIncludeFilterInputArea() { - return includeFilterInputArea; - } + /** + * Set whether the input filter text is to be included in the tag selection area. + * If excluded, clientscan still set the filter text directly using + * <code>setFilter</code>. + * @param include whether filter text input should be included + */ + public void setIncludeFilterInputArea(boolean include) { + includeFilterInputArea = include; + } + + /** + * Return whether the input filter text is to be included in the tag selection area. + * If excluded, clientscan still set the filter text directly using + * <code>setFilter</code>. + * @return whether filter text input should be included + */ + public boolean isIncludeFilterInputArea() { + return includeFilterInputArea; + } - /** - * Set the text used to filter the tag list. - * @param filter the filter pattern - */ - public void setFilter(String filter) { - this.filterPattern = filter; - updateTagDisplay(false); - } - - public void setRunnableContext(IRunnableContext context) { - this.context = context; - if (tagRefreshArea != null) - tagRefreshArea.setRunnableContext(context); - } + /** + * Set the text used to filter the tag list. + * @param filter the filter pattern + */ + public void setFilter(String filter) { + this.filterPattern = filter; + updateTagDisplay(false); + } + + public void setRunnableContext(IRunnableContext context) { + this.context = context; + if (tagRefreshArea != null) + tagRefreshArea.setRunnableContext(context); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionDialog.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionDialog.java index 8f3920571..1e23aec62 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionDialog.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionDialog.java @@ -58,17 +58,17 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis private static final int SIZING_DIALOG_WIDTH = 90; private static final int SIZING_DIALOG_HEIGHT = 25; - private CVSTag selection; + private CVSTag selection; - private TagSource tagSource; + private TagSource tagSource; - private String message; + private String message; - private int includeFlags; + private int includeFlags; - private String helpContext; + private String helpContext; - private boolean showRecurse; + private boolean showRecurse; public static CVSTag getTagToCompareWith(Shell shell, TagSource tagSource, int includeFlags) { TagSelectionDialog dialog = new TagSelectionDialog(shell, tagSource, @@ -107,12 +107,12 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis newShell.setText(title); } - protected Point getInitialSize() { - final Point size= super.getInitialSize(); - size.x= convertWidthInCharsToPixels(SIZING_DIALOG_WIDTH); - size.y= convertHeightInCharsToPixels(SIZING_DIALOG_HEIGHT); - return size; - } + protected Point getInitialSize() { + final Point size= super.getInitialSize(); + size.x= convertWidthInCharsToPixels(SIZING_DIALOG_WIDTH); + size.y= convertHeightInCharsToPixels(SIZING_DIALOG_HEIGHT); + return size; + } /** * Creates this window's widgetry. @@ -164,7 +164,7 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis final Composite top = (Composite)super.createDialogArea(parent); // Delegate most of the dialog to the tag selection area - tagSelectionArea = new TagSelectionArea(getShell(), tagSource, includeFlags, helpContext) { + tagSelectionArea = new TagSelectionArea(getShell(), tagSource, includeFlags, helpContext) { protected void createCustomArea(Composite parent) { if(showRecurse) { final Button recurseCheck = new Button(parent, SWT.CHECK); @@ -172,10 +172,10 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis recurseCheck.addListener(SWT.Selection, event -> recurse = recurseCheck.getSelection()); recurseCheck.setSelection(true); } - } + } }; if (message != null) - tagSelectionArea.setTagAreaLabel(message); + tagSelectionArea.setTagAreaLabel(message); tagSelectionArea.addPropertyChangeListener(this); tagSelectionArea.createArea(top); tagSelectionArea.setRunnableContext(getRunnableContext()); @@ -187,8 +187,8 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis seperator.setLayoutData(data); updateEnablement(); - applyDialogFont(parent); - + applyDialogFont(parent); + return top; } @@ -241,23 +241,23 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis } } - public void propertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); - if (property.equals(TagSelectionArea.SELECTED_TAG)) { - selection = (CVSTag)event.getNewValue(); - updateEnablement(); - } else if (property.equals(TagSelectionArea.OPEN_SELECTED_TAG)) { - okPressed(); - } - } - - /** - * Creates a runnable context that allows refreshing the tags in the background. - * - * @since 3.1 - */ - private IRunnableContext getRunnableContext() { - return (fork, cancelable, runnable) -> { + public void propertyChange(PropertyChangeEvent event) { + String property = event.getProperty(); + if (property.equals(TagSelectionArea.SELECTED_TAG)) { + selection = (CVSTag)event.getNewValue(); + updateEnablement(); + } else if (property.equals(TagSelectionArea.OPEN_SELECTED_TAG)) { + okPressed(); + } + } + + /** + * Creates a runnable context that allows refreshing the tags in the background. + * + * @since 3.1 + */ + private IRunnableContext getRunnableContext() { + return (fork, cancelable, runnable) -> { final Job refreshJob = new Job(CVSUIMessages.TagSelectionDialog_7) { protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) @@ -283,19 +283,19 @@ public class TagSelectionDialog extends TrayDialog implements IPropertyChangeLis getShell().addDisposeListener(e -> refreshJob.cancel()); refreshJob.schedule(); }; - } - - private void setBusy(final boolean busy) { + } + + private void setBusy(final boolean busy) { final Shell shell = getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(() -> { - if (!shell.isDisposed()) { + if (!shell.isDisposed()) { Cursor cursor = null; if (busy) { cursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_APPSTARTING); } shell.setCursor(cursor); - } + } }); } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionWizardPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionWizardPage.java index 265bd6fc9..e285cf865 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionWizardPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSelectionWizardPage.java @@ -47,12 +47,12 @@ public class TagSelectionWizardPage extends CVSWizardPage { private Button selectTagButton; private boolean useResourceTag = false; private String helpContextId; - private TagSelectionArea tagArea; - private TagSource tagSource; + private TagSelectionArea tagArea; + private TagSource tagSource; public TagSelectionWizardPage(String pageName, String title, ImageDescriptor titleImage, String description, TagSource tagSource, int includeFlags) { super(pageName, title, titleImage, description); - this.tagSource = tagSource; + this.tagSource = tagSource; this.includeFlags = includeFlags; } @@ -64,7 +64,7 @@ public class TagSelectionWizardPage extends CVSWizardPage { public void setHelpContxtId(String helpContextId) { this.helpContextId = helpContextId; } - + @Override public void createControl(Composite parent) { @@ -77,7 +77,7 @@ public class TagSelectionWizardPage extends CVSWizardPage { // set F1 help if (helpContextId != null) - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContextId); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContextId); if (allowNoTag) { SelectionListener listener = new SelectionAdapter() { @@ -103,29 +103,29 @@ public class TagSelectionWizardPage extends CVSWizardPage { private void createTagArea() { tagArea = new TagSelectionArea(getShell(), tagSource, includeFlags, null); - tagArea.setRunnableContext(getContainer()); + tagArea.setRunnableContext(getContainer()); tagArea.createArea(composite); tagArea.addPropertyChangeListener(new IPropertyChangeListener() { - @Override + @Override public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(TagSelectionArea.SELECTED_TAG)) { - selectedTag = tagArea.getSelection(); - updateEnablement(); - } else if (event.getProperty().equals(TagSelectionArea.OPEN_SELECTED_TAG)) { - if (selectedTag != null) - gotoNextPage(); - } + if (event.getProperty().equals(TagSelectionArea.SELECTED_TAG)) { + selectedTag = tagArea.getSelection(); + updateEnablement(); + } else if (event.getProperty().equals(TagSelectionArea.OPEN_SELECTED_TAG)) { + if (selectedTag != null) + gotoNextPage(); + } - } - }); + } + }); refreshTagArea(); - } + } - private void refreshTagArea() { - if (tagArea != null) { - tagArea.refresh(); - tagArea.setSelection(selectedTag); - } + private void refreshTagArea() { + if (tagArea != null) { + tagArea.refresh(); + tagArea.setSelection(selectedTag); + } } protected void updateEnablement() { @@ -159,26 +159,26 @@ public class TagSelectionWizardPage extends CVSWizardPage { } } - /** - * Set the tag source used by this wizard page - * @param source the tag source - */ - public void setTagSource(TagSource source) { - this.tagSource = source; - tagArea.setTagSource(tagSource); - setSelection(null); - refreshTagArea(); - } + /** + * Set the tag source used by this wizard page + * @param source the tag source + */ + public void setTagSource(TagSource source) { + this.tagSource = source; + tagArea.setTagSource(tagSource); + setSelection(null); + refreshTagArea(); + } - /** - * Set the selection of the page to the given tag - * @param selectedTag - */ - public void setSelection(CVSTag selectedTag) { + /** + * Set the selection of the page to the given tag + * @param selectedTag + */ + public void setSelection(CVSTag selectedTag) { if (selectedTag == null && (includeFlags & TagSelectionArea.INCLUDE_HEAD_TAG) > 0) { this.selectedTag = CVSTag.DEFAULT; } else { - this.selectedTag = selectedTag; + this.selectedTag = selectedTag; } - } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSource.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSource.java index 303cb4be2..890142793 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSource.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSource.java @@ -27,157 +27,157 @@ import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; * A tag source provides access to a set of tags. */ public abstract class TagSource { - - /* - * Special constant representing the BASE tag - */ - public static final int BASE = -1; - - public static final TagSource EMPTY = new TagSource() { - @Override + + /* + * Special constant representing the BASE tag + */ + public static final int BASE = -1; + + public static final TagSource EMPTY = new TagSource() { + @Override public void commit(CVSTag[] tags, boolean replace, IProgressMonitor monitor) throws CVSException { - // No-op - } - @Override + // No-op + } + @Override public ICVSRepositoryLocation getLocation() { - // TODO Auto-generated method stub - return null; - } - @Override + // TODO Auto-generated method stub + return null; + } + @Override public String getShortDescription() { - return "Empty"; //$NON-NLS-1$ - } - @Override + return "Empty"; //$NON-NLS-1$ + } + @Override public CVSTag[] getTags(int type) { - return new CVSTag[0]; - } - @Override + return new CVSTag[0]; + } + @Override public CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException { - return new CVSTag[0]; - } - @Override + return new CVSTag[0]; + } + @Override public ICVSResource[] getCVSResources() { - return new ICVSResource[0]; - } - }; - + return new ICVSResource[0]; + } + }; + private ListenerList<ITagSourceChangeListener> listeners = new ListenerList<>(ListenerList.IDENTITY); - - /** - * Simple interface for providing notification when the tags - * for this source have changed. - */ - public interface ITagSourceChangeListener { - void tagsChanged(TagSource source); - } - - public static int[] convertIncludeFlaqsToTagTypes(int includeFlags) { + + /** + * Simple interface for providing notification when the tags + * for this source have changed. + */ + public interface ITagSourceChangeListener { + void tagsChanged(TagSource source); + } + + public static int[] convertIncludeFlaqsToTagTypes(int includeFlags) { List<Integer> types = new ArrayList<>(); - if ((includeFlags & TagSelectionArea.INCLUDE_BRANCHES) > 0) - types.add(Integer.valueOf(CVSTag.BRANCH)); - if ((includeFlags & TagSelectionArea.INCLUDE_VERSIONS) > 0) - types.add(Integer.valueOf(CVSTag.VERSION)); - if ((includeFlags & (TagSelectionArea.INCLUDE_HEAD_TAG)) > 0) - types.add(Integer.valueOf(CVSTag.HEAD)); - if ((includeFlags & (TagSelectionArea.INCLUDE_DATES)) > 0) - types.add(Integer.valueOf(CVSTag.DATE)); - if ((includeFlags & (TagSelectionArea.INCLUDE_BASE_TAG)) > 0) - types.add(Integer.valueOf(BASE)); - int[] result = new int[types.size()]; - for (int i = 0; i < result.length; i++) { - result[i] = types.get(i).intValue(); - - } - return result; - } - - /** - * Create a tag source for the given folders - * @param folders one or more folders - * @return a tag source for the supplied folders - */ - public static TagSource create(ICVSFolder[] folders) { - if (folders.length == 1) { - return new SingleFolderTagSource(folders[0]); - } else { - return new MultiFolderTagSource(folders); - } - } - - /** - * Create a tag source for a list of resources - * @param resources one or more resources - * @return a tag source - */ - public static TagSource create(ICVSResource[] resources) { - if (resources.length == 1 && !resources[0].isFolder()) - return new SingleFileTagSource((ICVSFile)resources[0]); - return create(getFolders(resources)); - } + if ((includeFlags & TagSelectionArea.INCLUDE_BRANCHES) > 0) + types.add(Integer.valueOf(CVSTag.BRANCH)); + if ((includeFlags & TagSelectionArea.INCLUDE_VERSIONS) > 0) + types.add(Integer.valueOf(CVSTag.VERSION)); + if ((includeFlags & (TagSelectionArea.INCLUDE_HEAD_TAG)) > 0) + types.add(Integer.valueOf(CVSTag.HEAD)); + if ((includeFlags & (TagSelectionArea.INCLUDE_DATES)) > 0) + types.add(Integer.valueOf(CVSTag.DATE)); + if ((includeFlags & (TagSelectionArea.INCLUDE_BASE_TAG)) > 0) + types.add(Integer.valueOf(BASE)); + int[] result = new int[types.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = types.get(i).intValue(); + + } + return result; + } + + /** + * Create a tag source for the given folders + * @param folders one or more folders + * @return a tag source for the supplied folders + */ + public static TagSource create(ICVSFolder[] folders) { + if (folders.length == 1) { + return new SingleFolderTagSource(folders[0]); + } else { + return new MultiFolderTagSource(folders); + } + } + + /** + * Create a tag source for a list of resources + * @param resources one or more resources + * @return a tag source + */ + public static TagSource create(ICVSResource[] resources) { + if (resources.length == 1 && !resources[0].isFolder()) + return new SingleFileTagSource((ICVSFile)resources[0]); + return create(getFolders(resources)); + } - private static ICVSFolder[] getFolders(ICVSResource[] resources) { + private static ICVSFolder[] getFolders(ICVSResource[] resources) { HashSet<ICVSFolder> result = new HashSet<>(); - for (int i= 0; i < resources.length; i++) { - result.add(getFirstFolder(resources[i])); + for (int i= 0; i < resources.length; i++) { + result.add(getFirstFolder(resources[i])); } - return result.toArray(new ICVSFolder[result.size()]); - } + return result.toArray(new ICVSFolder[result.size()]); + } - /** - * Create a tag source for a list of resources - * @param resources one or more resources - * @return a tag source - */ - public static TagSource create(IResource[] resources) { - return create(getCVSResources(getProjects(resources))); - } - - /** - * Create a tag source for the given mappers. - * @param mappers the mappers - * @return a tag source - */ - public static TagSource create(ResourceMapping[] mappers) { - return create(getCVSResources(getProjects(mappers))); - } - - private static IResource[] getProjects(ResourceMapping[] mappers) { + /** + * Create a tag source for a list of resources + * @param resources one or more resources + * @return a tag source + */ + public static TagSource create(IResource[] resources) { + return create(getCVSResources(getProjects(resources))); + } + + /** + * Create a tag source for the given mappers. + * @param mappers the mappers + * @return a tag source + */ + public static TagSource create(ResourceMapping[] mappers) { + return create(getCVSResources(getProjects(mappers))); + } + + private static IResource[] getProjects(ResourceMapping[] mappers) { Set<IProject> projects = new HashSet<>(); - for (int i = 0; i < mappers.length; i++) { - ResourceMapping mapper = mappers[i]; - projects.addAll(Arrays.asList(mapper.getProjects())); - } - return projects.toArray(new IResource[projects.size()]); - } + for (int i = 0; i < mappers.length; i++) { + ResourceMapping mapper = mappers[i]; + projects.addAll(Arrays.asList(mapper.getProjects())); + } + return projects.toArray(new IResource[projects.size()]); + } - private static IResource[] getProjects(IResource[] resources) { + private static IResource[] getProjects(IResource[] resources) { Set<IProject> result = new HashSet<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - result.add(resource.getProject()); - } - return result.toArray(new IResource[result.size()]); - } + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + result.add(resource.getProject()); + } + return result.toArray(new IResource[result.size()]); + } - /** - * Return a tag source for a single remote folder - * @param remote the remote folder - * @return a tag source for that folder - */ - public static TagSource create(ICVSRemoteFolder remote) { - return new SingleFolderTagSource(remote); - } - - private static ICVSResource[] getCVSResources(IResource[] resources) { + /** + * Return a tag source for a single remote folder + * @param remote the remote folder + * @return a tag source for that folder + */ + public static TagSource create(ICVSRemoteFolder remote) { + return new SingleFolderTagSource(remote); + } + + private static ICVSResource[] getCVSResources(IResource[] resources) { List<ICVSResource> cvsResources = new ArrayList<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - cvsResources.add(CVSWorkspaceRoot.getCVSResourceFor(resource)); - } - return cvsResources.toArray(new ICVSResource[cvsResources.size()]); - } + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + cvsResources.add(CVSWorkspaceRoot.getCVSResourceFor(resource)); + } + return cvsResources.toArray(new ICVSResource[cvsResources.size()]); + } - private static ICVSFolder getFirstFolder(ICVSResource resource) { + private static ICVSFolder getFirstFolder(ICVSResource resource) { if (resource.isFolder()) { return (ICVSFolder)resource; } else { @@ -185,84 +185,84 @@ public abstract class TagSource { } } - public CVSTag[] getTags(int type) { - switch (type) { - case BASE: - return new CVSTag[] { CVSTag.BASE }; - case CVSTag.HEAD: - return new CVSTag[] { CVSTag.DEFAULT }; - } - return new CVSTag[0]; - } - - public CVSTag[] getTags(int[] types) { - if (types.length == 0) { - return new CVSTag[0]; - } - if (types.length == 1) { - return getTags(types[0]); - } + public CVSTag[] getTags(int type) { + switch (type) { + case BASE: + return new CVSTag[] { CVSTag.BASE }; + case CVSTag.HEAD: + return new CVSTag[] { CVSTag.DEFAULT }; + } + return new CVSTag[0]; + } + + public CVSTag[] getTags(int[] types) { + if (types.length == 0) { + return new CVSTag[0]; + } + if (types.length == 1) { + return getTags(types[0]); + } List<CVSTag> result = new ArrayList<>(); - for (int i = 0; i < types.length; i++) { - int type = types[i]; - CVSTag[] tags = getTags(type); - result.addAll(Arrays.asList(tags)); - } - return result.toArray(new CVSTag[result.size()]); - } + for (int i = 0; i < types.length; i++) { + int type = types[i]; + CVSTag[] tags = getTags(type); + result.addAll(Arrays.asList(tags)); + } + return result.toArray(new CVSTag[result.size()]); + } - /** - * Refresh the tags by contacting the server if appropriate - * @param monitor a progress monitor - * @param bestEffort if best effort is true, then the whole folder contents may be searched - * @return any discovered tags - */ - public abstract CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException; - - public abstract ICVSRepositoryLocation getLocation(); + /** + * Refresh the tags by contacting the server if appropriate + * @param monitor a progress monitor + * @param bestEffort if best effort is true, then the whole folder contents may be searched + * @return any discovered tags + */ + public abstract CVSTag[] refresh(boolean bestEffort, IProgressMonitor monitor) throws TeamException; + + public abstract ICVSRepositoryLocation getLocation(); - /** - * Return a short description of the tag source for displaying in UI. - * @return a short description of the tag source for displaying in UI. - */ - public abstract String getShortDescription(); + /** + * Return a short description of the tag source for displaying in UI. + * @return a short description of the tag source for displaying in UI. + */ + public abstract String getShortDescription(); - /** - * Commit a set of tag changes to the tag cache - * @param tags the tags that should be cached - * @param replace whether existing tags not in the list should be removed - * @param monitor a progress monitor - * @throws CVSException - */ - public abstract void commit(CVSTag[] tags, boolean replace, IProgressMonitor monitor) throws CVSException; - - public void addListener(ITagSourceChangeListener listener) { - listeners.add(listener); - } + /** + * Commit a set of tag changes to the tag cache + * @param tags the tags that should be cached + * @param replace whether existing tags not in the list should be removed + * @param monitor a progress monitor + * @throws CVSException + */ + public abstract void commit(CVSTag[] tags, boolean replace, IProgressMonitor monitor) throws CVSException; + + public void addListener(ITagSourceChangeListener listener) { + listeners.add(listener); + } - public void removeListener(ITagSourceChangeListener listener) { - listeners.remove(listener); - } - - /** - * Notify all listeners that the tags from this source may have changed - */ - public void fireChange() { - Object[] list = listeners.getListeners(); - for (int i = 0; i < list.length; i++) { - final ITagSourceChangeListener listener = (ITagSourceChangeListener)list[i]; - SafeRunner.run(new ISafeRunnable() { - @Override + public void removeListener(ITagSourceChangeListener listener) { + listeners.remove(listener); + } + + /** + * Notify all listeners that the tags from this source may have changed + */ + public void fireChange() { + Object[] list = listeners.getListeners(); + for (int i = 0; i < list.length; i++) { + final ITagSourceChangeListener listener = (ITagSourceChangeListener)list[i]; + SafeRunner.run(new ISafeRunnable() { + @Override public void handleException(Throwable exception) { - // logged by run - } - @Override + // logged by run + } + @Override public void run() throws Exception { - listener.tagsChanged(TagSource.this); - } - }); - } - } - - public abstract ICVSResource[] getCVSResources(); + listener.tagsChanged(TagSource.this); + } + }); + } + } + + public abstract ICVSResource[] getCVSResources(); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceResourceAdapter.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceResourceAdapter.java index dbdf19a15..744fc482d 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceResourceAdapter.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceResourceAdapter.java @@ -28,55 +28,55 @@ import org.eclipse.ui.model.IWorkbenchAdapter; */ public class TagSourceResourceAdapter implements IAdaptable, IWorkbenchAdapter { - public static Object getViewerInput(TagSource tagSource) { - return new TagSourceResourceAdapter(tagSource); - } - - TagSource tagSource; + public static Object getViewerInput(TagSource tagSource) { + return new TagSourceResourceAdapter(tagSource); + } + + TagSource tagSource; - private TagSourceResourceAdapter(TagSource tagSource) { - this.tagSource = tagSource; - } - - @Override + private TagSourceResourceAdapter(TagSource tagSource) { + this.tagSource = tagSource; + } + + @Override public Object[] getChildren(Object o) { - ICVSResource[] children = tagSource.getCVSResources(); - if (children.length == 0) return new Object[0]; + ICVSResource[] children = tagSource.getCVSResources(); + if (children.length == 0) return new Object[0]; List<CVSResourceElement> result = new ArrayList<>(); - for (int i = 0; i < children.length; i++) { - ICVSResource resource = children[i]; - if (resource.isFolder()) { - result.add(new CVSFolderElement((ICVSFolder)resource, false)); - } else { - result.add(new CVSFileElement((ICVSFile)resource)); - } - } - return result.toArray(new Object[result.size()]); - } + for (int i = 0; i < children.length; i++) { + ICVSResource resource = children[i]; + if (resource.isFolder()) { + result.add(new CVSFolderElement((ICVSFolder)resource, false)); + } else { + result.add(new CVSFileElement((ICVSFile)resource)); + } + } + return result.toArray(new Object[result.size()]); + } - @Override + @Override public ImageDescriptor getImageDescriptor(Object object) { - // No image descriptor - return null; - } + // No image descriptor + return null; + } - @Override + @Override public String getLabel(Object o) { - return tagSource.getShortDescription(); - } + return tagSource.getShortDescription(); + } - @Override + @Override public Object getParent(Object o) { - // No parent - return null; - } + // No parent + return null; + } - @Override + @Override public <T> T getAdapter(Class<T> adapter) { - if (adapter == IWorkbenchAdapter.class) { - return adapter.cast(this); - } - return null; - } + if (adapter == IWorkbenchAdapter.class) { + return adapter.cast(this); + } + return null; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceWorkbenchAdapter.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceWorkbenchAdapter.java index 863d291ce..075e8af25 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceWorkbenchAdapter.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagSourceWorkbenchAdapter.java @@ -30,9 +30,9 @@ import org.eclipse.ui.model.IWorkbenchAdapter; */ public class TagSourceWorkbenchAdapter implements IAdaptable, IWorkbenchAdapter { - /** - * Constants for configuring which types of tags should be displayed. - */ + /** + * Constants for configuring which types of tags should be displayed. + */ public static final int INCLUDE_HEAD_TAG = 1; public static final int INCLUDE_BASE_TAG = 2; public static final int INCLUDE_BRANCHES = 4; @@ -86,26 +86,26 @@ public class TagSourceWorkbenchAdapter implements IAdaptable, IWorkbenchAdapter } - /** - * Create a viewer input for the tag source - * @param tagSource the tag source - * @param includeFlags the types of tags to include - * @return a tree viewer input - */ - public static Object createInput(TagSource tagSource, int includeFlags) { - if (includeFlags == INCLUDE_VERSIONS) { - // Versions only is requested by the merge start page. - // Only need to show version tags - return new TagRootElement(null, tagSource, CVSTag.VERSION); - } - return new TagSourceWorkbenchAdapter(tagSource, includeFlags); - } - + /** + * Create a viewer input for the tag source + * @param tagSource the tag source + * @param includeFlags the types of tags to include + * @return a tree viewer input + */ + public static Object createInput(TagSource tagSource, int includeFlags) { + if (includeFlags == INCLUDE_VERSIONS) { + // Versions only is requested by the merge start page. + // Only need to show version tags + return new TagRootElement(null, tagSource, CVSTag.VERSION); + } + return new TagSourceWorkbenchAdapter(tagSource, includeFlags); + } + public TagSourceWorkbenchAdapter(TagSource tagSource, int includeFlags) { this.includeFlags = includeFlags; if (this.includeFlags == 0) this.includeFlags = INCLUDE_ALL_TAGS; if ((includeFlags & INCLUDE_BRANCHES) > 0) { - branches = new TagRootElement(this, tagSource, CVSTag.BRANCH); + branches = new TagRootElement(this, tagSource, CVSTag.BRANCH); } if ((includeFlags & INCLUDE_VERSIONS) > 0) { versions = new TagRootElement(this, tagSource, CVSTag.VERSION); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/AddWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/AddWizard.java index 7144e81c9..4aa2694ef 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/AddWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/AddWizard.java @@ -31,12 +31,12 @@ import org.eclipse.ui.PlatformUI; public class AddWizard extends ResizableWizard { - private final AddOperation op; - private final IFile[] unknowns; - private CommitWizardFileTypePage fFileTypePage; + private final AddOperation op; + private final IFile[] unknowns; + private CommitWizardFileTypePage fFileTypePage; - public static void run(Shell shell, final AddOperation op) throws InvocationTargetException, InterruptedException { - // Prompt if there are files of unknown type being added + public static void run(Shell shell, final AddOperation op) throws InvocationTargetException, InterruptedException { + // Prompt if there are files of unknown type being added PlatformUI.getWorkbench().getProgressService().run(true, true, monitor -> { try { op.buildScope(monitor); @@ -44,17 +44,17 @@ public class AddWizard extends ResizableWizard { throw new InvocationTargetException(e); } }); - - IFile[] unknowns = getUnaddedWithUnknownFileType(op.getTraversals()); - if (unknowns.length == 0) { - op.run(); - } else { - AddWizard wizard = new AddWizard(op, unknowns); - ResizableWizard.open(shell, wizard); - } - } - - private static IFile[] getUnaddedWithUnknownFileType(final ResourceTraversal[] traversals) throws InvocationTargetException, InterruptedException { + + IFile[] unknowns = getUnaddedWithUnknownFileType(op.getTraversals()); + if (unknowns.length == 0) { + op.run(); + } else { + AddWizard wizard = new AddWizard(op, unknowns); + ResizableWizard.open(shell, wizard); + } + } + + private static IFile[] getUnaddedWithUnknownFileType(final ResourceTraversal[] traversals) throws InvocationTargetException, InterruptedException { final List<IResource> unadded = new ArrayList<>(); PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { final IFileContentManager manager = Team.getFileContentManager(); @@ -88,77 +88,77 @@ public class AddWizard extends ResizableWizard { throw new InvocationTargetException(e); } } - } + } }); - return unadded.toArray(new IFile[unadded.size()]); - } - - public AddWizard(AddOperation op, IFile[] unknowns) { - super("AddWizard", CVSUIPlugin.getPlugin().getDialogSettings()); //$NON-NLS-1$ - this.op = op; - this.unknowns = unknowns; - setWindowTitle(CVSUIMessages.AddWizard_0); - setDefaultPageImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_NEW_LOCATION)); - } - - @Override - public void addPages() { - - final Collection<String> names= new HashSet<String>(); - final Collection<String> extensions= new HashSet<String>(); - getUnknownNamesAndExtension(unknowns, names, extensions); - - if (names.size() + extensions.size() > 0) { - fFileTypePage= new CommitWizardFileTypePage(extensions, names); - addPage(fFileTypePage); - } - - super.addPages(); - } - - private static void getUnknownNamesAndExtension(IFile[] files, Collection<String> names, Collection<String> extensions) { - - final IFileContentManager manager= Team.getFileContentManager(); - - for (int i = 0; i < files.length; i++) { - IFile file = files[i]; - - final String extension= file.getFileExtension(); - if (extension != null && !manager.isKnownExtension(extension)) { - extensions.add(extension); - } - - final String name= file.getName(); - if (extension == null && name != null && !manager.isKnownFilename(name)) - names.add(name); - } - } - - @Override + return unadded.toArray(new IFile[unadded.size()]); + } + + public AddWizard(AddOperation op, IFile[] unknowns) { + super("AddWizard", CVSUIPlugin.getPlugin().getDialogSettings()); //$NON-NLS-1$ + this.op = op; + this.unknowns = unknowns; + setWindowTitle(CVSUIMessages.AddWizard_0); + setDefaultPageImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_NEW_LOCATION)); + } + + @Override + public void addPages() { + + final Collection<String> names= new HashSet<String>(); + final Collection<String> extensions= new HashSet<String>(); + getUnknownNamesAndExtension(unknowns, names, extensions); + + if (names.size() + extensions.size() > 0) { + fFileTypePage= new CommitWizardFileTypePage(extensions, names); + addPage(fFileTypePage); + } + + super.addPages(); + } + + private static void getUnknownNamesAndExtension(IFile[] files, Collection<String> names, Collection<String> extensions) { + + final IFileContentManager manager= Team.getFileContentManager(); + + for (int i = 0; i < files.length; i++) { + IFile file = files[i]; + + final String extension= file.getFileExtension(); + if (extension != null && !manager.isKnownExtension(extension)) { + extensions.add(extension); + } + + final String name= file.getName(); + if (extension == null && name != null && !manager.isKnownFilename(name)) + names.add(name); + } + } + + @Override public boolean performFinish() { - final Map extensionsToSave= new HashMap(); - final Map extensionsNotToSave= new HashMap(); - - fFileTypePage.getModesForExtensions(extensionsToSave, extensionsNotToSave); - CommitWizardFileTypePage.saveExtensionMappings(extensionsToSave); - op.addModesForExtensions(extensionsNotToSave); - - final Map namesToSave= new HashMap(); - final Map namesNotToSave= new HashMap(); - - fFileTypePage.getModesForNames(namesToSave, namesNotToSave); - CommitWizardFileTypePage.saveNameMappings(namesToSave); - op.addModesForNames(namesNotToSave); - - try { - op.run(); - } catch (InvocationTargetException e) { - return false; - } catch (InterruptedException e) { - return false; - } - - return super.performFinish(); - } - + final Map extensionsToSave= new HashMap(); + final Map extensionsNotToSave= new HashMap(); + + fFileTypePage.getModesForExtensions(extensionsToSave, extensionsNotToSave); + CommitWizardFileTypePage.saveExtensionMappings(extensionsToSave); + op.addModesForExtensions(extensionsNotToSave); + + final Map namesToSave= new HashMap(); + final Map namesNotToSave= new HashMap(); + + fFileTypePage.getModesForNames(namesToSave, namesNotToSave); + CommitWizardFileTypePage.saveNameMappings(namesToSave); + op.addModesForNames(namesNotToSave); + + try { + op.run(); + } catch (InvocationTargetException e) { + return false; + } catch (InterruptedException e) { + return false; + } + + return super.performFinish(); + } + } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CVSWizardPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CVSWizardPage.java index 81076abd3..48d0f85d4 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CVSWizardPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CVSWizardPage.java @@ -40,7 +40,7 @@ import org.eclipse.ui.views.navigator.ResourceComparator; * for widget creation. */ public abstract class CVSWizardPage extends WizardPage { - + protected static final int LABEL_WIDTH_HINT = 400; protected static final int LABEL_INDENT_WIDTH = 32; protected static final int LIST_HEIGHT_HINT = 100; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsLocationSelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsLocationSelectionPage.java index 060b5b321..111b1ef9d 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsLocationSelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsLocationSelectionPage.java @@ -55,12 +55,12 @@ public class CheckoutAsLocationSelectionPage extends CVSWizardPage { // constants private static final int SIZING_TEXT_FIELD_WIDTH = 250; - private static final int COMBO_HISTORY_LENGTH = 5; + private static final int COMBO_HISTORY_LENGTH = 5; + + // store id constants + private static final String STORE_PREVIOUS_LOCATIONS = + "CheckoutAsLocationSelectionPage.STORE_PREVIOUS_LOCATIONS";//$NON-NLS-1$ - // store id constants - private static final String STORE_PREVIOUS_LOCATIONS = - "CheckoutAsLocationSelectionPage.STORE_PREVIOUS_LOCATIONS";//$NON-NLS-1$ - /** * @param pageName * @param title @@ -110,7 +110,7 @@ public class CheckoutAsLocationSelectionPage extends CVSWizardPage { // required in order to use setButtonLayoutData initializeDialogUnits(composite); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.CHECKOUT_LOCATION_SELECTION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.CHECKOUT_LOCATION_SELECTION_PAGE); final Button useDefaultsButton = new Button(composite, SWT.CHECK | SWT.RIGHT); @@ -118,7 +118,7 @@ public class CheckoutAsLocationSelectionPage extends CVSWizardPage { useDefaultsButton.setSelection(this.useDefaults); createUserSpecifiedProjectLocationGroup(composite, !this.useDefaults); - initializeValues(); + initializeValues(); SelectionListener listener = new SelectionAdapter() { @Override @@ -132,7 +132,7 @@ public class CheckoutAsLocationSelectionPage extends CVSWizardPage { } }; useDefaultsButton.addSelectionListener(listener); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } /** @@ -182,77 +182,77 @@ public class CheckoutAsLocationSelectionPage extends CVSWizardPage { return projectGroup; } - /** - * Initializes states of the controls. - */ - private void initializeValues() { - // Set remembered values - IDialogSettings settings = getDialogSettings(); - if (settings != null) { - String[] previouseLocations = settings.getArray(STORE_PREVIOUS_LOCATIONS); - if (previouseLocations != null) { - for (int i = 0; i < previouseLocations.length; i++) { - if(isSingleFolder()) - locationPathField.add(new Path(previouseLocations[i]).append(getSingleProject().getName()).toOSString()); - else - locationPathField.add(previouseLocations[i]); - } - } - } - } - - /** - * Saves the widget values - */ - private void saveWidgetValues() { - // Update history - IDialogSettings settings = getDialogSettings(); - if (settings != null) { - String[] previouseLocations = settings.getArray(STORE_PREVIOUS_LOCATIONS); - if (previouseLocations == null) previouseLocations = new String[0]; - if(isSingleFolder()) - previouseLocations = addToHistory(previouseLocations, new Path(locationPathField.getText()).removeLastSegments(1).toOSString()); - else - previouseLocations = addToHistory(previouseLocations, locationPathField.getText()); - settings.put(STORE_PREVIOUS_LOCATIONS, previouseLocations); - } - } + /** + * Initializes states of the controls. + */ + private void initializeValues() { + // Set remembered values + IDialogSettings settings = getDialogSettings(); + if (settings != null) { + String[] previouseLocations = settings.getArray(STORE_PREVIOUS_LOCATIONS); + if (previouseLocations != null) { + for (int i = 0; i < previouseLocations.length; i++) { + if(isSingleFolder()) + locationPathField.add(new Path(previouseLocations[i]).append(getSingleProject().getName()).toOSString()); + else + locationPathField.add(previouseLocations[i]); + } + } + } + } + + /** + * Saves the widget values + */ + private void saveWidgetValues() { + // Update history + IDialogSettings settings = getDialogSettings(); + if (settings != null) { + String[] previouseLocations = settings.getArray(STORE_PREVIOUS_LOCATIONS); + if (previouseLocations == null) previouseLocations = new String[0]; + if(isSingleFolder()) + previouseLocations = addToHistory(previouseLocations, new Path(locationPathField.getText()).removeLastSegments(1).toOSString()); + else + previouseLocations = addToHistory(previouseLocations, locationPathField.getText()); + settings.put(STORE_PREVIOUS_LOCATIONS, previouseLocations); + } + } - /** - * Adds an entry to a history, while taking care of duplicate history items - * and excessively long histories. The assumption is made that all histories - * should be of length <code>CheckoutAsLocationSelectionPage.COMBO_HISTORY_LENGTH</code>. - * - * @param history the current history - * @param newEntry the entry to add to the history - * @return the history with the new entry appended - */ - private String[] addToHistory(String[] history, String newEntry) { + /** + * Adds an entry to a history, while taking care of duplicate history items + * and excessively long histories. The assumption is made that all histories + * should be of length <code>CheckoutAsLocationSelectionPage.COMBO_HISTORY_LENGTH</code>. + * + * @param history the current history + * @param newEntry the entry to add to the history + * @return the history with the new entry appended + */ + private String[] addToHistory(String[] history, String newEntry) { ArrayList<String> l = new ArrayList<>(Arrays.asList(history)); - addToHistory(l, newEntry); - String[] r = new String[l.size()]; - l.toArray(r); - return r; - } - - /** - * Adds an entry to a history, while taking care of duplicate history items - * and excessively long histories. The assumption is made that all histories - * should be of length <code>CheckoutAsLocationSelectionPage.COMBO_HISTORY_LENGTH</code>. - * - * @param history the current history - * @param newEntry the entry to add to the history - */ + addToHistory(l, newEntry); + String[] r = new String[l.size()]; + l.toArray(r); + return r; + } + + /** + * Adds an entry to a history, while taking care of duplicate history items + * and excessively long histories. The assumption is made that all histories + * should be of length <code>CheckoutAsLocationSelectionPage.COMBO_HISTORY_LENGTH</code>. + * + * @param history the current history + * @param newEntry the entry to add to the history + */ private void addToHistory(List<String> history, String newEntry) { - history.remove(newEntry); - history.add(0,newEntry); - - // since only one new item was added, we can be over the limit - // by at most one item - if (history.size() > COMBO_HISTORY_LENGTH) - history.remove(COMBO_HISTORY_LENGTH); - } - + history.remove(newEntry); + history.add(0,newEntry); + + // since only one new item was added, we can be over the limit + // by at most one item + if (history.size() > COMBO_HISTORY_LENGTH) + history.remove(COMBO_HISTORY_LENGTH); + } + /** * Check if the entry in the widget location is valid. If it is valid return null. Otherwise * return a string that indicates the problem. @@ -384,9 +384,9 @@ public class CheckoutAsLocationSelectionPage extends CVSWizardPage { */ public String getTargetLocation() { if (isCustomLocationSpecified()) { - saveWidgetValues(); - return targetLocation; - } + saveWidgetValues(); + return targetLocation; + } return null; } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsMainPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsMainPage.java index 4a2dc12ad..69a4a9d5e 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsMainPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsMainPage.java @@ -74,7 +74,7 @@ public class CheckoutAsMainPage extends CVSWizardPage { Composite composite = createComposite(parent, 1, false); setControl(composite); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.CHECKOUT_CONFIGURATION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.CHECKOUT_CONFIGURATION_PAGE); if (isSingleFolder()) { createSingleFolderArea(composite); @@ -83,7 +83,7 @@ public class CheckoutAsMainPage extends CVSWizardPage { } updateEnablements(); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } /* diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsProjectSelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsProjectSelectionPage.java index a3de224d6..53f47a364 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsProjectSelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsProjectSelectionPage.java @@ -87,7 +87,7 @@ public class CheckoutAsProjectSelectionPage extends CVSWizardPage { Composite composite= createComposite(parent, 2, false); setControl(composite); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.CHECKOUT_PROJECT_SELECTION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.CHECKOUT_PROJECT_SELECTION_PAGE); if (isSingleFolder()) { createLabel(composite, CVSUIMessages.CheckoutAsProjectSelectionPage_name); @@ -123,7 +123,7 @@ public class CheckoutAsProjectSelectionPage extends CVSWizardPage { initializeValues(); updateWidgetEnablements(); tree.getControl().setFocus(); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } /** diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsWizard.java index 0494a1d92..7bae109da 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutAsWizard.java @@ -70,22 +70,22 @@ public class CheckoutAsWizard extends Wizard { } } - /** - * Return the settings used for all CheckoutAsWizard pages - */ - public static IDialogSettings getCheckoutAsDialogSettings() { - IDialogSettings workbenchSettings = CVSUIPlugin.getPlugin().getDialogSettings(); - IDialogSettings section = workbenchSettings.getSection("CheckoutAsWizard");//$NON-NLS-1$ - if (section == null) { - section = workbenchSettings.addNewSection("CheckoutAsWizard");//$NON-NLS-1$ - } - return section; - } - + /** + * Return the settings used for all CheckoutAsWizard pages + */ + public static IDialogSettings getCheckoutAsDialogSettings() { + IDialogSettings workbenchSettings = CVSUIPlugin.getPlugin().getDialogSettings(); + IDialogSettings section = workbenchSettings.getSection("CheckoutAsWizard");//$NON-NLS-1$ + if (section == null) { + section = workbenchSettings.addNewSection("CheckoutAsWizard");//$NON-NLS-1$ + } + return section; + } + public CheckoutAsWizard(IWorkbenchPart part, ICVSRemoteFolder[] remoteFolders, boolean allowProjectConfiguration) { this.part = part; this.remoteFolders = remoteFolders; - setDialogSettings(getCheckoutAsDialogSettings()); + setDialogSettings(getCheckoutAsDialogSettings()); setWindowTitle(CVSUIMessages.CheckoutAsWizard_title); this.allowProjectConfiguration = allowProjectConfiguration; } @@ -105,11 +105,11 @@ public class CheckoutAsWizard extends Wizard { addPage(locationSelectionPage); tagSelectionPage = new TagSelectionWizardPage("tagPage", CVSUIMessages.CheckoutAsWizard_3, substImage, CVSUIMessages.CheckoutAsWizard_4, TagSource.create(remoteFolders), //$NON-NLS-1$ - TagSelectionArea.INCLUDE_HEAD_TAG | - TagSelectionArea.INCLUDE_BRANCHES | - TagSelectionArea.INCLUDE_VERSIONS | - TagSelectionArea.INCLUDE_DATES - ); + TagSelectionArea.INCLUDE_HEAD_TAG | + TagSelectionArea.INCLUDE_BRANCHES | + TagSelectionArea.INCLUDE_VERSIONS | + TagSelectionArea.INCLUDE_DATES + ); if (remoteFolders.length > 0) { try { CVSTag selectedTag = remoteFolders[0].getFolderSyncInfo().getTag(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizard.java index c42d365db..1e98440b5 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizard.java @@ -55,84 +55,84 @@ import org.eclipse.ui.PlatformUI; * of a set of <code>SyncInfo</code>. */ public class CommitWizard extends ResizableWizard { - + public static final String COMMIT_WIZARD_DIALOG_SETTINGS = "CommitWizard"; //$NON-NLS-1$ - /** - * An operation to add and commit resources to a CVS repository. - */ - public static class AddAndCommitOperation extends CVSOperation { - - private final IResource[] fAllResources; - private final String fComment; - - private Map fModesForExtensionsForOneTime; - private Map fModesForNamesForOneTime; - - private IResource[] fNewResources; + /** + * An operation to add and commit resources to a CVS repository. + */ + public static class AddAndCommitOperation extends CVSOperation { + + private final IResource[] fAllResources; + private final String fComment; + + private Map fModesForExtensionsForOneTime; + private Map fModesForNamesForOneTime; + + private IResource[] fNewResources; private IJobChangeListener jobListener; - - public AddAndCommitOperation(IWorkbenchPart part, IResource[] allResources, IResource[] newResources, String comment) { - super(part); - fAllResources = allResources; - fNewResources = newResources; - fModesForExtensionsForOneTime = Collections.EMPTY_MAP; - fModesForNamesForOneTime= Collections.EMPTY_MAP; - fComment = comment; - } - - public void setModesForExtensionsForOneTime(Map modes) { - if (modes != null) - fModesForExtensionsForOneTime= modes; - } - - public void setModesForNamesForOneTime(Map modes) { - if (modes != null) - fModesForNamesForOneTime= modes; - } - - @Override + + public AddAndCommitOperation(IWorkbenchPart part, IResource[] allResources, IResource[] newResources, String comment) { + super(part); + fAllResources = allResources; + fNewResources = newResources; + fModesForExtensionsForOneTime = Collections.EMPTY_MAP; + fModesForNamesForOneTime= Collections.EMPTY_MAP; + fComment = comment; + } + + public void setModesForExtensionsForOneTime(Map modes) { + if (modes != null) + fModesForExtensionsForOneTime= modes; + } + + public void setModesForNamesForOneTime(Map modes) { + if (modes != null) + fModesForNamesForOneTime= modes; + } + + @Override protected void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { - try { - monitor.beginTask(null, (fNewResources.length + fAllResources.length) * 100); - if (fNewResources.length > 0) { - final AddOperation op= new AddOperation(getPart(), RepositoryProviderOperation.asResourceMappers(fNewResources)); - op.addModesForExtensions(fModesForExtensionsForOneTime); - op.addModesForNames(fModesForNamesForOneTime); - op.run(Policy.subMonitorFor(monitor, fNewResources.length * 100)); - } - if (fAllResources.length > 0) { - CommitOperation commitOperation = new CommitOperation(getPart(), RepositoryProviderOperation.asResourceMappers(fAllResources), new Command.LocalOption[0], fComment) { - @Override + try { + monitor.beginTask(null, (fNewResources.length + fAllResources.length) * 100); + if (fNewResources.length > 0) { + final AddOperation op= new AddOperation(getPart(), RepositoryProviderOperation.asResourceMappers(fNewResources)); + op.addModesForExtensions(fModesForExtensionsForOneTime); + op.addModesForNames(fModesForNamesForOneTime); + op.run(Policy.subMonitorFor(monitor, fNewResources.length * 100)); + } + if (fAllResources.length > 0) { + CommitOperation commitOperation = new CommitOperation(getPart(), RepositoryProviderOperation.asResourceMappers(fAllResources), new Command.LocalOption[0], fComment) { + @Override public boolean consultModelsForMappings() { - // Do not consult models from the commit wizard - return false; - } - }; + // Do not consult models from the commit wizard + return false; + } + }; commitOperation.run(Policy.subMonitorFor(monitor, fAllResources.length * 100)); - } - } catch (InvocationTargetException e) { - throw CVSException.wrapException(e); - } finally { - monitor.done(); - } - } - - @Override + } + } catch (InvocationTargetException e) { + throw CVSException.wrapException(e); + } finally { + monitor.done(); + } + } + + @Override protected String getJobName() { - return CVSUIMessages.CommitWizard_0; - } - - @Override + return CVSUIMessages.CommitWizard_0; + } + + @Override protected String getTaskName() { - return CVSUIMessages.CommitWizard_1; - } + return CVSUIMessages.CommitWizard_1; + } - /* - * Set the job listener. It will only recieve scheduled and done - * events as these are what are used by a sync model operation - * to show busy state in the sync view. - */ + /* + * Set the job listener. It will only recieve scheduled and done + * events as these are what are used by a sync model operation + * to show busy state in the sync view. + */ protected void setJobChangeListener(IJobChangeListener jobListener) { this.jobListener = jobListener; } @@ -150,36 +150,36 @@ public class CommitWizard extends ResizableWizard { if (jobListener != null) jobListener.scheduled(event); } - } - - private final IResource[] fResources; - private IResource[] fUnaddedDiffs; - private final ModelSynchronizeParticipant fParticipant; - - private CommitWizardFileTypePage fFileTypePage; - private CommitWizardCommitPage fCommitPage; + } + + private final IResource[] fResources; + private IResource[] fUnaddedDiffs; + private final ModelSynchronizeParticipant fParticipant; + + private CommitWizardFileTypePage fFileTypePage; + private CommitWizardCommitPage fCommitPage; private IJobChangeListener jobListener; private IWorkbenchPart part; - - public CommitWizard(SyncInfoSet infos) throws CVSException { - this(infos.getResources()); - } - - public CommitWizard(final IResource [] resources) throws CVSException { - - super(COMMIT_WIZARD_DIALOG_SETTINGS, CVSUIPlugin.getPlugin().getDialogSettings()); - - setNeedsProgressMonitor(true); - setWindowTitle(CVSUIMessages.CommitWizard_2); - setDefaultPageImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_NEW_LOCATION)); - - fResources= resources; - ResourceMapping[] mappings = Utils.getResourceMappings(resources); - fParticipant = createWorkspaceParticipant(mappings, getShell()); + + public CommitWizard(SyncInfoSet infos) throws CVSException { + this(infos.getResources()); + } + + public CommitWizard(final IResource [] resources) throws CVSException { + + super(COMMIT_WIZARD_DIALOG_SETTINGS, CVSUIPlugin.getPlugin().getDialogSettings()); + + setNeedsProgressMonitor(true); + setWindowTitle(CVSUIMessages.CommitWizard_2); + setDefaultPageImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_NEW_LOCATION)); + + fResources= resources; + ResourceMapping[] mappings = Utils.getResourceMappings(resources); + fParticipant = createWorkspaceParticipant(mappings, getShell()); - getAllOutOfSync(); - fUnaddedDiffs = getUnaddedResources(getDiffTree().getAffectedResources()); - } + getAllOutOfSync(); + fUnaddedDiffs = getUnaddedResources(getDiffTree().getAffectedResources()); + } private ModelSynchronizeParticipant createWorkspaceParticipant(ResourceMapping[] selectedMappings, Shell shell) { ISynchronizationScopeManager manager = WorkspaceSubscriberContext.createWorkspaceScopeManager(selectedMappings, true, CommitAction.isIncludeChangeSets(shell, CVSUIMessages.SyncAction_1)); @@ -202,18 +202,18 @@ public class CommitWizard extends ResizableWizard { } } - public boolean hasOutgoingChanges() { - IResourceDiffTree tree = getDiffTree(); + public boolean hasOutgoingChanges() { + IResourceDiffTree tree = getDiffTree(); return tree != null && tree.hasMatchingDiffs(ResourcesPlugin.getWorkspace().getRoot().getFullPath(), new FastDiffFilter() { @Override public boolean select(IDiff diff) { return AbstractCommitAction.hasLocalChange(diff); } }); - } - - boolean hasConflicts() { - IResourceDiffTree tree = getDiffTree(); + } + + boolean hasConflicts() { + IResourceDiffTree tree = getDiffTree(); return tree != null && tree.hasMatchingDiffs(ResourcesPlugin.getWorkspace().getRoot().getFullPath(), new FastDiffFilter() { @Override public boolean select(IDiff diff) { @@ -225,156 +225,156 @@ public class CommitWizard extends ResizableWizard { } }); } - - public int getHighestProblemSeverity() { + + public int getHighestProblemSeverity() { IResource[] resources = getDiffTree().getAffectedResources(); - int mostSeriousSeverity = -1; - - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - try { - int severity = resource.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO); - if (severity > mostSeriousSeverity) { + int mostSeriousSeverity = -1; + + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + try { + int severity = resource.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO); + if (severity > mostSeriousSeverity) { mostSeriousSeverity = severity; } } catch (CoreException e) { } - } - - return mostSeriousSeverity; - } + } + + return mostSeriousSeverity; + } IResourceDiffTree getDiffTree() { return fParticipant.getContext().getDiffTree(); } - public CommitWizardFileTypePage getFileTypePage() { - return fFileTypePage; - } + public CommitWizardFileTypePage getFileTypePage() { + return fFileTypePage; + } - public CommitWizardCommitPage getCommitPage() { - return fCommitPage; - } + public CommitWizardCommitPage getCommitPage() { + return fCommitPage; + } public ModelSynchronizeParticipant getParticipant() { - return fParticipant; - } + return fParticipant; + } - @Override + @Override public boolean canFinish() { - final IWizardPage current= getContainer().getCurrentPage(); - if (current == fFileTypePage && fCommitPage != null) - return false; - return super.canFinish(); - } + final IWizardPage current= getContainer().getCurrentPage(); + if (current == fFileTypePage && fCommitPage != null) + return false; + return super.canFinish(); + } - @Override + @Override public boolean performFinish() { - - final String comment= fCommitPage.getComment(getShell()); - if (comment == null) - return false; - - IResource[] resources = AbstractCommitAction.getOutgoingChanges(getDiffTree(), fCommitPage.getTraversalsToCommit(), null); - if (resources.length == 0) + + final String comment= fCommitPage.getComment(getShell()); + if (comment == null) + return false; + + IResource[] resources = AbstractCommitAction.getOutgoingChanges(getDiffTree(), fCommitPage.getTraversalsToCommit(), null); + if (resources.length == 0) return true; - - final IResource[] unadded; - try { - unadded = getUnaddedResources(resources); - } catch (CVSException e1) { - return false; - } - - final IResource[] files = getFiles(resources); - - final AddAndCommitOperation operation= new AddAndCommitOperation(getPart(), files, unadded, comment); - if (jobListener != null) - operation.setJobChangeListener(jobListener); - - if (fFileTypePage != null) { - final Map extensionsToSave= new HashMap(); - final Map extensionsNotToSave= new HashMap(); - - fFileTypePage.getModesForExtensions(extensionsToSave, extensionsNotToSave); - CommitWizardFileTypePage.saveExtensionMappings(extensionsToSave); - operation.setModesForExtensionsForOneTime(extensionsNotToSave); - - final Map namesToSave= new HashMap(); - final Map namesNotToSave= new HashMap(); - - fFileTypePage.getModesForNames(namesToSave, namesNotToSave); - CommitWizardFileTypePage.saveNameMappings(namesToSave); - operation.setModesForNamesForOneTime(namesNotToSave); - } - - try { - operation.run(); - } catch (InvocationTargetException e) { - return false; - } catch (InterruptedException e) { - return false; - } - - fCommitPage.finish(); - return super.performFinish(); - } - - @Override + + final IResource[] unadded; + try { + unadded = getUnaddedResources(resources); + } catch (CVSException e1) { + return false; + } + + final IResource[] files = getFiles(resources); + + final AddAndCommitOperation operation= new AddAndCommitOperation(getPart(), files, unadded, comment); + if (jobListener != null) + operation.setJobChangeListener(jobListener); + + if (fFileTypePage != null) { + final Map extensionsToSave= new HashMap(); + final Map extensionsNotToSave= new HashMap(); + + fFileTypePage.getModesForExtensions(extensionsToSave, extensionsNotToSave); + CommitWizardFileTypePage.saveExtensionMappings(extensionsToSave); + operation.setModesForExtensionsForOneTime(extensionsNotToSave); + + final Map namesToSave= new HashMap(); + final Map namesNotToSave= new HashMap(); + + fFileTypePage.getModesForNames(namesToSave, namesNotToSave); + CommitWizardFileTypePage.saveNameMappings(namesToSave); + operation.setModesForNamesForOneTime(namesNotToSave); + } + + try { + operation.run(); + } catch (InvocationTargetException e) { + return false; + } catch (InterruptedException e) { + return false; + } + + fCommitPage.finish(); + return super.performFinish(); + } + + @Override public boolean performCancel() { - fCommitPage.finish(); - return super.performCancel(); - } + fCommitPage.finish(); + return super.performCancel(); + } - @Override + @Override public void addPages() { - + final Collection<String> names = new HashSet<>(); final Collection<String> extensions = new HashSet<>(); - getUnknownNamesAndExtension(fUnaddedDiffs, names, extensions); - - if (names.size() + extensions.size() > 0) { - fFileTypePage= new CommitWizardFileTypePage(extensions, names); - addPage(fFileTypePage); - } - - fCommitPage= new CommitWizardCommitPage(fResources, this); - addPage(fCommitPage); - - super.addPages(); - } + getUnknownNamesAndExtension(fUnaddedDiffs, names, extensions); + + if (names.size() + extensions.size() > 0) { + fFileTypePage= new CommitWizardFileTypePage(extensions, names); + addPage(fFileTypePage); + } + + fCommitPage= new CommitWizardCommitPage(fResources, this); + addPage(fCommitPage); + + super.addPages(); + } - @Override + @Override public void dispose() { - fParticipant.dispose(); - super.dispose(); - } - - public static void run(IWorkbenchPart part, Shell shell, IResource [] resources) throws CVSException { - try { + fParticipant.dispose(); + super.dispose(); + } + + public static void run(IWorkbenchPart part, Shell shell, IResource [] resources) throws CVSException { + try { CommitWizard commitWizard = new CommitWizard(resources); commitWizard.setPart(part); run(shell, commitWizard); } catch (OperationCanceledException e) { // Ignore } - } - - private void setPart(IWorkbenchPart part) { + } + + private void setPart(IWorkbenchPart part) { this.part = part; } public static void run(Shell shell, SyncInfoSet infos, IJobChangeListener jobListener) throws CVSException { - try { + try { run(shell, new CommitWizard(infos, jobListener)); } catch (OperationCanceledException e) { // Ignore } - } + } public static void run(IWorkbenchPart part, Shell shell, final ResourceTraversal[] traversals) throws CVSException { - try { - final IResource [][] resources = new IResource[][] { null }; + try { + final IResource [][] resources = new IResource[][] { null }; PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { try { resources[0] = getDeepResourcesToCommit(traversals, monitor); @@ -393,17 +393,17 @@ public class CommitWizard extends ResizableWizard { } private IWorkbenchPart getPart() { - if (part != null) - return part; - return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart(); - } - - private static void run(Shell shell, CommitWizard wizard) { - if (!wizard.hasOutgoingChanges()) { - MessageDialog.openInformation(shell, CVSUIMessages.CommitWizard_6, CVSUIMessages.CommitWizard_7); // - } else { - int highestProblemSeverity = wizard.getHighestProblemSeverity(); - IPreferenceStore preferenceStore = CVSUIPlugin.getPlugin().getPreferenceStore(); + if (part != null) + return part; + return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().getActivePart(); + } + + private static void run(Shell shell, CommitWizard wizard) { + if (!wizard.hasOutgoingChanges()) { + MessageDialog.openInformation(shell, CVSUIMessages.CommitWizard_6, CVSUIMessages.CommitWizard_7); // + } else { + int highestProblemSeverity = wizard.getHighestProblemSeverity(); + IPreferenceStore preferenceStore = CVSUIPlugin.getPlugin().getPreferenceStore(); switch (highestProblemSeverity) { case IMarker.SEVERITY_WARNING: String allowCommitsWithWarnings = preferenceStore.getString(ICVSUIConstants.PREF_ALLOW_COMMIT_WITH_WARNINGS); @@ -424,37 +424,37 @@ public class CommitWizard extends ResizableWizard { } break; } - open(shell, wizard); - } - } + open(shell, wizard); + } + } - protected static int open(Shell shell, ResizableWizard wizard) { - final WizardDialog dialog= new WizardDialog(shell, wizard); - dialog.setPageSize(wizard.loadSize()); - return dialog.open(); - } - + protected static int open(Shell shell, ResizableWizard wizard) { + final WizardDialog dialog= new WizardDialog(shell, wizard); + dialog.setPageSize(wizard.loadSize()); + return dialog.open(); + } + private void getUnknownNamesAndExtension(IResource[] resources, Collection<String> names, Collection<String> extensions) { - final IFileContentManager manager= Team.getFileContentManager(); + final IFileContentManager manager= Team.getFileContentManager(); - for (int i = 0; i < resources.length; i++) { + for (int i = 0; i < resources.length; i++) { - IResource local = resources[i]; - if (local instanceof IFile && manager.getType((IFile)local) == Team.UNKNOWN) { - final String extension= local.getFileExtension(); - if (extension != null && !manager.isKnownExtension(extension)) { - extensions.add(extension); - } + IResource local = resources[i]; + if (local instanceof IFile && manager.getType((IFile)local) == Team.UNKNOWN) { + final String extension= local.getFileExtension(); + if (extension != null && !manager.isKnownExtension(extension)) { + extensions.add(extension); + } - final String name= local.getName(); - if (extension == null && name != null && !manager.isKnownFilename(name)) - names.add(name); - } - } - } - + final String name= local.getName(); + if (extension == null && name != null && !manager.isKnownFilename(name)) + names.add(name); + } + } + } + private IResource[] getUnaddedResources(IResource[] resources) throws CVSException { List/* <IResource> */<IResource> unadded = new ArrayList<>(); for (int i = 0; i < resources.length; i++) { @@ -474,46 +474,46 @@ public class CommitWizard extends ResizableWizard { return files.toArray(new IResource[0]); } - private static boolean isAdded(IResource resource) throws CVSException { - final ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource); - if (cvsResource.isFolder()) { - return ((ICVSFolder)cvsResource).isCVSFolder(); - } - return cvsResource.isManaged(); - } + private static boolean isAdded(IResource resource) throws CVSException { + final ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(resource); + if (cvsResource.isFolder()) { + return ((ICVSFolder)cvsResource).isCVSFolder(); + } + return cvsResource.isManaged(); + } - private static IResource[] getDeepResourcesToCommit(ResourceTraversal[] traversals, IProgressMonitor monitor) throws CoreException { + private static IResource[] getDeepResourcesToCommit(ResourceTraversal[] traversals, IProgressMonitor monitor) throws CoreException { List<IResource> roots = new ArrayList<>(); - for (int j = 0; j < traversals.length; j++) { - ResourceTraversal traversal = traversals[j]; - IResource[] resources = traversal.getResources(); - if (traversal.getDepth() == IResource.DEPTH_INFINITE) { - roots.addAll(Arrays.asList(resources)); - } else if (traversal.getDepth() == IResource.DEPTH_ZERO) { - collectShallowFiles(resources, roots); - } else if (traversal.getDepth() == IResource.DEPTH_ONE) { - collectShallowFiles(resources, roots); - for (int k = 0; k < resources.length; k++) { - IResource resource = resources[k]; - if (resource.getType() != IResource.FILE) { - collectShallowFiles(members(resource), roots); - } - } - } - } - return roots.toArray(new IResource[roots.size()]); - } + for (int j = 0; j < traversals.length; j++) { + ResourceTraversal traversal = traversals[j]; + IResource[] resources = traversal.getResources(); + if (traversal.getDepth() == IResource.DEPTH_INFINITE) { + roots.addAll(Arrays.asList(resources)); + } else if (traversal.getDepth() == IResource.DEPTH_ZERO) { + collectShallowFiles(resources, roots); + } else if (traversal.getDepth() == IResource.DEPTH_ONE) { + collectShallowFiles(resources, roots); + for (int k = 0; k < resources.length; k++) { + IResource resource = resources[k]; + if (resource.getType() != IResource.FILE) { + collectShallowFiles(members(resource), roots); + } + } + } + } + return roots.toArray(new IResource[roots.size()]); + } - private static IResource[] members(IResource resource) throws CoreException { - return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().members(resource); - } + private static IResource[] members(IResource resource) throws CoreException { + return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().members(resource); + } private static void collectShallowFiles(IResource[] resources, List<IResource> roots) { - for (int k = 0; k < resources.length; k++) { - IResource resource = resources[k]; - if (resource.getType() == IResource.FILE) - roots.add(resource); - } - } + for (int k = 0; k < resources.length; k++) { + IResource resource = resources[k]; + if (resource.getType() == IResource.FILE) + roots.add(resource); + } + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardCommitPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardCommitPage.java index 353ca068f..1dad2c681 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardCommitPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardCommitPage.java @@ -54,44 +54,44 @@ import org.eclipse.ui.part.PageBook; * a commit comment. */ public class CommitWizardCommitPage extends WizardPage implements IPropertyChangeListener { - - public static final String SHOW_COMPARE = "ShowCompare"; //$NON-NLS-1$ - private static final String H_WEIGHT_1 = "HWeight1"; //$NON-NLS-1$ - private static final String H_WEIGHT_2 = "HWeight2"; //$NON-NLS-1$ - private static final String V_WEIGHT_1 = "VWeight1"; //$NON-NLS-1$ - private static final String V_WEIGHT_2 = "VWeight2"; //$NON-NLS-1$ - + + public static final String SHOW_COMPARE = "ShowCompare"; //$NON-NLS-1$ + private static final String H_WEIGHT_1 = "HWeight1"; //$NON-NLS-1$ + private static final String H_WEIGHT_2 = "HWeight2"; //$NON-NLS-1$ + private static final String V_WEIGHT_1 = "VWeight1"; //$NON-NLS-1$ + private static final String V_WEIGHT_2 = "VWeight2"; //$NON-NLS-1$ + private final CommitCommentArea fCommentArea; - - private ISynchronizePageConfiguration fConfiguration; - - protected final CommitWizard fWizard; - + + private ISynchronizePageConfiguration fConfiguration; + + protected final CommitWizard fWizard; + private ParticipantPagePane fPagePane; - private PageBook bottomChild; + private PageBook bottomChild; private boolean fHasConflicts; private boolean fIsEmpty; - + private SashForm horizontalSash; private SashForm verticalSash; private Splitter placeholder; private boolean showCompare; - public CommitWizardCommitPage(IResource [] resources, CommitWizard wizard) { - - super(CVSUIMessages.CommitWizardCommitPage_0); - setTitle(CVSUIMessages.CommitWizardCommitPage_0); - setDescription(CVSUIMessages.CommitWizardCommitPage_2); - - fWizard= wizard; - fCommentArea= new CommitCommentArea(); - fCommentArea.setProposedComment(getProposedComment(resources)); - if (resources.length > 0) - fCommentArea.setProject(resources[0].getProject()); - fWizard.getDiffTree().addDiffChangeListener(new IDiffChangeListener() { + public CommitWizardCommitPage(IResource [] resources, CommitWizard wizard) { + + super(CVSUIMessages.CommitWizardCommitPage_0); + setTitle(CVSUIMessages.CommitWizardCommitPage_0); + setDescription(CVSUIMessages.CommitWizardCommitPage_2); + + fWizard= wizard; + fCommentArea= new CommitCommentArea(); + fCommentArea.setProposedComment(getProposedComment(resources)); + if (resources.length > 0) + fCommentArea.setProject(resources[0].getProject()); + fWizard.getDiffTree().addDiffChangeListener(new IDiffChangeListener() { @Override public void propertyChanged(IDiffTree tree, int property, IPath[] paths) { // ignore property changes @@ -101,34 +101,34 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang Utils.syncExec((Runnable) () -> updateEnablements(), CommitWizardCommitPage.this.getControl()); } }); - } - - @Override + } + + @Override public void createControl(Composite parent) { - initializeDialogUnits(parent); - Dialog.applyDialogFont(parent); - final PixelConverter converter= new PixelConverter(parent); - - final Composite composite= new Composite(parent, SWT.NONE); - composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DEFAULT)); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.COMMIT_COMMENT_PAGE); - - - horizontalSash = new SashForm(composite, SWT.HORIZONTAL); - horizontalSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - verticalSash = new SashForm(horizontalSash, SWT.VERTICAL); - verticalSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + initializeDialogUnits(parent); + Dialog.applyDialogFont(parent); + final PixelConverter converter= new PixelConverter(parent); + + final Composite composite= new Composite(parent, SWT.NONE); + composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DEFAULT)); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.COMMIT_COMMENT_PAGE); + + + horizontalSash = new SashForm(composite, SWT.HORIZONTAL); + horizontalSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + verticalSash = new SashForm(horizontalSash, SWT.VERTICAL); + verticalSash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - createCommentArea(verticalSash, converter); + createCommentArea(verticalSash, converter); - placeholder = new Splitter(horizontalSash, SWT.VERTICAL /*any*/); - placeholder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + placeholder = new Splitter(horizontalSash, SWT.VERTICAL /*any*/); + placeholder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - createChangesArea(verticalSash, converter); + createChangesArea(verticalSash, converter); - IDialogSettings section = getDialogSettings().getSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); + IDialogSettings section = getDialogSettings().getSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); showCompare = section == null ? false : section.getBoolean(SHOW_COMPARE); int vWeight1 = 50; int vWeight2 = 50; @@ -157,75 +157,75 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang verticalSash.setWeights(new int[] {vWeight1, vWeight2}); horizontalSash.setWeights(new int[] {hWeight1, hWeight2}); - //fSashForm.setWeights(weights); - Dialog.applyDialogFont(parent); - setControl(composite); - - fCommentArea.setFocus(); - - validatePage(false); - } - - private void createCommentArea(Composite parent, PixelConverter converter) { - Composite c = new Composite(parent, SWT.NONE); - c.setLayout(GridLayoutFactory.fillDefaults().margins(0, 0).create()); - - fCommentArea.createArea(c); - GridData gd = SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true); - fCommentArea.getComposite().setLayoutData(gd); - fCommentArea.addPropertyChangeListener(this); - - createPlaceholder(c); - } - - private void createChangesArea(Composite parent, PixelConverter converter) { - - ISynchronizeParticipant participant= fWizard.getParticipant(); - int size = fWizard.getDiffTree().getAffectedResources().length; - if (size > getFileDisplayThreshold()) { - // Create a page book to allow eventual inclusion of changes - bottomChild = new PageBook(parent, SWT.NONE); - bottomChild.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, false)); - // Create composite for showing the reason for not showing the changes and a button to show them - Composite changeDesc = new Composite(bottomChild, SWT.NONE); - changeDesc.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); - SWTUtils.createLabel(changeDesc, NLS.bind(CVSUIMessages.CommitWizardCommitPage_1, new String[] { Integer.toString(size), Integer.toString(getFileDisplayThreshold()) })); - Button showChanges = new Button(changeDesc, SWT.PUSH); - showChanges.setText(CVSUIMessages.CommitWizardCommitPage_5); - showChanges.addSelectionListener(new SelectionAdapter() { - @Override + //fSashForm.setWeights(weights); + Dialog.applyDialogFont(parent); + setControl(composite); + + fCommentArea.setFocus(); + + validatePage(false); + } + + private void createCommentArea(Composite parent, PixelConverter converter) { + Composite c = new Composite(parent, SWT.NONE); + c.setLayout(GridLayoutFactory.fillDefaults().margins(0, 0).create()); + + fCommentArea.createArea(c); + GridData gd = SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true); + fCommentArea.getComposite().setLayoutData(gd); + fCommentArea.addPropertyChangeListener(this); + + createPlaceholder(c); + } + + private void createChangesArea(Composite parent, PixelConverter converter) { + + ISynchronizeParticipant participant= fWizard.getParticipant(); + int size = fWizard.getDiffTree().getAffectedResources().length; + if (size > getFileDisplayThreshold()) { + // Create a page book to allow eventual inclusion of changes + bottomChild = new PageBook(parent, SWT.NONE); + bottomChild.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, false)); + // Create composite for showing the reason for not showing the changes and a button to show them + Composite changeDesc = new Composite(bottomChild, SWT.NONE); + changeDesc.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); + SWTUtils.createLabel(changeDesc, NLS.bind(CVSUIMessages.CommitWizardCommitPage_1, new String[] { Integer.toString(size), Integer.toString(getFileDisplayThreshold()) })); + Button showChanges = new Button(changeDesc, SWT.PUSH); + showChanges.setText(CVSUIMessages.CommitWizardCommitPage_5); + showChanges.addSelectionListener(new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - showChangesPane(); - } - }); - showChanges.setLayoutData(new GridData()); - bottomChild.showPage(changeDesc); - // Hide compare pane - horizontalSash.setMaximizedControl(verticalSash); - } else { - final Composite composite= new Composite(parent, SWT.NONE); - composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); - composite.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true)); - - Control c = createChangesPage(composite, participant); - c.setLayoutData(SWTUtils.createHVFillGridData()); - } - } + showChangesPane(); + } + }); + showChanges.setLayoutData(new GridData()); + bottomChild.showPage(changeDesc); + // Hide compare pane + horizontalSash.setMaximizedControl(verticalSash); + } else { + final Composite composite= new Composite(parent, SWT.NONE); + composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); + composite.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true)); + + Control c = createChangesPage(composite, participant); + c.setLayoutData(SWTUtils.createHVFillGridData()); + } + } - protected void showChangesPane() { - Control c = createChangesPage(bottomChild, fWizard.getParticipant()); - bottomChild.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true)); - bottomChild.showPage(c); - // Restore compare pane. It has been hidden when file display threshold was reached. - if (showCompare) { - horizontalSash.setMaximizedControl(null); - } - Dialog.applyDialogFont(getControl()); - ((Composite)getControl()).layout(); - } + protected void showChangesPane() { + Control c = createChangesPage(bottomChild, fWizard.getParticipant()); + bottomChild.setLayoutData(SWTUtils.createGridData(SWT.DEFAULT, SWT.DEFAULT, SWT.FILL, SWT.FILL, true, true)); + bottomChild.showPage(c); + // Restore compare pane. It has been hidden when file display threshold was reached. + if (showCompare) { + horizontalSash.setMaximizedControl(null); + } + Dialog.applyDialogFont(getControl()); + ((Composite)getControl()).layout(); + } - private Control createChangesPage(final Composite composite, ISynchronizeParticipant participant) { - fConfiguration= participant.createPageConfiguration(); + private Control createChangesPage(final Composite composite, ISynchronizeParticipant participant) { + fConfiguration= participant.createPageConfiguration(); CompareConfiguration cc = new CompareConfiguration(); cc.setLeftEditable(false); cc.setRightEditable(false); @@ -233,8 +233,8 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang Control control = input.createContents(composite); control.setLayoutData(new GridData(GridData.FILL_BOTH)); return control; - } - + } + private class CommitWizardParticipantPageCompareEditorInput extends ParticipantPageCompareEditorInput { public CommitWizardParticipantPageCompareEditorInput( @@ -259,11 +259,11 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang protected void setPageDescription(String title) { super.setPageDescription(TeamUIMessages.ParticipantPageSaveablePart_0); } - } - + } + private int getFileDisplayThreshold() { - return CVSUIPlugin.getPlugin().getPreferenceStore().getInt(ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD); - } + return CVSUIPlugin.getPlugin().getPreferenceStore().getInt(ICVSUIConstants.PREF_COMMIT_FILES_DISPLAY_THRESHOLD); + } @Override public void dispose() { @@ -273,16 +273,16 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang fPagePane.dispose(); } - private void createPlaceholder(final Composite composite) { - final Composite placeholder= new Composite(composite, SWT.NONE); - placeholder.setLayoutData(new GridData(SWT.DEFAULT, convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_SPACING) /3)); - } - - public String getComment(Shell shell) { - return fCommentArea.getCommentWithPrompt(shell); - } - - @Override + private void createPlaceholder(final Composite composite) { + final Composite placeholder= new Composite(composite, SWT.NONE); + placeholder.setLayoutData(new GridData(SWT.DEFAULT, convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_SPACING) /3)); + } + + public String getComment(Shell shell) { + return fCommentArea.getCommentWithPrompt(shell); + } + + @Override public boolean isPageComplete() { /* if empty comment is not allowed (see bug 114678) */ final IPreferenceStore store = CVSUIPlugin.getPlugin() @@ -298,72 +298,72 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang } return super.isPageComplete(); } - - @Override + + @Override public void setVisible(boolean visible) { - super.setVisible(visible); - expand(); - if (visible && fConfiguration != null) { - final Viewer viewer= fConfiguration.getPage().getViewer(); - viewer.refresh(); - } - updateEnablements(); - setFocus(); - } + super.setVisible(visible); + expand(); + if (visible && fConfiguration != null) { + final Viewer viewer= fConfiguration.getPage().getViewer(); + viewer.refresh(); + } + updateEnablements(); + setFocus(); + } - protected void expand() { - if (fConfiguration != null) { - final Viewer viewer= fConfiguration.getPage().getViewer(); - if (viewer instanceof TreeViewer) { - try { - viewer.getControl().setRedraw(false); - ((TreeViewer)viewer).expandAll(); - } finally { - viewer.getControl().setRedraw(true); - } - } - } - } - + protected void expand() { + if (fConfiguration != null) { + final Viewer viewer= fConfiguration.getPage().getViewer(); + if (viewer instanceof TreeViewer) { + try { + viewer.getControl().setRedraw(false); + ((TreeViewer)viewer).expandAll(); + } finally { + viewer.getControl().setRedraw(true); + } + } + } + } + /* * Expand the sync elements and update the page enablement */ protected void updateForModelChange() { - Control control = getControl(); - if (control == null || control.isDisposed()) return; + Control control = getControl(); + if (control == null || control.isDisposed()) return; expand(); updateEnablements(); } public void updateEnablements() { - if (fConfiguration != null) { - fHasConflicts = false; - fIsEmpty = false; - + if (fConfiguration != null) { + fHasConflicts = false; + fIsEmpty = false; + if (fWizard.hasConflicts()) { - fHasConflicts = true; - } + fHasConflicts = true; + } if (!fWizard.hasOutgoingChanges()) { - fIsEmpty = true; - } - } - + fIsEmpty = true; + } + } + validatePage(false); } boolean validatePage(boolean setMessage) { - if (fCommentArea != null && fCommentArea.getComment(false).length() == 0) { - final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore(); - final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); - if (MessageDialogWithToggle.NEVER.equals(value)) { - setPageComplete(false); - if (setMessage) - setErrorMessage(CVSUIMessages.CommitWizardCommitPage_3); - return false; - } - } - - if (fHasConflicts) { + if (fCommentArea != null && fCommentArea.getComment(false).length() == 0) { + final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore(); + final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); + if (MessageDialogWithToggle.NEVER.equals(value)) { + setPageComplete(false); + if (setMessage) + setErrorMessage(CVSUIMessages.CommitWizardCommitPage_3); + return false; + } + } + + if (fHasConflicts) { setErrorMessage(CVSUIMessages.CommitWizardCommitPage_4); setPageComplete(false); return false; @@ -374,67 +374,67 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang setPageComplete(false); return false; } - - setPageComplete(true); - setErrorMessage(null); - return true; - } - - public void setFocus() { - fCommentArea.setFocus(); - validatePage(true); - } - - @Override + + setPageComplete(true); + setErrorMessage(null); + return true; + } + + public void setFocus() { + fCommentArea.setFocus(); + validatePage(true); + } + + @Override protected IWizardContainer getContainer() { - return super.getContainer(); - } + return super.getContainer(); + } ResourceTraversal[] getTraversalsToCommit() { return fWizard.getParticipant().getContext().getScope().getTraversals(); - } + } - @Override + @Override public void propertyChange(PropertyChangeEvent event) { - - if (event.getProperty().equals(CommitCommentArea.OK_REQUESTED)) { - final IWizardContainer container= getContainer(); - if (container instanceof WizardDialog) { - final WizardDialog dialog= (WizardDialog)container; - if (getWizard().canFinish()) { - try { - getWizard().performFinish(); - } finally { - dialog.close(); - } - } - } - } - if (event.getProperty().equals(CommitCommentArea.COMMENT_MODIFIED)) { - validatePage(true); - } - } - + + if (event.getProperty().equals(CommitCommentArea.OK_REQUESTED)) { + final IWizardContainer container= getContainer(); + if (container instanceof WizardDialog) { + final WizardDialog dialog= (WizardDialog)container; + if (getWizard().canFinish()) { + try { + getWizard().performFinish(); + } finally { + dialog.close(); + } + } + } + } + if (event.getProperty().equals(CommitCommentArea.COMMENT_MODIFIED)) { + validatePage(true); + } + } + /* * Get a proposed comment by looking at the active change sets */ - private String getProposedComment(IResource[] resourcesToCommit) { - StringBuffer comment = new StringBuffer(); - ChangeSet[] sets = CVSUIPlugin.getPlugin().getChangeSetManager().getSets(); - Arrays.sort(sets, new ChangeSetComparator()); - int numMatchedSets = 0; - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (isUserSet(set) && containsOne(set, resourcesToCommit)) { - if(numMatchedSets > 0) comment.append(System.getProperty("line.separator")); //$NON-NLS-1$ - comment.append(set.getComment()); - numMatchedSets++; - } - } - return comment.toString(); - } - - private boolean isUserSet(ChangeSet set) { + private String getProposedComment(IResource[] resourcesToCommit) { + StringBuffer comment = new StringBuffer(); + ChangeSet[] sets = CVSUIPlugin.getPlugin().getChangeSetManager().getSets(); + Arrays.sort(sets, new ChangeSetComparator()); + int numMatchedSets = 0; + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (isUserSet(set) && containsOne(set, resourcesToCommit)) { + if(numMatchedSets > 0) comment.append(System.getProperty("line.separator")); //$NON-NLS-1$ + comment.append(set.getComment()); + numMatchedSets++; + } + } + return comment.toString(); + } + + private boolean isUserSet(ChangeSet set) { if (set instanceof ActiveChangeSet) { ActiveChangeSet acs = (ActiveChangeSet) set; return acs.isUserCreated(); @@ -443,7 +443,7 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang } private boolean containsOne(ChangeSet set, IResource[] resourcesToCommit) { - for (int j = 0; j < resourcesToCommit.length; j++) { + for (int j = 0; j < resourcesToCommit.length; j++) { IResource resource = resourcesToCommit[j]; if (set.contains(resource)) { return true; @@ -455,14 +455,14 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang } } return false; - } + } public void finish() { int[] hWeights = horizontalSash.getWeights(); int[] vWeights = verticalSash.getWeights(); IDialogSettings section = getDialogSettings().getSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); - if (section == null) - section= getDialogSettings().addNewSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); + if (section == null) + section= getDialogSettings().addNewSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); if (showCompare) { section.put(H_WEIGHT_1, hWeights[0]); section.put(H_WEIGHT_2, hWeights[1]); @@ -481,6 +481,6 @@ public class CommitWizardCommitPage extends WizardPage implements IPropertyChang } } - + } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardFileTypePage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardFileTypePage.java index 9b02b25db..0b7ce95ba 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardFileTypePage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardFileTypePage.java @@ -42,116 +42,116 @@ import org.eclipse.ui.PlatformUI; */ public class CommitWizardFileTypePage extends WizardPage { - private final Collection fExtensions; + private final Collection fExtensions; private final Collection<Item> fNames; - - public CommitWizardFileTypePage(Collection unknownExtensions, Collection unknownNames) { - super(CVSUIMessages.CommitWizardFileTypePage_0); - setTitle(CVSUIMessages.CommitWizardFileTypePage_0); - setDescription(CVSUIMessages.CommitWizardFileTypePage_2); - + + public CommitWizardFileTypePage(Collection unknownExtensions, Collection unknownNames) { + super(CVSUIMessages.CommitWizardFileTypePage_0); + setTitle(CVSUIMessages.CommitWizardFileTypePage_0); + setDescription(CVSUIMessages.CommitWizardFileTypePage_2); + fNames = new ArrayList<>(); - for (final Iterator iter = unknownNames.iterator(); iter.hasNext();) { - final String name = (String) iter.next(); - fNames.add(new FileTypeTable.Name(name, false)); - } - - fExtensions= new ArrayList(); - for (final Iterator iter = unknownExtensions.iterator(); iter.hasNext();) { - final String extension= (String)iter.next(); - fExtensions.add(new FileTypeTable.Extension(extension, false)); - } - } - - @Override + for (final Iterator iter = unknownNames.iterator(); iter.hasNext();) { + final String name = (String) iter.next(); + fNames.add(new FileTypeTable.Name(name, false)); + } + + fExtensions= new ArrayList(); + for (final Iterator iter = unknownExtensions.iterator(); iter.hasNext();) { + final String extension= (String)iter.next(); + fExtensions.add(new FileTypeTable.Extension(extension, false)); + } + } + + @Override public void createControl(Composite parent) { - - initializeDialogUnits(parent); - - final Composite composite= new Composite(parent, SWT.NONE); - composite.setLayout(new GridLayout(1, false)); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.COMMIT_FILE_TYPES_PAGE); - - final Label label= new Label(composite, SWT.WRAP); - label.setText(CVSUIMessages.CommitWizardFileTypePage_3); - label.setLayoutData(SWTUtils.createHFillGridData()); - Dialog.applyDialogFont(composite); - - final List items= new ArrayList(); - items.addAll(fNames); - items.addAll(fExtensions); - - new FileTypeTable(composite, items, true); + + initializeDialogUnits(parent); + + final Composite composite= new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(1, false)); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.COMMIT_FILE_TYPES_PAGE); + + final Label label= new Label(composite, SWT.WRAP); + label.setText(CVSUIMessages.CommitWizardFileTypePage_3); + label.setLayoutData(SWTUtils.createHFillGridData()); + Dialog.applyDialogFont(composite); + + final List items= new ArrayList(); + items.addAll(fNames); + items.addAll(fExtensions); + + new FileTypeTable(composite, items, true); - setControl(composite); - - } + setControl(composite); + + } public void getModesForExtensions(Map toSave, Map notToSave) { - getModes(fExtensions, toSave, notToSave); + getModes(fExtensions, toSave, notToSave); } public void getModesForNames(Map toSave, Map notToSave) { - getModes(fNames, toSave, notToSave); + getModes(fNames, toSave, notToSave); } - private static void getModes(Collection items, Map toSave, Map notToSave) { - for (final Iterator iter = items.iterator(); iter.hasNext();) { - final FileTypeTable.Item item= (FileTypeTable.Item)iter.next(); - final Map destination= item.save ? toSave : notToSave; - destination.put(item.name, Integer.valueOf(item.mode)); - } - } + private static void getModes(Collection items, Map toSave, Map notToSave) { + for (final Iterator iter = items.iterator(); iter.hasNext();) { + final FileTypeTable.Item item= (FileTypeTable.Item)iter.next(); + final Map destination= item.save ? toSave : notToSave; + destination.put(item.name, Integer.valueOf(item.mode)); + } + } - public KSubstOption getOption(IFile file) throws CVSException { - final String extension= file.getFileExtension(); - if (extension != null) { - for (Iterator iter = fExtensions.iterator(); iter.hasNext();) { - final FileTypeTable.Item element = (FileTypeTable.Item) iter.next(); - if (element.name.equals(extension)) { - return element.mode == Team.TEXT ? KSubstOption.getDefaultTextMode() : Command.KSUBST_BINARY; - } - } - } else { - final String name= file.getName(); - for (Iterator iter = fNames.iterator(); iter.hasNext();) { - FileTypeTable.Item item = (FileTypeTable.Item) iter.next(); - if (item.name.equals(name)) { - return item.mode == Team.TEXT ? KSubstOption.getDefaultTextMode() : Command.KSUBST_BINARY; - } - } - } - final ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file); + public KSubstOption getOption(IFile file) throws CVSException { + final String extension= file.getFileExtension(); + if (extension != null) { + for (Iterator iter = fExtensions.iterator(); iter.hasNext();) { + final FileTypeTable.Item element = (FileTypeTable.Item) iter.next(); + if (element.name.equals(extension)) { + return element.mode == Team.TEXT ? KSubstOption.getDefaultTextMode() : Command.KSUBST_BINARY; + } + } + } else { + final String name= file.getName(); + for (Iterator iter = fNames.iterator(); iter.hasNext();) { + FileTypeTable.Item item = (FileTypeTable.Item) iter.next(); + if (item.name.equals(name)) { + return item.mode == Team.TEXT ? KSubstOption.getDefaultTextMode() : Command.KSUBST_BINARY; + } + } + } + final ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file); ResourceSyncInfo fileInfo = cvsFile.getSyncInfo(); return fileInfo != null ? fileInfo.getKeywordMode() : KSubstOption.fromFile(file); - } - - public static void saveExtensionMappings(Map modesToPersist) { - - final String [] extensions= new String [modesToPersist.size()]; - final int [] modes= new int[modesToPersist.size()]; - - int index= 0; - for (Iterator iter= modesToPersist.keySet().iterator(); iter.hasNext();) { - extensions[index]= (String) iter.next(); - modes[index]= ((Integer)modesToPersist.get(extensions[index])).intValue(); - ++index; - } - Team.getFileContentManager().addExtensionMappings(extensions, modes); - } - - public static void saveNameMappings(Map modesToPersist) { - - final String [] names= new String [modesToPersist.size()]; - final int [] modes= new int[modesToPersist.size()]; - - int index= 0; - for (Iterator iter= modesToPersist.keySet().iterator(); iter.hasNext();) { - names[index]= (String) iter.next(); - modes[index]= ((Integer)modesToPersist.get(names[index])).intValue(); - ++index; - } - Team.getFileContentManager().addNameMappings(names, modes); - } + } + + public static void saveExtensionMappings(Map modesToPersist) { + + final String [] extensions= new String [modesToPersist.size()]; + final int [] modes= new int[modesToPersist.size()]; + + int index= 0; + for (Iterator iter= modesToPersist.keySet().iterator(); iter.hasNext();) { + extensions[index]= (String) iter.next(); + modes[index]= ((Integer)modesToPersist.get(extensions[index])).intValue(); + ++index; + } + Team.getFileContentManager().addExtensionMappings(extensions, modes); + } + + public static void saveNameMappings(Map modesToPersist) { + + final String [] names= new String [modesToPersist.size()]; + final int [] modes= new int[modesToPersist.size()]; + + int index= 0; + for (Iterator iter= modesToPersist.keySet().iterator(); iter.hasNext();) { + names[index]= (String) iter.next(); + modes[index]= ((Integer)modesToPersist.get(names[index])).intValue(); + ++index; + } + Team.getFileContentManager().addNameMappings(names, modes); + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardParticipant.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardParticipant.java index 39836e4e4..914b204f2 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardParticipant.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CommitWizardParticipant.java @@ -38,116 +38,116 @@ import org.eclipse.team.ui.synchronize.*; */ public class CommitWizardParticipant extends WorkspaceModelParticipant { - /** - * The actions to be displayed in the context menu. - */ - private class ActionContribution extends SynchronizePageActionGroup { - @Override + /** + * The actions to be displayed in the context menu. + */ + private class ActionContribution extends SynchronizePageActionGroup { + @Override public void modelChanged(final ISynchronizeModelElement root) { - super.modelChanged(root); + super.modelChanged(root); Display.getDefault().asyncExec(() -> { final CommitWizardCommitPage page = fWizard.getCommitPage(); if (page != null) page.updateForModelChange(); }); - } - } - - private WorkspaceChangeSetCapability capability; - - @Override + } + } + + private WorkspaceChangeSetCapability capability; + + @Override public ChangeSetCapability getChangeSetCapability() { - if (capability == null) { - capability = new WorkspaceChangeSetCapability() { - @Override + if (capability == null) { + capability = new WorkspaceChangeSetCapability() { + @Override public boolean supportsCheckedInChangeSets() { - return false; - } - @Override + return false; + } + @Override public boolean enableActiveChangeSetsFor(ISynchronizePageConfiguration configuration) { - return false; - }; - }; - } - return capability; - } + return false; + }; + }; + } + return capability; + } - /** - * An extension of the standard label decorator which configures the keyword substitution - * mode according to the settings on the file type wizard page. - */ - private static class Decorator extends CVSParticipantLabelDecorator { - - private final CommitWizard fWizard; + /** + * An extension of the standard label decorator which configures the keyword substitution + * mode according to the settings on the file type wizard page. + */ + private static class Decorator extends CVSParticipantLabelDecorator { + + private final CommitWizard fWizard; - public Decorator(ISynchronizePageConfiguration configuration, CommitWizard wizard) { - super(configuration); - fWizard= wizard; - } - - @Override + public Decorator(ISynchronizePageConfiguration configuration, CommitWizard wizard) { + super(configuration); + fWizard= wizard; + } + + @Override protected CVSDecoration getDecoration(IResource resource) throws CoreException { - final CVSDecoration decoration= super.getDecoration(resource); - final CommitWizardFileTypePage page= fWizard.getFileTypePage(); - - if (page != null && resource instanceof IFile) - decoration.setKeywordSubstitution(page.getOption((IFile)resource).getShortDisplayText()); - return decoration; - } - } + final CVSDecoration decoration= super.getDecoration(resource); + final CommitWizardFileTypePage page= fWizard.getFileTypePage(); + + if (page != null && resource instanceof IFile) + decoration.setKeywordSubstitution(page.getOption((IFile)resource).getShortDisplayText()); + return decoration; + } + } protected static final String ACTION_GROUP = "org.eclipse.tam.cvs.ui.CommitActions"; //$NON-NLS-1$ - - final CommitWizard fWizard; + + final CommitWizard fWizard; protected Action showComparePaneAction; - - public CommitWizardParticipant(SynchronizationContext context, CommitWizard wizard) { - super(context); - fWizard= wizard; - } - - @Override + + public CommitWizardParticipant(SynchronizationContext context, CommitWizard wizard) { + super(context); + fWizard= wizard; + } + + @Override protected ILabelDecorator getLabelDecorator(ISynchronizePageConfiguration configuration) { - return new Decorator(configuration, fWizard); - } + return new Decorator(configuration, fWizard); + } - @Override + @Override protected void initializeConfiguration(final ISynchronizePageConfiguration configuration) { - super.initializeConfiguration(configuration); - configuration.setProperty(ISynchronizePageConfiguration.P_TOOLBAR_MENU, new String[] {ACTION_GROUP, ISynchronizePageConfiguration.NAVIGATE_GROUP}); - configuration.setProperty(ISynchronizePageConfiguration.P_CONTEXT_MENU, ISynchronizePageConfiguration.DEFAULT_CONTEXT_MENU); + super.initializeConfiguration(configuration); + configuration.setProperty(ISynchronizePageConfiguration.P_TOOLBAR_MENU, new String[] {ACTION_GROUP, ISynchronizePageConfiguration.NAVIGATE_GROUP}); + configuration.setProperty(ISynchronizePageConfiguration.P_CONTEXT_MENU, ISynchronizePageConfiguration.DEFAULT_CONTEXT_MENU); configuration.addMenuGroup( ISynchronizePageConfiguration.P_CONTEXT_MENU, CONTEXT_MENU_CONTRIBUTION_GROUP_3); - configuration.addActionContribution(new ActionContribution()); + configuration.addActionContribution(new ActionContribution()); - // Wrap the container so that we can update the enablements after the runnable - // (i.e. the container resets the state to what it was at the beginning of the - // run even if the state of the page changed. Remove from View changes the state) + // Wrap the container so that we can update the enablements after the runnable + // (i.e. the container resets the state to what it was at the beginning of the + // run even if the state of the page changed. Remove from View changes the state) configuration.setRunnableContext((fork, cancelable, runnable) -> { fWizard.getContainer().run(fork, cancelable, runnable); final CommitWizardCommitPage page = fWizard.getCommitPage(); if (page != null) page.updateEnablements(); }); - configuration.setSupportedModes(ISynchronizePageConfiguration.OUTGOING_MODE); - configuration.setMode(ISynchronizePageConfiguration.OUTGOING_MODE); - configuration.addActionContribution(new SynchronizePageActionGroup() { - @Override + configuration.setSupportedModes(ISynchronizePageConfiguration.OUTGOING_MODE); + configuration.setMode(ISynchronizePageConfiguration.OUTGOING_MODE); + configuration.addActionContribution(new SynchronizePageActionGroup() { + @Override public void initialize(ISynchronizePageConfiguration configuration) { - super.initialize(configuration); - showComparePaneAction = new Action(null, Action.AS_CHECK_BOX) { - @Override + super.initialize(configuration); + showComparePaneAction = new Action(null, Action.AS_CHECK_BOX) { + @Override public void run() { - fWizard.getCommitPage().showComparePane(this.isChecked()); - } - }; - Utils.initAction(showComparePaneAction, "ComnitWizardComparePaneToggle.", Policy.getActionBundle()); //$NON-NLS-1$ - showComparePaneAction.setChecked(isComparePaneVisible()); - appendToGroup(ISynchronizePageConfiguration.P_TOOLBAR_MENU, ACTION_GROUP, showComparePaneAction); - } + fWizard.getCommitPage().showComparePane(this.isChecked()); + } + }; + Utils.initAction(showComparePaneAction, "ComnitWizardComparePaneToggle.", Policy.getActionBundle()); //$NON-NLS-1$ + showComparePaneAction.setChecked(isComparePaneVisible()); + appendToGroup(ISynchronizePageConfiguration.P_TOOLBAR_MENU, ACTION_GROUP, showComparePaneAction); + } }); - configuration.setProperty(SynchronizePageConfiguration.P_OPEN_ACTION, new Action() { + configuration.setProperty(SynchronizePageConfiguration.P_OPEN_ACTION, new Action() { @Override public void run() { ISelection selection = configuration.getSite().getSelectionProvider().getSelection(); @@ -159,18 +159,18 @@ public class CommitWizardParticipant extends WorkspaceModelParticipant { } } } - }); - } - - @Override + }); + } + + @Override public boolean doesSupportSynchronize() { - return false; - } - - private boolean isComparePaneVisible() { - IDialogSettings section = fWizard.getDialogSettings().getSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); + return false; + } + + private boolean isComparePaneVisible() { + IDialogSettings section = fWizard.getDialogSettings().getSection(CommitWizard.COMMIT_WIZARD_DIALOG_SETTINGS); return section == null ? false : section.getBoolean(CommitWizardCommitPage.SHOW_COMPARE); - } + } @Override protected ModelSynchronizeParticipantActionGroup createMergeActionGroup() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ConfigurationWizardAutoconnectPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ConfigurationWizardAutoconnectPage.java index 013ee872f..8b521bafc 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ConfigurationWizardAutoconnectPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ConfigurationWizardAutoconnectPage.java @@ -50,7 +50,7 @@ public class ConfigurationWizardAutoconnectPage extends CVSWizardPage { setControl(composite); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARING_AUTOCONNECT_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARING_AUTOCONNECT_PAGE); Label description = new Label(composite, SWT.WRAP); GridData data = new GridData(); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java index b4410999e..cd22913fa 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/GenerateDiffFileWizard.java @@ -582,11 +582,11 @@ public class GenerateDiffFileWizard extends Wizard { * Ensure the page is in a valid state. */ /*if (!validatePage()) { - store.storeRadioSelection(CLIPBOARD); - initializeDefaultValues(); - validatePage(); - } - pageValid= true;*/ + store.storeRadioSelection(CLIPBOARD); + initializeDefaultValues(); + validatePage(); + } + pageValid= true;*/ validatePage(); updateEnablements(); @@ -1045,7 +1045,7 @@ public class GenerateDiffFileWizard extends Wizard { public final static int FORMAT_STANDARD = 3; /** - The possible root of the patch + The possible root of the patch */ public final static int ROOT_WORKSPACE = 1; public final static int ROOT_PROJECT = 2; @@ -1303,11 +1303,11 @@ public class GenerateDiffFileWizard extends Wizard { public LocalOption[] getOptions() { List<LocalOption> options = new ArrayList<>(5); /* if(includeNewFilesOptions.getSelection()) { - options.add(Diff.INCLUDE_NEWFILES); - } - if(!recurseOption.getSelection()) { - options.add(Command.DO_NOT_RECURSE); - }*/ + options.add(Diff.INCLUDE_NEWFILES); + } + if(!recurseOption.getSelection()) { + options.add(Command.DO_NOT_RECURSE); + }*/ //Add new files for now options.add(Diff.INCLUDE_NEWFILES); @@ -1545,11 +1545,11 @@ public class GenerateDiffFileWizard extends Wizard { defaultValuesStore.storeLocationSelection(LocationPage.WORKSPACE); defaultValuesStore.storeWorkspacePath(workspaceResource); /* try { - workspaceResource.getParent().refreshLocal(IResource.DEPTH_ONE, null); - } catch(CoreException e) { - CVSUIPlugin.openError(getShell(), CVSUIMessages.GenerateCVSDiff_error, null, e); - return false; - } */ + workspaceResource.getParent().refreshLocal(IResource.DEPTH_ONE, null); + } catch(CoreException e) { + CVSUIPlugin.openError(getShell(), CVSUIMessages.GenerateCVSDiff_error, null, e); + return false; + } */ } else { //Problem with workspace location, open with clipboard next time defaultValuesStore.storeLocationSelection(LocationPage.CLIPBOARD); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java index a23484157..838639e01 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizard.java @@ -39,21 +39,21 @@ import org.eclipse.team.ui.synchronize.ISynchronizeParticipant; import org.eclipse.ui.IWorkbenchPart; public class MergeWizard extends Wizard { - MergeWizardPage page; + MergeWizardPage page; IResource[] resources; - private final IWorkbenchPart part; - private final ResourceMapping[] mappings; - + private final IWorkbenchPart part; + private final ResourceMapping[] mappings; + public MergeWizard(IWorkbenchPart part, IResource[] resources, ResourceMapping[] mappings) { - this.part = part; - this.resources = resources; - this.mappings = mappings; - } + this.part = part; + this.resources = resources; + this.mappings = mappings; + } @Override public void addPages() { - setNeedsProgressMonitor(true); - TagSource tagSource = TagSource.create(resources); + setNeedsProgressMonitor(true); + TagSource tagSource = TagSource.create(resources); setWindowTitle(CVSUIMessages.MergeWizard_title); ImageDescriptor mergeImage = CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_MERGE); page = new MergeWizardPage("mergePage", CVSUIMessages.MergeWizard_0, mergeImage, CVSUIMessages.MergeWizard_1, tagSource); //$NON-NLS-1$ @@ -67,21 +67,21 @@ public class MergeWizard extends Wizard { CVSTag endTag = page.getEndTag(); if (startTag == null || !page.isPreview()) { - // Perform the update (merge) in the background - UpdateOperation op = new UpdateOperation(getPart(), mappings, getLocalOptions(startTag, endTag), null); - try { - op.run(); - } catch (InvocationTargetException e) { - CVSUIPlugin.openError(getShell(), null, null, e); - } catch (InterruptedException e) { - // Ignore - } + // Perform the update (merge) in the background + UpdateOperation op = new UpdateOperation(getPart(), mappings, getLocalOptions(startTag, endTag), null); + try { + op.run(); + } catch (InvocationTargetException e) { + CVSUIPlugin.openError(getShell(), null, null, e); + } catch (InterruptedException e) { + // Ignore + } } else { if (isShowModelSync()) { ModelMergeParticipant participant = ModelMergeParticipant.getMatchingParticipant(mappings, startTag, endTag); if(participant == null) { - CVSMergeSubscriber s = new CVSMergeSubscriber(getProjects(resources), startTag, endTag, true); - try { + CVSMergeSubscriber s = new CVSMergeSubscriber(getProjects(resources), startTag, endTag, true); + try { new ModelMergeOperation(getPart(), mappings, s, page.isOnlyPreviewConflicts()).run(); } catch (InvocationTargetException e) { CVSUIPlugin.log(IStatus.ERROR, "Internal error", e.getTargetException()); //$NON-NLS-1$ @@ -93,12 +93,12 @@ public class MergeWizard extends Wizard { } } else { // First check if there is an existing matching participant, if so then re-use it - try { - resources = getAllResources(startTag, endTag); - } catch (InvocationTargetException e) { - // Log and continue with the original resources - CVSUIPlugin.log(IStatus.ERROR, "An error occurred while determining if extra resources should be included in the merge", e.getTargetException()); //$NON-NLS-1$ - } + try { + resources = getAllResources(startTag, endTag); + } catch (InvocationTargetException e) { + // Log and continue with the original resources + CVSUIPlugin.log(IStatus.ERROR, "An error occurred while determining if extra resources should be included in the merge", e.getTargetException()); //$NON-NLS-1$ + } MergeSynchronizeParticipant participant = MergeSynchronizeParticipant.getMatchingParticipant(resources, startTag, endTag); if(participant == null) { CVSMergeSubscriber s = new CVSMergeSubscriber(resources, startTag, endTag, false); @@ -113,19 +113,19 @@ public class MergeWizard extends Wizard { } private IResource[] getAllResources(CVSTag startTag, CVSTag endTag) throws InvocationTargetException { - // Only do the extra work if the model is a logical model (i.e. not IResource) - if (!WorkspaceTraversalAction.isLogicalModel(mappings)) - return resources; - CVSMergeSubscriber s = new CVSMergeSubscriber(WorkspaceTraversalAction.getProjects(resources), startTag, endTag, false); - IResource[] allResources = WorkspaceTraversalAction.getResourcesToCompare(mappings, s); - s.cancel(); - return allResources; - } + // Only do the extra work if the model is a logical model (i.e. not IResource) + if (!WorkspaceTraversalAction.isLogicalModel(mappings)) + return resources; + CVSMergeSubscriber s = new CVSMergeSubscriber(WorkspaceTraversalAction.getProjects(resources), startTag, endTag, false); + IResource[] allResources = WorkspaceTraversalAction.getResourcesToCompare(mappings, s); + s.cancel(); + return allResources; + } - public static boolean isShowModelSync() { + public static boolean isShowModelSync() { return CVSUIPlugin.getPlugin().getPreferenceStore().getBoolean(ICVSUIConstants.PREF_ENABLE_MODEL_SYNC); } - + private IResource[] getProjects(IResource[] resources) { Set<IProject> projects = new HashSet<>(); for (int i = 0; i < resources.length; i++) { @@ -135,16 +135,16 @@ public class MergeWizard extends Wizard { return projects.toArray(new IResource[projects.size()]); } - private Command.LocalOption[] getLocalOptions(CVSTag startTag, CVSTag endTag) { + private Command.LocalOption[] getLocalOptions(CVSTag startTag, CVSTag endTag) { List<LocalOption> options = new ArrayList<>(); - if (startTag != null) { - options.add(Command.makeArgumentOption(Update.JOIN, startTag.getName())); - } - options.add(Command.makeArgumentOption(Update.JOIN, endTag.getName())); - return options.toArray(new Command.LocalOption[options.size()]); - } + if (startTag != null) { + options.add(Command.makeArgumentOption(Update.JOIN, startTag.getName())); + } + options.add(Command.makeArgumentOption(Update.JOIN, endTag.getName())); + return options.toArray(new Command.LocalOption[options.size()]); + } - private IWorkbenchPart getPart() { - return part; - } + private IWorkbenchPart getPart() { + return part; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java index 02b52e4c7..b00039397 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/MergeWizardPage.java @@ -31,275 +31,275 @@ import org.eclipse.ui.PlatformUI; public class MergeWizardPage extends CVSWizardPage { - private Text endTagField; - private Button endTagBrowseButton; - private TagSource tagSource; - private Text startTagField; - private Button startTagBrowseButton; - private TagRefreshButtonArea tagRefreshArea; - private CVSTag startTag; - private CVSTag endTag; - private Button previewButton; - private Button noPreviewButton; - protected boolean preview = true; + private Text endTagField; + private Button endTagBrowseButton; + private TagSource tagSource; + private Text startTagField; + private Button startTagBrowseButton; + private TagRefreshButtonArea tagRefreshArea; + private CVSTag startTag; + private CVSTag endTag; + private Button previewButton; + private Button noPreviewButton; + protected boolean preview = true; private Button onlyPreviewConflicts; private boolean isOnlyPreviewConflicts = false; - public MergeWizardPage(String pageName, String title, ImageDescriptor titleImage, String description, TagSource tagSource) { - super(pageName, title, titleImage, description); - this.tagSource = tagSource; - } + public MergeWizardPage(String pageName, String title, ImageDescriptor titleImage, String description, TagSource tagSource) { + super(pageName, title, titleImage, description); + this.tagSource = tagSource; + } - @Override + @Override public void createControl(Composite parent) { - - final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent); - - final Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DEFAULT)); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.MERGE_WIZARD_PAGE); - - final Composite mainArea = new Composite(composite, SWT.NONE); - mainArea.setLayoutData(SWTUtils.createHFillGridData()); - mainArea.setLayout(SWTUtils.createGridLayout(2, converter, SWTUtils.MARGINS_NONE)); - - createEndTagArea(mainArea); - createStartTagArea(mainArea); - SWTUtils.equalizeControls(converter, new Button [] { endTagBrowseButton, startTagBrowseButton } ); - - createPreviewOptionArea(composite, converter); - createTagRefreshArea(composite); + + final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent); + + final Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_DEFAULT)); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.MERGE_WIZARD_PAGE); + + final Composite mainArea = new Composite(composite, SWT.NONE); + mainArea.setLayoutData(SWTUtils.createHFillGridData()); + mainArea.setLayout(SWTUtils.createGridLayout(2, converter, SWTUtils.MARGINS_NONE)); + + createEndTagArea(mainArea); + createStartTagArea(mainArea); + SWTUtils.equalizeControls(converter, new Button [] { endTagBrowseButton, startTagBrowseButton } ); + + createPreviewOptionArea(composite, converter); + createTagRefreshArea(composite); - Dialog.applyDialogFont(composite); - setControl(composite); - } + Dialog.applyDialogFont(composite); + setControl(composite); + } - private void createPreviewOptionArea(Composite parent, PixelConverter converter) { - - final Composite composite= new Composite(parent, SWT.NONE); - composite.setLayoutData(SWTUtils.createHFillGridData()); - composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); - - previewButton = SWTUtils.createRadioButton(composite, CVSUIMessages.MergeWizardPage_0); - if (MergeWizard.isShowModelSync()) { - onlyPreviewConflicts = SWTUtils.createCheckBox(composite, CVSUIMessages.MergeWizardPage_14); - GridData data = SWTUtils.createHFillGridData(1); - data.horizontalIndent = 10; - onlyPreviewConflicts.setLayoutData(data); - } - noPreviewButton = SWTUtils.createRadioButton(composite, CVSUIMessages.MergeWizardPage_1); - SelectionAdapter selectionAdapter = new SelectionAdapter() { - @Override + private void createPreviewOptionArea(Composite parent, PixelConverter converter) { + + final Composite composite= new Composite(parent, SWT.NONE); + composite.setLayoutData(SWTUtils.createHFillGridData()); + composite.setLayout(SWTUtils.createGridLayout(1, converter, SWTUtils.MARGINS_NONE)); + + previewButton = SWTUtils.createRadioButton(composite, CVSUIMessages.MergeWizardPage_0); + if (MergeWizard.isShowModelSync()) { + onlyPreviewConflicts = SWTUtils.createCheckBox(composite, CVSUIMessages.MergeWizardPage_14); + GridData data = SWTUtils.createHFillGridData(1); + data.horizontalIndent = 10; + onlyPreviewConflicts.setLayoutData(data); + } + noPreviewButton = SWTUtils.createRadioButton(composite, CVSUIMessages.MergeWizardPage_1); + SelectionAdapter selectionAdapter = new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - preview = previewButton.getSelection(); - updateEnablements(); - } - }; - previewButton.setSelection(preview); - noPreviewButton.setSelection(!preview); - previewButton.addSelectionListener(selectionAdapter); - noPreviewButton.addSelectionListener(selectionAdapter); - if (onlyPreviewConflicts != null) { - onlyPreviewConflicts.setEnabled(preview); - onlyPreviewConflicts.setSelection(isOnlyPreviewConflicts); - onlyPreviewConflicts.addSelectionListener(new SelectionAdapter() { + preview = previewButton.getSelection(); + updateEnablements(); + } + }; + previewButton.setSelection(preview); + noPreviewButton.setSelection(!preview); + previewButton.addSelectionListener(selectionAdapter); + noPreviewButton.addSelectionListener(selectionAdapter); + if (onlyPreviewConflicts != null) { + onlyPreviewConflicts.setEnabled(preview); + onlyPreviewConflicts.setSelection(isOnlyPreviewConflicts); + onlyPreviewConflicts.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { isOnlyPreviewConflicts = onlyPreviewConflicts.getSelection(); } }); - } - } - private void createTagRefreshArea(Composite composite) { - tagRefreshArea = new TagRefreshButtonArea(getShell(), getTagSource(), null) { - @Override + } + } + private void createTagRefreshArea(Composite composite) { + tagRefreshArea = new TagRefreshButtonArea(getShell(), getTagSource(), null) { + @Override public void refresh(boolean background) { - super.refresh(background); - updateStartTag(startTagField.getText()); - updateEndTag(endTagField.getText()); - }; - }; - tagRefreshArea.setRunnableContext(getContainer()); - tagRefreshArea.createArea(composite); - } + super.refresh(background); + updateStartTag(startTagField.getText()); + updateEndTag(endTagField.getText()); + }; + }; + tagRefreshArea.setRunnableContext(getContainer()); + tagRefreshArea.createArea(composite); + } - private void createEndTagArea(Composite parent) { - SWTUtils.createLabel(parent, CVSUIMessages.MergeWizardPage_2, 2); - - endTagField = SWTUtils.createText(parent); + private void createEndTagArea(Composite parent) { + SWTUtils.createLabel(parent, CVSUIMessages.MergeWizardPage_2, 2); + + endTagField = SWTUtils.createText(parent); endTagField.addModifyListener(e -> updateEndTag(endTagField.getText())); - final int endTagIncludeFlags = TagSelectionArea.INCLUDE_VERSIONS | TagSelectionArea.INCLUDE_BRANCHES | TagSelectionArea.INCLUDE_HEAD_TAG; - TagContentAssistProcessor.createContentAssistant(endTagField, tagSource, endTagIncludeFlags); - endTagBrowseButton = createPushButton(parent, CVSUIMessages.MergeWizardPage_3); - - endTagBrowseButton.addSelectionListener(new SelectionAdapter() { - @Override + final int endTagIncludeFlags = TagSelectionArea.INCLUDE_VERSIONS | TagSelectionArea.INCLUDE_BRANCHES | TagSelectionArea.INCLUDE_HEAD_TAG; + TagContentAssistProcessor.createContentAssistant(endTagField, tagSource, endTagIncludeFlags); + endTagBrowseButton = createPushButton(parent, CVSUIMessages.MergeWizardPage_3); + + endTagBrowseButton.addSelectionListener(new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - TagSelectionDialog dialog = new TagSelectionDialog(getShell(), getTagSource(), - CVSUIMessages.MergeWizardPage_4, - CVSUIMessages.MergeWizardPage_5, - endTagIncludeFlags, - false, IHelpContextIds.MERGE_END_PAGE); - if (dialog.open() == Window.OK) { - CVSTag selectedTag = dialog.getResult(); - setEndTag(selectedTag); - } - } - }); - } - - private void createStartTagArea(Composite parent) { - - SWTUtils.createLabel(parent, CVSUIMessages.MergeWizardPage_6, 2); + TagSelectionDialog dialog = new TagSelectionDialog(getShell(), getTagSource(), + CVSUIMessages.MergeWizardPage_4, + CVSUIMessages.MergeWizardPage_5, + endTagIncludeFlags, + false, IHelpContextIds.MERGE_END_PAGE); + if (dialog.open() == Window.OK) { + CVSTag selectedTag = dialog.getResult(); + setEndTag(selectedTag); + } + } + }); + } + + private void createStartTagArea(Composite parent) { + + SWTUtils.createLabel(parent, CVSUIMessages.MergeWizardPage_6, 2); - startTagField = SWTUtils.createText(parent); + startTagField = SWTUtils.createText(parent); startTagField.addModifyListener(e -> updateStartTag(startTagField.getText())); - TagContentAssistProcessor.createContentAssistant(startTagField, tagSource, TagSelectionArea.INCLUDE_VERSIONS); + TagContentAssistProcessor.createContentAssistant(startTagField, tagSource, TagSelectionArea.INCLUDE_VERSIONS); - startTagBrowseButton = createPushButton(parent, CVSUIMessages.MergeWizardPage_7); - startTagBrowseButton.addSelectionListener(new SelectionAdapter() { - @Override + startTagBrowseButton = createPushButton(parent, CVSUIMessages.MergeWizardPage_7); + startTagBrowseButton.addSelectionListener(new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - TagSelectionDialog dialog = new TagSelectionDialog(getShell(), getTagSource(), - CVSUIMessages.MergeWizardPage_8, - CVSUIMessages.MergeWizardPage_9, - TagSelectionDialog.INCLUDE_VERSIONS | TagSelectionDialog.INCLUDE_DATES, - false, IHelpContextIds.MERGE_START_PAGE); - if (dialog.open() == Window.OK) { - CVSTag selectedTag = dialog.getResult(); - setStartTag(selectedTag); - } - } - }); - } + TagSelectionDialog dialog = new TagSelectionDialog(getShell(), getTagSource(), + CVSUIMessages.MergeWizardPage_8, + CVSUIMessages.MergeWizardPage_9, + TagSelectionDialog.INCLUDE_VERSIONS | TagSelectionDialog.INCLUDE_DATES, + false, IHelpContextIds.MERGE_START_PAGE); + if (dialog.open() == Window.OK) { + CVSTag selectedTag = dialog.getResult(); + setStartTag(selectedTag); + } + } + }); + } - protected void updateEndTag(String text) { - if (endTag == null || !endTag.getName().equals(text)) { - CVSTag tag = getTagFor(text, false); - setEndTag(tag); - } - updateEnablements(); - } - - protected void updateStartTag(String text) { - if (startTag == null || !startTag.getName().equals(text)) { - CVSTag tag = getTagFor(text, true); - setStartTag(tag); - } - updateEnablements(); - } + protected void updateEndTag(String text) { + if (endTag == null || !endTag.getName().equals(text)) { + CVSTag tag = getTagFor(text, false); + setEndTag(tag); + } + updateEnablements(); + } + + protected void updateStartTag(String text) { + if (startTag == null || !startTag.getName().equals(text)) { + CVSTag tag = getTagFor(text, true); + setStartTag(tag); + } + updateEnablements(); + } - private CVSTag getTagFor(String text, boolean versionsOnly) { - if (text.equals(CVSTag.DEFAULT.getName())) { - if (versionsOnly) return null; - return CVSTag.DEFAULT; - } - if (text.equals(CVSTag.BASE.getName())) { - if (versionsOnly) return null; - return CVSTag.BASE; - } - CVSTag[] tags; - if (versionsOnly) { - tags = tagSource.getTags(new int[] { CVSTag.VERSION, CVSTag.DATE }); - } else { - tags = tagSource.getTags(new int[] { CVSTag.VERSION, CVSTag.BRANCH, CVSTag.DATE }); - } - for (int i = 0; i < tags.length; i++) { - CVSTag tag = tags[i]; - if (tag.getName().equals(text)) { - return tag; - } - } - return null; - } + private CVSTag getTagFor(String text, boolean versionsOnly) { + if (text.equals(CVSTag.DEFAULT.getName())) { + if (versionsOnly) return null; + return CVSTag.DEFAULT; + } + if (text.equals(CVSTag.BASE.getName())) { + if (versionsOnly) return null; + return CVSTag.BASE; + } + CVSTag[] tags; + if (versionsOnly) { + tags = tagSource.getTags(new int[] { CVSTag.VERSION, CVSTag.DATE }); + } else { + tags = tagSource.getTags(new int[] { CVSTag.VERSION, CVSTag.BRANCH, CVSTag.DATE }); + } + for (int i = 0; i < tags.length; i++) { + CVSTag tag = tags[i]; + if (tag.getName().equals(text)) { + return tag; + } + } + return null; + } - protected void setEndTag(CVSTag selectedTag) { - if (selectedTag == null || endTag == null || !endTag.equals(selectedTag)) { - endTag = selectedTag; - if (endTagField != null) { - String name = endTagField.getText(); - if (endTag != null) - name = endTag.getName(); - if (!endTagField.getText().equals(name)) - endTagField.setText(name); - if (startTag == null && endTag != null && endTag.getType() == CVSTag.BRANCH) { - CVSTag tag = findCommonBaseTag(endTag); - if (tag != null) { - setStartTag(tag); - } - } - } - updateEnablements(); - } - } + protected void setEndTag(CVSTag selectedTag) { + if (selectedTag == null || endTag == null || !endTag.equals(selectedTag)) { + endTag = selectedTag; + if (endTagField != null) { + String name = endTagField.getText(); + if (endTag != null) + name = endTag.getName(); + if (!endTagField.getText().equals(name)) + endTagField.setText(name); + if (startTag == null && endTag != null && endTag.getType() == CVSTag.BRANCH) { + CVSTag tag = findCommonBaseTag(endTag); + if (tag != null) { + setStartTag(tag); + } + } + } + updateEnablements(); + } + } - protected void setStartTag(CVSTag selectedTag) { - if (selectedTag == null || startTag != null || endTag == null || !endTag.equals(selectedTag)) { - startTag = selectedTag; - if (startTagField != null) { - String name = startTagField.getText(); - if (startTag != null) - name = startTag.getName(); - if (!startTagField.getText().equals(name)) - startTagField.setText(name); - } - updateEnablements(); - } - } - - private CVSTag findCommonBaseTag(CVSTag tag) { - CVSTag[] tags = tagSource.getTags(CVSTag.VERSION); - for (int i = 0; i < tags.length; i++) { - CVSTag potentialMatch = tags[i]; - if (potentialMatch.getName().indexOf(tag.getName()) != -1) { - return potentialMatch; - } - } - return null; - } + protected void setStartTag(CVSTag selectedTag) { + if (selectedTag == null || startTag != null || endTag == null || !endTag.equals(selectedTag)) { + startTag = selectedTag; + if (startTagField != null) { + String name = startTagField.getText(); + if (startTag != null) + name = startTag.getName(); + if (!startTagField.getText().equals(name)) + startTagField.setText(name); + } + updateEnablements(); + } + } + + private CVSTag findCommonBaseTag(CVSTag tag) { + CVSTag[] tags = tagSource.getTags(CVSTag.VERSION); + for (int i = 0; i < tags.length; i++) { + CVSTag potentialMatch = tags[i]; + if (potentialMatch.getName().indexOf(tag.getName()) != -1) { + return potentialMatch; + } + } + return null; + } - private void updateEnablements() { - if (onlyPreviewConflicts != null) - onlyPreviewConflicts.setEnabled(preview); - if (endTag == null && endTagField.getText().length() > 0) { - setErrorMessage(CVSUIMessages.MergeWizardPage_10); - } else if (startTag == null && startTagField.getText().length() > 0) { - setErrorMessage(CVSUIMessages.MergeWizardPage_11); - } else if (endTag != null && startTag != null && startTag.equals(endTag)) { - setErrorMessage(CVSUIMessages.MergeWizardPage_12); - } else if (startTag == null && endTag != null && preview) { - setErrorMessage(CVSUIMessages.MergeWizardPage_13); - } else { - setErrorMessage(null); - } - setPageComplete((startTag != null || !preview) && endTag != null && (startTag == null || !startTag.equals(endTag))); - } + private void updateEnablements() { + if (onlyPreviewConflicts != null) + onlyPreviewConflicts.setEnabled(preview); + if (endTag == null && endTagField.getText().length() > 0) { + setErrorMessage(CVSUIMessages.MergeWizardPage_10); + } else if (startTag == null && startTagField.getText().length() > 0) { + setErrorMessage(CVSUIMessages.MergeWizardPage_11); + } else if (endTag != null && startTag != null && startTag.equals(endTag)) { + setErrorMessage(CVSUIMessages.MergeWizardPage_12); + } else if (startTag == null && endTag != null && preview) { + setErrorMessage(CVSUIMessages.MergeWizardPage_13); + } else { + setErrorMessage(null); + } + setPageComplete((startTag != null || !preview) && endTag != null && (startTag == null || !startTag.equals(endTag))); + } - protected TagSource getTagSource() { - return tagSource; - } + protected TagSource getTagSource() { + return tagSource; + } - private Button createPushButton(Composite parent, String label) { - final Button button = new Button(parent, SWT.PUSH); - button.setText(label); - button.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); - return button; - } + private Button createPushButton(Composite parent, String label) { + final Button button = new Button(parent, SWT.PUSH); + button.setText(label); + button.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); + return button; + } - public CVSTag getStartTag() { - return startTag; - } - - public CVSTag getEndTag() { - return endTag; - } + public CVSTag getStartTag() { + return startTag; + } + + public CVSTag getEndTag() { + return endTag; + } - public boolean isPreview() { - return preview; - } - - public boolean isOnlyPreviewConflicts() { - return isOnlyPreviewConflicts; - } + public boolean isPreview() { + return preview; + } + + public boolean isOnlyPreviewConflicts() { + return isOnlyPreviewConflicts; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizard.java index dfff977c3..fa2e49126 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizard.java @@ -45,94 +45,94 @@ import org.eclipse.team.internal.ccvs.ui.Policy; * 5. Perform the operation on Finish. */ public class ModeWizard extends ResizableWizard { - - public static class ModeChange { - - private final IFile fFile; - private final KSubstOption fMode; - - private KSubstOption fNewMode; - - public ModeChange(IFile file, KSubstOption mode) { - fFile = file; - fMode= mode; - fNewMode= mode; - } - - public IFile getFile() { - return fFile; - } - - public KSubstOption getMode() { - return fMode; - } - - public KSubstOption getNewMode() { - return fNewMode; - } - - public boolean hasChanged() { - return !fMode.equals(fNewMode); - } - - public void setNewMode(KSubstOption mode) { - fNewMode= mode; - } - - public int compareTo(Object o) { - return fFile.getName().compareTo(((ModeChange)o).getFile().getName()); - } - } - - protected List fChanges; - final ModeWizardSelectionPage fPage; - - public static ModeWizard run(final Shell shell, final IResource [] resources) { - - final ModeWizard [] wizard= new ModeWizard[1]; + + public static class ModeChange { + + private final IFile fFile; + private final KSubstOption fMode; + + private KSubstOption fNewMode; + + public ModeChange(IFile file, KSubstOption mode) { + fFile = file; + fMode= mode; + fNewMode= mode; + } + + public IFile getFile() { + return fFile; + } + + public KSubstOption getMode() { + return fMode; + } + + public KSubstOption getNewMode() { + return fNewMode; + } + + public boolean hasChanged() { + return !fMode.equals(fNewMode); + } + + public void setNewMode(KSubstOption mode) { + fNewMode= mode; + } + + public int compareTo(Object o) { + return fFile.getName().compareTo(((ModeChange)o).getFile().getName()); + } + } + + protected List fChanges; + final ModeWizardSelectionPage fPage; + + public static ModeWizard run(final Shell shell, final IResource [] resources) { + + final ModeWizard [] wizard= new ModeWizard[1]; BusyIndicator.showWhile(shell.getDisplay(), () -> wizard[0] = new ModeWizard(shell, resources)); - - open(shell, wizard[0]); - return wizard[0]; - } - - /** - * Creates a wizard to set the keyword substitution mode for the specified resources. - * - * @param resources the resources to alter - * @param depth the recursion depth - * @param defaultOption the keyword substitution option to select by default - */ - - protected ModeWizard(Shell shell, final IResource[] resources) { - super(CVSUIMessages.ModeWizard_0, CVSUIPlugin.getPlugin().getDialogSettings(), 700, 480); - setWindowTitle(CVSUIMessages.ModeWizard_1); - - fChanges= getModeChanges(shell, resources); - fPage= new ModeWizardSelectionPage(fChanges); + + open(shell, wizard[0]); + return wizard[0]; + } + + /** + * Creates a wizard to set the keyword substitution mode for the specified resources. + * + * @param resources the resources to alter + * @param depth the recursion depth + * @param defaultOption the keyword substitution option to select by default + */ + + protected ModeWizard(Shell shell, final IResource[] resources) { + super(CVSUIMessages.ModeWizard_0, CVSUIPlugin.getPlugin().getDialogSettings(), 700, 480); + setWindowTitle(CVSUIMessages.ModeWizard_1); + + fChanges= getModeChanges(shell, resources); + fPage= new ModeWizardSelectionPage(fChanges); // Workbench.getInstance().getProgressService().busyCursorWhile(new IRunnableWithProgress() { - - } - - @Override + + } + + @Override public void addPages() { - addPage(fPage); - } - - @Override + addPage(fPage); + } + + @Override public boolean needsProgressMonitor() { - return true; - } - - protected static List getModeChanges(Shell shell, IResource [] resources) { - + return true; + } + + protected static List getModeChanges(Shell shell, IResource [] resources) { + final ArrayList<ModeChange> changes = new ArrayList<>(); final HashSet<IResource> visited = new HashSet<>(); - - for (int i = 0; i < resources.length; i++) { - final IResource currentResource = resources[i]; - try { + + for (int i = 0; i < resources.length; i++) { + final IResource currentResource = resources[i]; + try { currentResource.accept((IResourceVisitor) resource -> { try { if (visited.contains(resource) || resource.getType() != IResource.FILE || !resource.exists()) @@ -153,117 +153,117 @@ public class ModeWizard extends ResizableWizard { // always return true and let the depth determine if children are visited return true; }, IResource.DEPTH_INFINITE, false); - } catch (CoreException e) { - CVSUIPlugin.openError(shell, CVSUIMessages.ModeWizard_2, null, e); - } - } - return changes; - } - - @Override + } catch (CoreException e) { + CVSUIPlugin.openError(shell, CVSUIMessages.ModeWizard_2, null, e); + } + } + return changes; + } + + @Override public boolean performFinish() { - try { - final List<IStatus> messages = new ArrayList<>(); - final List changes= fPage.getChanges(); - if (changes.size() == 0) - return true; - - final String comment = fPage.getComment(getShell()); - if (comment == null) - return false; - - getContainer().run(false /*fork*/, true /*cancelable*/, new IRunnableWithProgress() { - @Override + try { + final List<IStatus> messages = new ArrayList<>(); + final List changes= fPage.getChanges(); + if (changes.size() == 0) + return true; + + final String comment = fPage.getComment(getShell()); + if (comment == null) + return false; + + getContainer().run(false /*fork*/, true /*cancelable*/, new IRunnableWithProgress() { + @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - try { - final int totalWork= 10000; - monitor.beginTask(CVSUIMessages.ModeWizard_3, totalWork); - - final Map changesPerProvider= getProviderMapping(changes); - - final int initialWork= totalWork / 10; - monitor.worked(initialWork); - - final int workPerProvider = (totalWork - initialWork) / changesPerProvider.size(); + try { + final int totalWork= 10000; + monitor.beginTask(CVSUIMessages.ModeWizard_3, totalWork); + + final Map changesPerProvider= getProviderMapping(changes); + + final int initialWork= totalWork / 10; + monitor.worked(initialWork); + + final int workPerProvider = (totalWork - initialWork) / changesPerProvider.size(); - for (Iterator iter = changesPerProvider.entrySet().iterator(); iter.hasNext();) { - final Map.Entry entry = (Map.Entry) iter.next(); - final CVSTeamProvider provider = (CVSTeamProvider)entry.getKey(); - final Map providerFiles = (Map) entry.getValue(); + for (Iterator iter = changesPerProvider.entrySet().iterator(); iter.hasNext();) { + final Map.Entry entry = (Map.Entry) iter.next(); + final CVSTeamProvider provider = (CVSTeamProvider)entry.getKey(); + final Map providerFiles = (Map) entry.getValue(); - final IStatus status = provider.setKeywordSubstitution(providerFiles, comment, Policy.subMonitorFor(monitor, workPerProvider)); - if (status.getCode() != IStatus.OK) { - messages.add(status); - } - } - // Broadcast a decorator change so all interested parties will update their labels. - // This is done in particular because the syncview will not see this change - // as a change in state for the resources involved - CVSUIPlugin.broadcastPropertyChange(new PropertyChangeEvent(this, CVSUIPlugin.P_DECORATORS_CHANGED, null, null)); - } catch (TeamException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }); - // Check for any status messages and display them - if (!messages.isEmpty()) { - boolean error = false; - final MultiStatus combinedStatus = new MultiStatus(CVSUIPlugin.ID, 0, CVSUIMessages.ModeWizard_4, null); - for (int i = 0; i < messages.size(); i++) { - final IStatus status = messages.get(i); - if (status.getSeverity() == IStatus.ERROR || status.getCode() == CVSStatus.SERVER_ERROR) { - error = true; - } - combinedStatus.merge(status); - } - String message = null; - IStatus statusToDisplay; - if (combinedStatus.getChildren().length == 1) { - message = combinedStatus.getMessage(); - statusToDisplay = combinedStatus.getChildren()[0]; - } else { - statusToDisplay = combinedStatus; - } - final String title= error ? CVSUIMessages.ModeWizard_5 : CVSUIMessages.ModeWizard_6; // - CVSUIPlugin.openError(getShell(), title, message, new CVSException(statusToDisplay)); - } - return super.performFinish(); - } catch (InterruptedException e) { - return true; - } catch (InvocationTargetException e) { - CVSUIPlugin.openError(getShell(), CVSUIMessages.ModeWizard_4, null, e); - return false; - } - } - - /** - * Get a map - * @param changes - * @return - */ - static Map getProviderMapping(Collection changes) { - + final IStatus status = provider.setKeywordSubstitution(providerFiles, comment, Policy.subMonitorFor(monitor, workPerProvider)); + if (status.getCode() != IStatus.OK) { + messages.add(status); + } + } + // Broadcast a decorator change so all interested parties will update their labels. + // This is done in particular because the syncview will not see this change + // as a change in state for the resources involved + CVSUIPlugin.broadcastPropertyChange(new PropertyChangeEvent(this, CVSUIPlugin.P_DECORATORS_CHANGED, null, null)); + } catch (TeamException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }); + // Check for any status messages and display them + if (!messages.isEmpty()) { + boolean error = false; + final MultiStatus combinedStatus = new MultiStatus(CVSUIPlugin.ID, 0, CVSUIMessages.ModeWizard_4, null); + for (int i = 0; i < messages.size(); i++) { + final IStatus status = messages.get(i); + if (status.getSeverity() == IStatus.ERROR || status.getCode() == CVSStatus.SERVER_ERROR) { + error = true; + } + combinedStatus.merge(status); + } + String message = null; + IStatus statusToDisplay; + if (combinedStatus.getChildren().length == 1) { + message = combinedStatus.getMessage(); + statusToDisplay = combinedStatus.getChildren()[0]; + } else { + statusToDisplay = combinedStatus; + } + final String title= error ? CVSUIMessages.ModeWizard_5 : CVSUIMessages.ModeWizard_6; // + CVSUIPlugin.openError(getShell(), title, message, new CVSException(statusToDisplay)); + } + return super.performFinish(); + } catch (InterruptedException e) { + return true; + } catch (InvocationTargetException e) { + CVSUIPlugin.openError(getShell(), CVSUIMessages.ModeWizard_4, null, e); + return false; + } + } + + /** + * Get a map + * @param changes + * @return + */ + static Map getProviderMapping(Collection changes) { + final Map<RepositoryProvider, HashMap<?, ?>> table = new HashMap<>(); - - for (Iterator iter = changes.iterator(); iter.hasNext();) { - final ModeChange change= (ModeChange)iter.next(); - - if (!change.hasChanged()) - continue; - - final IFile file = change.getFile(); - final RepositoryProvider provider = RepositoryProvider.getProvider(file.getProject(), CVSProviderPlugin.getTypeId()); - - if (!table.containsKey(provider)) { - table.put(provider, new HashMap()); - } - final Map providerMap = table.get(provider); - providerMap.put(file, change.getNewMode()); - } - return table; - } + + for (Iterator iter = changes.iterator(); iter.hasNext();) { + final ModeChange change= (ModeChange)iter.next(); + + if (!change.hasChanged()) + continue; + + final IFile file = change.getFile(); + final RepositoryProvider provider = RepositoryProvider.getProvider(file.getProject(), CVSProviderPlugin.getTypeId()); + + if (!table.containsKey(provider)) { + table.put(provider, new HashMap()); + } + final Map providerMap = table.get(provider); + providerMap.put(file, change.getNewMode()); + } + return table; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizardSelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizardSelectionPage.java index d53b5e8ee..2e9ce65b0 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizardSelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModeWizardSelectionPage.java @@ -733,9 +733,9 @@ public class ModeWizardSelectionPage extends WizardPage { * The main composite with the vertical sash */ final Composite mainComposite= SWTUtils.createHVFillComposite(parent, SWTUtils.MARGINS_DEFAULT); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(mainComposite, IHelpContextIds.KEYWORD_SUBSTITUTION_PAGE); - + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(mainComposite, IHelpContextIds.KEYWORD_SUBSTITUTION_PAGE); + final SashForm mainSash= new SashForm(mainComposite, SWT.VERTICAL); mainSash.setLayoutData(SWTUtils.createHVFillGridData()); diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModuleSelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModuleSelectionPage.java index 42315700a..e69fa9c04 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModuleSelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ModuleSelectionPage.java @@ -73,7 +73,7 @@ public class ModuleSelectionPage extends CVSWizardPage { Composite composite = createComposite(parent, 2, false); if (helpContextId != null) - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContextId); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContextId); Listener listener = event -> updateEnablements(false); @@ -114,7 +114,7 @@ public class ModuleSelectionPage extends CVSWizardPage { useModuleAndProjectNameButton.setSelection(false); updateEnablements(false); setControl(composite); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } private void updateText() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/NewLocationWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/NewLocationWizard.java index f0afb980b..5ea822d70 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/NewLocationWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/NewLocationWizard.java @@ -140,9 +140,9 @@ public class NewLocationWizard extends Wizard implements INewWizard { if (keepLocation) { KnownRepositories.getInstance().addRepository(location[0], true /* let the world know */); if (switchPerspectives) { - final IWorkbench workbench= PlatformUI.getWorkbench(); - final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - + final IWorkbench workbench= PlatformUI.getWorkbench(); + final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + final String defaultPerspectiveID= promptForPerspectiveSwitch(); if (defaultPerspectiveID != null) { @@ -193,7 +193,7 @@ public class NewLocationWizard extends Wizard implements INewWizard { } if (desired != null) { - + String message;; String desc = desired.getDescription(); if (desc == null) { @@ -201,25 +201,25 @@ public class NewLocationWizard extends Wizard implements INewWizard { } else { message = NLS.bind(CVSUIMessages.NewLocationWizard_3, new String[] { desired.getLabel(), desc }); } - // Ask the user whether to switch + // Ask the user whether to switch final MessageDialogWithToggle m = MessageDialogWithToggle.openYesNoQuestion( - Utils.getShell(null), - CVSUIMessages.NewLocationWizard_1, - message, - CVSUIMessages.NewLocationWizard_4, - false /* toggle state */, - store, - ICVSUIConstants.PREF_CHANGE_PERSPECTIVE_ON_NEW_REPOSITORY_LOCATION); + Utils.getShell(null), + CVSUIMessages.NewLocationWizard_1, + message, + CVSUIMessages.NewLocationWizard_4, + false /* toggle state */, + store, + ICVSUIConstants.PREF_CHANGE_PERSPECTIVE_ON_NEW_REPOSITORY_LOCATION); final int result = m.getReturnCode(); switch (result) { // yes case IDialogConstants.YES_ID: case IDialogConstants.OK_ID : - return desiredID; + return desiredID; // no case IDialogConstants.NO_ID : - return null; + return null; } } return null; diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RepositorySelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RepositorySelectionPage.java index 42b98226a..1bfdb46a3 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RepositorySelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RepositorySelectionPage.java @@ -86,7 +86,7 @@ public class RepositorySelectionPage extends CVSWizardPage { public void createControl(Composite parent) { Composite composite = createComposite(parent, 1, false); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARING_SELECT_REPOSITORY_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARING_SELECT_REPOSITORY_PAGE); if (extendedDescription == null) { extendedDescription = CVSUIMessages.RepositorySelectionPage_description; } @@ -103,39 +103,39 @@ public class RepositorySelectionPage extends CVSWizardPage { traverseRepositories(e.character); } } - }); + }); table = createTable(composite, 1); table.setContentProvider(new WorkbenchContentProvider()); table.setLabelProvider(new DecoratingRepoLabelProvider()/*WorkbenchLabelProvider()*/); table.setComparator(new RepositoryComparator()); - table.addDoubleClickListener(event -> getContainer().showPage(getNextPage())); - table.getTable().addKeyListener(new KeyAdapter() { + table.addDoubleClickListener(event -> getContainer().showPage(getNextPage())); + table.getTable().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { traverseRepositories(e.character); } - }); + }); setControl(composite); initializeValues(); - Dialog.applyDialogFont(parent); - - table.addSelectionChangedListener(event -> { - result = (ICVSRepositoryLocation)table.getStructuredSelection().getFirstElement(); - setPageComplete(true); + Dialog.applyDialogFont(parent); + + table.addSelectionChangedListener(event -> { + result = (ICVSRepositoryLocation)table.getStructuredSelection().getFirstElement(); + setPageComplete(true); }); - - useExistingRepo.addListener(SWT.Selection, event -> { - if (useNewRepo.getSelection()) { - table.getTable().setEnabled(false); - result = null; - } else { - table.getTable().setEnabled(true); - result = (ICVSRepositoryLocation)table.getStructuredSelection().getFirstElement(); - } - setPageComplete(true); + + useExistingRepo.addListener(SWT.Selection, event -> { + if (useNewRepo.getSelection()) { + table.getTable().setEnabled(false); + result = null; + } else { + table.getTable().setEnabled(true); + result = (ICVSRepositoryLocation)table.getStructuredSelection().getFirstElement(); + } + setPageComplete(true); }); } /** @@ -147,16 +147,16 @@ public class RepositorySelectionPage extends CVSWizardPage { table.setInput(input); if (locations.length == 0) { useNewRepo.setSelection(true); - useExistingRepo.setSelection(false); - table.getTable().setEnabled(false); + useExistingRepo.setSelection(false); + table.getTable().setEnabled(false); } else { - useNewRepo.setSelection(false); + useNewRepo.setSelection(false); useExistingRepo.setSelection(true); - table.getTable().setEnabled(true); - result = locations[0]; + table.getTable().setEnabled(true); + result = locations[0]; table.setSelection(new StructuredSelection(result)); } - setPageComplete(true); + setPageComplete(true); } public ICVSRepositoryLocation getLocation() { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ResizableWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ResizableWizard.java index c794479b0..e377b813f 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ResizableWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/ResizableWizard.java @@ -27,65 +27,65 @@ public class ResizableWizard extends Wizard { private final int DEFAULT_WIDTH; private final int DEFAULT_HEIGHT; - - private static final String BOUNDS_HEIGHT_KEY = "width"; //$NON-NLS-1$ - private static final String BOUNDS_WIDTH_KEY = "height"; //$NON-NLS-1$ - - final String fSectionName; - - public ResizableWizard(String sectionName, IDialogSettings settings) { - this(sectionName, settings, 300, 400); - } - - protected ResizableWizard(String sectionName, IDialogSettings settings, int defaultWidth, int defaultHeight) { - DEFAULT_WIDTH= defaultWidth; - DEFAULT_HEIGHT= defaultHeight; - fSectionName= sectionName; - setDialogSettings(settings); - } - - protected static int open(Shell shell, ResizableWizard wizard) { - final WizardDialog dialog= new WizardDialog(shell, wizard); - dialog.setMinimumPageSize(wizard.loadSize()); - return dialog.open(); - } - - public void saveSize() { - final Rectangle bounds= getContainer().getCurrentPage().getControl().getParent().getClientArea(); - final IDialogSettings settings= getDialogSettings(); - if (settings == null) - return; - - IDialogSettings section= settings.getSection(fSectionName); - if (section == null) - section= settings.addNewSection(fSectionName); - - section.put(BOUNDS_WIDTH_KEY, bounds.width); - section.put(BOUNDS_HEIGHT_KEY, bounds.height); - } - - public Point loadSize() { - final Point size= new Point(DEFAULT_WIDTH, DEFAULT_HEIGHT); - - final IDialogSettings settings= getDialogSettings(); - if (settings == null) - return size; - - final IDialogSettings section= settings.getSection(fSectionName); - if (section == null) - return size; + + private static final String BOUNDS_HEIGHT_KEY = "width"; //$NON-NLS-1$ + private static final String BOUNDS_WIDTH_KEY = "height"; //$NON-NLS-1$ + + final String fSectionName; + + public ResizableWizard(String sectionName, IDialogSettings settings) { + this(sectionName, settings, 300, 400); + } + + protected ResizableWizard(String sectionName, IDialogSettings settings, int defaultWidth, int defaultHeight) { + DEFAULT_WIDTH= defaultWidth; + DEFAULT_HEIGHT= defaultHeight; + fSectionName= sectionName; + setDialogSettings(settings); + } + + protected static int open(Shell shell, ResizableWizard wizard) { + final WizardDialog dialog= new WizardDialog(shell, wizard); + dialog.setMinimumPageSize(wizard.loadSize()); + return dialog.open(); + } + + public void saveSize() { + final Rectangle bounds= getContainer().getCurrentPage().getControl().getParent().getClientArea(); + final IDialogSettings settings= getDialogSettings(); + if (settings == null) + return; + + IDialogSettings section= settings.getSection(fSectionName); + if (section == null) + section= settings.addNewSection(fSectionName); + + section.put(BOUNDS_WIDTH_KEY, bounds.width); + section.put(BOUNDS_HEIGHT_KEY, bounds.height); + } + + public Point loadSize() { + final Point size= new Point(DEFAULT_WIDTH, DEFAULT_HEIGHT); + + final IDialogSettings settings= getDialogSettings(); + if (settings == null) + return size; + + final IDialogSettings section= settings.getSection(fSectionName); + if (section == null) + return size; - try { - size.x= section.getInt(BOUNDS_WIDTH_KEY); - size.y= section.getInt(BOUNDS_HEIGHT_KEY); - } catch (NumberFormatException e) { - } - return size; - } + try { + size.x= section.getInt(BOUNDS_WIDTH_KEY); + size.y= section.getInt(BOUNDS_HEIGHT_KEY); + } catch (NumberFormatException e) { + } + return size; + } - public boolean performFinish() { - saveSize(); - return true; - } + public boolean performFinish() { + saveSize(); + return true; + } } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RestoreFromRepositoryFileSelectionPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RestoreFromRepositoryFileSelectionPage.java index 1e00d3b71..504afc838 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RestoreFromRepositoryFileSelectionPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/RestoreFromRepositoryFileSelectionPage.java @@ -126,7 +126,7 @@ public class RestoreFromRepositoryFileSelectionPage extends CVSWizardPage { Composite composite= createComposite(parent, 1, false); setControl(composite); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.RESTORE_FROM_REPOSITORY_FILE_SELECTION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.RESTORE_FROM_REPOSITORY_FILE_SELECTION_PAGE); // Top and bottom panes: top is the two selection panes, bottom is the file content viewer Splitter vsplitter= new Splitter(composite, SWT.VERTICAL); @@ -165,7 +165,7 @@ public class RestoreFromRepositoryFileSelectionPage extends CVSWizardPage { initializeValues(); updateWidgetEnablements(); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } protected CheckboxTableViewer createRevisionSelectionTable(CompareViewerPane composite, HistoryTableProvider tableProvider) { diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/SharingWizardSyncPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/SharingWizardSyncPage.java index 85964f94e..619929cef 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/SharingWizardSyncPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/SharingWizardSyncPage.java @@ -90,7 +90,7 @@ public class SharingWizardSyncPage extends CVSWizardPage implements IDiffChangeL updatePage(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARING_SYNC_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARING_SYNC_PAGE); Dialog.applyDialogFont(parent); } diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/UpdateWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/UpdateWizard.java index 8bc35262a..dd1f9b330 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/UpdateWizard.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/UpdateWizard.java @@ -37,21 +37,21 @@ public class UpdateWizard extends ResizableWizard { private TagSelectionWizardPage tagSelectionPage; public UpdateWizard(IWorkbenchPart part, ResourceMapping[] mappers) { - super("UpdateWizard", CVSUIPlugin.getPlugin().getDialogSettings()); //$NON-NLS-1$ + super("UpdateWizard", CVSUIPlugin.getPlugin().getDialogSettings()); //$NON-NLS-1$ this.part = part; this.mappers = mappers; setWindowTitle(CVSUIMessages.UpdateWizard_title); } - public static void run(IWorkbenchPart part, ResourceMapping[] mappers) { - final UpdateWizard wizard = new UpdateWizard(part, mappers); - open(part.getSite().getShell(), wizard); - } - + public static void run(IWorkbenchPart part, ResourceMapping[] mappers) { + final UpdateWizard wizard = new UpdateWizard(part, mappers); + open(part.getSite().getShell(), wizard); + } + @Override public void addPages() { ImageDescriptor substImage = CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_CHECKOUT); - tagSelectionPage = new TagSelectionWizardPage("tagPage", CVSUIMessages.UpdateWizard_0, substImage, CVSUIMessages.UpdateWizard_1, TagSource.create(mappers), TagSourceWorkbenchAdapter.INCLUDE_ALL_TAGS); //$NON-NLS-1$ + tagSelectionPage = new TagSelectionWizardPage("tagPage", CVSUIMessages.UpdateWizard_0, substImage, CVSUIMessages.UpdateWizard_1, TagSource.create(mappers), TagSourceWorkbenchAdapter.INCLUDE_ALL_TAGS); //$NON-NLS-1$ tagSelectionPage.setAllowNoTag(true); tagSelectionPage.setHelpContxtId(IHelpContextIds.UPDATE_TAG_SELETION_PAGE); CVSTag tag = getInitialSelection(); @@ -62,27 +62,27 @@ public class UpdateWizard extends ResizableWizard { } /** - * @return - */ - private CVSTag getInitialSelection() { - try { - for (int i = 0; i < mappers.length; i++) { - ResourceMapping mapper = mappers[i]; - IProject[] projects = mapper.getProjects(); - for (int k = 0; k < projects.length; k++) { - IProject project = projects[k]; - ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project); - FolderSyncInfo info = folder.getFolderSyncInfo(); - if (info != null) { - return info.getTag(); - } - } - } - } catch (CoreException e) { - CVSUIPlugin.log(e); - } - return null; - } + * @return + */ + private CVSTag getInitialSelection() { + try { + for (int i = 0; i < mappers.length; i++) { + ResourceMapping mapper = mappers[i]; + IProject[] projects = mapper.getProjects(); + for (int k = 0; k < projects.length; k++) { + IProject project = projects[k]; + ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project); + FolderSyncInfo info = folder.getFolderSyncInfo(); + if (info != null) { + return info.getTag(); + } + } + } + } catch (CoreException e) { + CVSUIPlugin.log(e); + } + return null; + } @Override public boolean performFinish() { diff --git a/bundles/org.eclipse.team.genericeditor.diff.extension/META-INF/MANIFEST.MF b/bundles/org.eclipse.team.genericeditor.diff.extension/META-INF/MANIFEST.MF index 85e627ea5..4553e0bb4 100644 --- a/bundles/org.eclipse.team.genericeditor.diff.extension/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.team.genericeditor.diff.extension/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.team.genericeditor.diff.extension;singleton:=true -Bundle-Version: 1.0.200.qualifier +Bundle-Version: 1.0.300.qualifier Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-RequiredExecutionEnvironment: JavaSE-1.8 diff --git a/bundles/org.eclipse.team.genericeditor.diff.extension/pom.xml b/bundles/org.eclipse.team.genericeditor.diff.extension/pom.xml index ea46def4f..e3677f48f 100644 --- a/bundles/org.eclipse.team.genericeditor.diff.extension/pom.xml +++ b/bundles/org.eclipse.team.genericeditor.diff.extension/pom.xml @@ -19,6 +19,6 @@ </parent> <groupId>org.eclipse.team</groupId> <artifactId>org.eclipse.team.genericeditor.diff.extension</artifactId> - <version>1.0.200-SNAPSHOT</version> + <version>1.0.300-SNAPSHOT</version> <packaging>eclipse-plugin</packaging> </project> diff --git a/bundles/org.eclipse.team.genericeditor.diff.extension/src/org/eclipse/team/internal/genericeditor/diff/extension/partitioner/DiffPartitioner.java b/bundles/org.eclipse.team.genericeditor.diff.extension/src/org/eclipse/team/internal/genericeditor/diff/extension/partitioner/DiffPartitioner.java index 882efd10c..c408bb41c 100644 --- a/bundles/org.eclipse.team.genericeditor.diff.extension/src/org/eclipse/team/internal/genericeditor/diff/extension/partitioner/DiffPartitioner.java +++ b/bundles/org.eclipse.team.genericeditor.diff.extension/src/org/eclipse/team/internal/genericeditor/diff/extension/partitioner/DiffPartitioner.java @@ -24,12 +24,12 @@ public class DiffPartitioner implements IDocumentSetupParticipant{ public void setup(IDocument document) { IPartitionTokenScanner scanner = new DiffPartitionScanner(); FastPartitioner partitioner = new FastPartitioner(scanner, IDiffPartitioning.LEGAL_PARTITION_TYPES); - if (document instanceof IDocumentExtension3) { - final IDocumentExtension3 extension3 = (IDocumentExtension3) document; - extension3.setDocumentPartitioner(IDiffPartitioning.DIFF_PARTITIONINING, partitioner); - } else { - document.setDocumentPartitioner(partitioner); - } - partitioner.connect(document); + if (document instanceof IDocumentExtension3) { + final IDocumentExtension3 extension3 = (IDocumentExtension3) document; + extension3.setDocumentPartitioner(IDiffPartitioning.DIFF_PARTITIONINING, partitioner); + } else { + document.setDocumentPartitioner(partitioner); + } + partitioner.connect(document); } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/DefaultUIFileModificationValidator.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/DefaultUIFileModificationValidator.java index 4c44dcc35..99ac0ba6a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/DefaultUIFileModificationValidator.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/DefaultUIFileModificationValidator.java @@ -42,28 +42,28 @@ import org.eclipse.ui.PlatformUI; */ public class DefaultUIFileModificationValidator extends DefaultFileModificationValidator { - public static class FileListDialog extends DetailsDialog { + public static class FileListDialog extends DetailsDialog { - private final IFile[] files; + private final IFile[] files; - public static boolean openQuestion(Shell shell, IFile[] files) { - FileListDialog dialog = new FileListDialog(shell, files); - int code = dialog.open(); - return code == OK; - } + public static boolean openQuestion(Shell shell, IFile[] files) { + FileListDialog dialog = new FileListDialog(shell, files); + int code = dialog.open(); + return code == OK; + } - public FileListDialog(Shell parentShell, IFile[] files) { - super(parentShell, TeamUIMessages.DefaultUIFileModificationValidator_0); - this.files = files; + public FileListDialog(Shell parentShell, IFile[] files) { + super(parentShell, TeamUIMessages.DefaultUIFileModificationValidator_0); + this.files = files; setImageKey(DLG_IMG_WARNING); - } + } - @Override + @Override protected void createMainDialogArea(Composite parent) { createWrappingLabel(parent, TeamUIMessages.DefaultUIFileModificationValidator_1); - } + } - @Override + @Override protected Composite createDropDownDialogArea(Composite parent) { Composite composite = createComposite(parent); createWrappingLabel(composite, TeamUIMessages.DefaultUIFileModificationValidator_2); @@ -78,65 +78,65 @@ public class DefaultUIFileModificationValidator extends DefaultFileModificationV fileList.add(files[i].getFullPath().toString()); } return composite; - } + } - @Override + @Override protected void updateEnablements() { - // Nothing to do - } + // Nothing to do + } - @Override + @Override protected boolean includeCancelButton() { - return false; - } + return false; + } - @Override + @Override protected boolean includeOkButton() { - return false; - } + return false; + } - @Override + @Override protected void createButtonsForButtonBar(Composite parent) { - createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, true); - createButton(parent, IDialogConstants.NO_ID, IDialogConstants.NO_LABEL, true); - super.createButtonsForButtonBar(parent); - } + createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, true); + createButton(parent, IDialogConstants.NO_ID, IDialogConstants.NO_LABEL, true); + super.createButtonsForButtonBar(parent); + } - @Override + @Override protected void buttonPressed(int id) { - if (IDialogConstants.YES_ID == id) { - okPressed(); - } else if (IDialogConstants.NO_ID == id) { - cancelPressed(); - } else { - super.buttonPressed(id); - } - } - } - - @Override + if (IDialogConstants.YES_ID == id) { + okPressed(); + } else if (IDialogConstants.NO_ID == id) { + cancelPressed(); + } else { + super.buttonPressed(id); + } + } + } + + @Override public IStatus validateEdit(final IFile[] allFiles, FileModificationValidationContext context) { - final IFile[] readOnlyFiles = getReadOnlyFiles(allFiles); - if (readOnlyFiles.length > 0 && context != null) { - final Shell shell = getShell(context); - final boolean[] ok = new boolean[] { false }; - if (readOnlyFiles.length == 1) { - syncExec(() -> ok[0] = MessageDialog.openQuestion(shell, TeamUIMessages.DefaultUIFileModificationValidator_3, NLS.bind(TeamUIMessages.DefaultUIFileModificationValidator_4, new String[] { readOnlyFiles[0].getFullPath().toString() }))); - } else { - syncExec(() -> ok[0] = FileListDialog.openQuestion(shell, readOnlyFiles)); - } - if (ok[0]) { - setWritable(readOnlyFiles); - }; - } else if (readOnlyFiles.length > 0 && context == null) { - if (isMakeWrittableWhenContextNotProvided()) { - setWritable(readOnlyFiles); - } - } - return getStatus(readOnlyFiles); - } - - private Shell getShell(FileModificationValidationContext context) { + final IFile[] readOnlyFiles = getReadOnlyFiles(allFiles); + if (readOnlyFiles.length > 0 && context != null) { + final Shell shell = getShell(context); + final boolean[] ok = new boolean[] { false }; + if (readOnlyFiles.length == 1) { + syncExec(() -> ok[0] = MessageDialog.openQuestion(shell, TeamUIMessages.DefaultUIFileModificationValidator_3, NLS.bind(TeamUIMessages.DefaultUIFileModificationValidator_4, new String[] { readOnlyFiles[0].getFullPath().toString() }))); + } else { + syncExec(() -> ok[0] = FileListDialog.openQuestion(shell, readOnlyFiles)); + } + if (ok[0]) { + setWritable(readOnlyFiles); + }; + } else if (readOnlyFiles.length > 0 && context == null) { + if (isMakeWrittableWhenContextNotProvided()) { + setWritable(readOnlyFiles); + } + } + return getStatus(readOnlyFiles); + } + + private Shell getShell(FileModificationValidationContext context) { if (context.getShell() != null) return (Shell)context.getShell(); IWorkbench workbench = PlatformUI.getWorkbench(); @@ -147,21 +147,21 @@ public class DefaultUIFileModificationValidator extends DefaultFileModificationV return null; } - private static void syncExec(Runnable runnable) { + private static void syncExec(Runnable runnable) { Display display = PlatformUI.getWorkbench().getDisplay(); display.syncExec(runnable); } @Override public IStatus validateSave(IFile file) { - if (file.isReadOnly() && isMakeWrittableWhenContextNotProvided()) { - IFile[] readOnlyFiles = new IFile[] { file }; - setWritable(readOnlyFiles); - return getStatus(readOnlyFiles); - } else { - return getDefaultStatus(file); - } - } + if (file.isReadOnly() && isMakeWrittableWhenContextNotProvided()) { + IFile[] readOnlyFiles = new IFile[] { file }; + setWritable(readOnlyFiles); + return getStatus(readOnlyFiles); + } else { + return getDefaultStatus(file); + } + } private boolean isMakeWrittableWhenContextNotProvided() { return TeamUIPlugin.getPlugin().getPreferenceStore().getBoolean(IPreferenceIds.MAKE_FILE_WRITTABLE_IF_CONTEXT_MISSING); @@ -179,18 +179,18 @@ public class DefaultUIFileModificationValidator extends DefaultFileModificationV } protected IStatus setWritable(final IFile[] files) { - for (int i = 0; i < files.length; i++) { - IFile file = files[i]; - ResourceAttributes attributes = file.getResourceAttributes(); - if (attributes != null) { - attributes.setReadOnly(false); - } - try { - file.setResourceAttributes(attributes); - } catch (CoreException e) { - return e.getStatus(); - } - } - return Status.OK_STATUS; - } + for (int i = 0; i < files.length; i++) { + IFile file = files[i]; + ResourceAttributes attributes = file.getResourceAttributes(); + if (attributes != null) { + attributes.setReadOnly(false); + } + try { + file.setResourceAttributes(attributes); + } catch (CoreException e) { + return e.getStatus(); + } + } + return Status.OK_STATUS; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/IHelpContextIds.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/IHelpContextIds.java index a2784021e..7daf497f9 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/IHelpContextIds.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/IHelpContextIds.java @@ -16,14 +16,14 @@ package org.eclipse.team.internal.ui; public interface IHelpContextIds { public static final String PREFIX = TeamUIPlugin.ID + "."; //$NON-NLS-1$ - // Dialogs - public static final String CONFIGURE_REFRESH_SCHEDULE_DIALOG = PREFIX + "configre_refresh_schedule_dialog_context"; //$NON-NLS-1$ + // Dialogs + public static final String CONFIGURE_REFRESH_SCHEDULE_DIALOG = PREFIX + "configre_refresh_schedule_dialog_context"; //$NON-NLS-1$ // Preference Pages public static final String IGNORE_PREFERENCE_PAGE = PREFIX + "ignore_preference_page_context"; //$NON-NLS-1$ public static final String MODEL_PREFERENCE_PAGE = PREFIX + "model_preference_page_context"; //$NON-NLS-1$ public static final String FILE_TYPE_PREFERENCE_PAGE = PREFIX + "file_type_preference_page_context"; //$NON-NLS-1$ - public static final String SYNC_PREFERENCE_PAGE = PREFIX + "sync_preference_page_context"; //$NON-NLS-1$ + public static final String SYNC_PREFERENCE_PAGE = PREFIX + "sync_preference_page_context"; //$NON-NLS-1$ public static final String SYNC_STARTUP_PREFERENCE_PAGE = PREFIX + "sync_startup_preference_page_context"; //$NON-NLS-1$ public static final String RESOURCE_MODEL_PREFERENCE_PAGE = PREFIX + "resource_model_preference_page_context"; //$NON-NLS-1$ @@ -32,7 +32,7 @@ public interface IHelpContextIds { public static final String IMPORT_PROJECT_SET_PAGE = PREFIX + "import_project_set_page_context"; //$NON-NLS-1$ public static final String EXPORT_PROJECT_SET_PAGE = PREFIX + "export_project_set_page_context"; //$NON-NLS-1$ public static final String SYNC_RESOURCE_SELECTION_PAGE = PREFIX + "sync_resource_selection_page_context"; //$NON-NLS-1$ - public static final String REFRESH_WIZARD_SELECTION_PAGE = PREFIX + "refresh_wizard_selection_page_context"; //$NON-NLS-1$ + public static final String REFRESH_WIZARD_SELECTION_PAGE = PREFIX + "refresh_wizard_selection_page_context"; //$NON-NLS-1$ // Catchup Release Viewers public static final String TARGET_CATCHUP_RELEASE_VIEWER = PREFIX + "target_catchup_release_viewer_context"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/PixelConverter.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/PixelConverter.java index 3e6dbcad7..398cadd8c 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/PixelConverter.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/PixelConverter.java @@ -24,12 +24,12 @@ public class PixelConverter { public PixelConverter(Control control) { GC gc = new GC(control); - try { - gc.setFont(control.getFont()); - fFontMetrics= gc.getFontMetrics(); - } finally { - gc.dispose(); - } + try { + gc.setFont(control.getFont()); + fFontMetrics= gc.getFontMetrics(); + } finally { + gc.dispose(); + } } public int convertHeightInCharsToPixels(int chars) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Policy.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Policy.java index ff31ff64d..4034293fa 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Policy.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Policy.java @@ -33,19 +33,19 @@ public class Policy { public static boolean DEBUG_DND = false; public static boolean DEBUG_COMPARE_EDITOR_INPUT = false; - private static String ACTION_BUNDLE = "org.eclipse.team.internal.ui.actions.actions"; //$NON-NLS-1$ - private static ResourceBundle actionBundle = null; + private static String ACTION_BUNDLE = "org.eclipse.team.internal.ui.actions.actions"; //$NON-NLS-1$ + private static ResourceBundle actionBundle = null; - /* - * Returns a resource bundle, creating one if it none is available. - */ - public static ResourceBundle getActionBundle() { - // thread safety - ResourceBundle tmpBundle = actionBundle; - if (tmpBundle != null) - return tmpBundle; - return actionBundle = ResourceBundle.getBundle(ACTION_BUNDLE); - } + /* + * Returns a resource bundle, creating one if it none is available. + */ + public static ResourceBundle getActionBundle() { + // thread safety + ResourceBundle tmpBundle = actionBundle; + if (tmpBundle != null) + return tmpBundle; + return actionBundle = ResourceBundle.getBundle(ACTION_BUNDLE); + } static final DebugOptionsListener DEBUG_OPTIONS_LISTENER = options -> { boolean DEBUG = options.getBooleanOption(TeamUIPlugin.ID + "/debug", false); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/ProjectSetImporter.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/ProjectSetImporter.java index d34cf98d2..70e5d16dc 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/ProjectSetImporter.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/ProjectSetImporter.java @@ -111,37 +111,37 @@ public class ProjectSetImporter { } else { UIProjectSetSerializationContext context = new UIProjectSetSerializationContext(shell, filename); List<TeamException> errors = new ArrayList<TeamException>(); - IMemento[] providers = xmlMemento.getChildren("provider"); //$NON-NLS-1$ - for (int i = 0; i < providers.length; i++) { + IMemento[] providers = xmlMemento.getChildren("provider"); //$NON-NLS-1$ + for (int i = 0; i < providers.length; i++) { ArrayList<String> referenceStrings= new ArrayList<>(); IMemento[] projects = providers[i].getChildren("project"); //$NON-NLS-1$ for (int j = 0; j < projects.length; j++) { referenceStrings.add(projects[j].getString("reference")); //$NON-NLS-1$ } try { - String id = providers[i].getString("id"); //$NON-NLS-1$ - TeamCapabilityHelper.getInstance().processRepositoryId(id, - PlatformUI.getWorkbench().getActivitySupport()); - RepositoryProviderType providerType = RepositoryProviderType.getProviderType(id); - if (providerType == null) { - // The provider type is absent. Perhaps there is another provider that can import this type - providerType = TeamPlugin.getAliasType(id); - } - if (providerType == null) { - throw new TeamException(new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, NLS.bind(TeamUIMessages.ProjectSetImportWizard_0, new String[] { id }), null)); - } - ProjectSetCapability serializer = providerType.getProjectSetCapability(); - ProjectSetCapability.ensureBackwardsCompatible(providerType, serializer); - if (serializer != null) { - IProject[] allProjects = serializer.addToWorkspace(referenceStrings.toArray(new String[referenceStrings.size()]), context, monitor); - if (allProjects != null) - newProjects.addAll(Arrays.asList(allProjects)); - } - } catch (TeamException e) { - errors.add(e); - } + String id = providers[i].getString("id"); //$NON-NLS-1$ + TeamCapabilityHelper.getInstance().processRepositoryId(id, + PlatformUI.getWorkbench().getActivitySupport()); + RepositoryProviderType providerType = RepositoryProviderType.getProviderType(id); + if (providerType == null) { + // The provider type is absent. Perhaps there is another provider that can import this type + providerType = TeamPlugin.getAliasType(id); + } + if (providerType == null) { + throw new TeamException(new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, NLS.bind(TeamUIMessages.ProjectSetImportWizard_0, new String[] { id }), null)); + } + ProjectSetCapability serializer = providerType.getProjectSetCapability(); + ProjectSetCapability.ensureBackwardsCompatible(providerType, serializer); + if (serializer != null) { + IProject[] allProjects = serializer.addToWorkspace(referenceStrings.toArray(new String[referenceStrings.size()]), context, monitor); + if (allProjects != null) + newProjects.addAll(Arrays.asList(allProjects)); + } + } catch (TeamException e) { + errors.add(e); + } } - if (!errors.isEmpty()) { + if (!errors.isEmpty()) { TeamException[] exceptions= errors.toArray(new TeamException[errors.size()]); IStatus[] status= new IStatus[exceptions.length]; for (int i= 0; i < exceptions.length; i++) { @@ -150,14 +150,14 @@ public class ProjectSetImporter { throw new TeamException(new MultiStatus(TeamUIPlugin.ID, 0, status, TeamUIMessages.ProjectSetImportWizard_1, null)); } - //try working sets - IMemento[] sets = xmlMemento.getChildren("workingSets"); //$NON-NLS-1$ - IWorkingSetManager wsManager = TeamUIPlugin.getPlugin().getWorkbench().getWorkingSetManager(); - boolean replaceAll = false; - boolean mergeAll = false; - boolean skipAll = false; + //try working sets + IMemento[] sets = xmlMemento.getChildren("workingSets"); //$NON-NLS-1$ + IWorkingSetManager wsManager = TeamUIPlugin.getPlugin().getWorkbench().getWorkingSetManager(); + boolean replaceAll = false; + boolean mergeAll = false; + boolean skipAll = false; - for (int i = 0; i < sets.length; i++) { + for (int i = 0; i < sets.length; i++) { IWorkingSet newWs = wsManager.createWorkingSet(sets[i]); if (newWs != null) { IWorkingSet oldWs = wsManager.getWorkingSet(newWs diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/SWTUtils.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/SWTUtils.java index 51b44f4c6..18e26ea52 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/SWTUtils.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/SWTUtils.java @@ -51,8 +51,8 @@ public class SWTUtils { public static final int MARGINS_DIALOG= 1; public static PreferenceLinkArea createPreferenceLink(IWorkbenchPreferenceContainer container, Composite parent, String pageId, String text) { - final PreferenceLinkArea area = new PreferenceLinkArea(parent, SWT.NONE, pageId, text, container, null); - return area; + final PreferenceLinkArea area = new PreferenceLinkArea(parent, SWT.NONE, pageId, text, container, null); + return area; } public static Link createPreferenceLink(final Shell shell, Composite parent, final String pageId, String message) { @@ -81,120 +81,120 @@ public class SWTUtils { } } - /** - * Get the preference node with pageId. - * - * @param pageId - * @return IPreferenceNode - */ - private static IPreferenceNode getPreferenceNode(String pageId) { - Iterator iterator = PlatformUI.getWorkbench().getPreferenceManager() - .getElements(PreferenceManager.PRE_ORDER).iterator(); - while (iterator.hasNext()) { - IPreferenceNode next = (IPreferenceNode) iterator.next(); - if (next.getId().equals(pageId)) { + /** + * Get the preference node with pageId. + * + * @param pageId + * @return IPreferenceNode + */ + private static IPreferenceNode getPreferenceNode(String pageId) { + Iterator iterator = PlatformUI.getWorkbench().getPreferenceManager() + .getElements(PreferenceManager.PRE_ORDER).iterator(); + while (iterator.hasNext()) { + IPreferenceNode next = (IPreferenceNode) iterator.next(); + if (next.getId().equals(pageId)) { return next; } - } - return null; - } - - - public static GridData createGridData(int width, int height, boolean hFill, boolean vFill) { - return createGridData(width, height, hFill ? SWT.FILL : SWT.BEGINNING, vFill ? SWT.FILL : SWT.CENTER, hFill, vFill); - } - - public static GridData createGridData(int width, int height, int hAlign, int vAlign, boolean hGrab, boolean vGrab) { - final GridData gd= new GridData(hAlign, vAlign, hGrab, vGrab); - gd.widthHint= width; - gd.heightHint= height; - return gd; - } - - public static GridData createHFillGridData() { - return createHFillGridData(1); - } - - public static GridData createHFillGridData(int span) { - final GridData gd= createGridData(0, SWT.DEFAULT, SWT.FILL, SWT.CENTER, true, false); - gd.horizontalSpan= span; - return gd; - } - - public static Composite createHFillComposite(Composite parent, int margins) { - return createHFillComposite(parent, margins, 1); - } - - public static Composite createHFillComposite(Composite parent, int margins, int columns) { - final Composite composite= new Composite(parent, SWT.NONE); - composite.setFont(parent.getFont()); - composite.setLayoutData(createHFillGridData()); - composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); - return composite; - } - - public static Composite createHVFillComposite(Composite parent, int margins) { - return createHVFillComposite(parent, margins, 1); - } - - public static Composite createHVFillComposite(Composite parent, int margins, int columns) { - final Composite composite= new Composite(parent, SWT.NONE); - composite.setFont(parent.getFont()); - composite.setLayoutData(createHVFillGridData()); - composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); - return composite; - } - - - /** - * Groups - */ - - public static Group createHFillGroup(Composite parent, String text, int margins) { - return createHFillGroup(parent, text, margins, 1); - } - - public static Group createHFillGroup(Composite parent, String text, int margins, int rows) { - final Group group= new Group(parent, SWT.NONE); - group.setFont(parent.getFont()); - group.setLayoutData(createHFillGridData()); - if (text != null) - group.setText(text); - group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); - return group; - } - - public static Group createHVFillGroup(Composite parent, String text, int margins) { - return createHVFillGroup(parent, text, margins, 1); - } - - public static Group createHVFillGroup(Composite parent, String text, int margins, int rows) { - final Group group= new Group(parent, SWT.NONE); - group.setFont(parent.getFont()); - group.setLayoutData(createHVFillGridData()); - if (text != null) - group.setText(text); - group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); - return group; - } - - - /** - * Grid data - */ - - public static GridData createHVFillGridData() { - return createHVFillGridData(1); - } - - public static GridData createHVFillGridData(int span) { - final GridData gd= createGridData(0, 0, true, true); - gd.horizontalSpan= span; - return gd; - } - - - /** + } + return null; + } + + + public static GridData createGridData(int width, int height, boolean hFill, boolean vFill) { + return createGridData(width, height, hFill ? SWT.FILL : SWT.BEGINNING, vFill ? SWT.FILL : SWT.CENTER, hFill, vFill); + } + + public static GridData createGridData(int width, int height, int hAlign, int vAlign, boolean hGrab, boolean vGrab) { + final GridData gd= new GridData(hAlign, vAlign, hGrab, vGrab); + gd.widthHint= width; + gd.heightHint= height; + return gd; + } + + public static GridData createHFillGridData() { + return createHFillGridData(1); + } + + public static GridData createHFillGridData(int span) { + final GridData gd= createGridData(0, SWT.DEFAULT, SWT.FILL, SWT.CENTER, true, false); + gd.horizontalSpan= span; + return gd; + } + + public static Composite createHFillComposite(Composite parent, int margins) { + return createHFillComposite(parent, margins, 1); + } + + public static Composite createHFillComposite(Composite parent, int margins, int columns) { + final Composite composite= new Composite(parent, SWT.NONE); + composite.setFont(parent.getFont()); + composite.setLayoutData(createHFillGridData()); + composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); + return composite; + } + + public static Composite createHVFillComposite(Composite parent, int margins) { + return createHVFillComposite(parent, margins, 1); + } + + public static Composite createHVFillComposite(Composite parent, int margins, int columns) { + final Composite composite= new Composite(parent, SWT.NONE); + composite.setFont(parent.getFont()); + composite.setLayoutData(createHVFillGridData()); + composite.setLayout(createGridLayout(columns, new PixelConverter(parent), margins)); + return composite; + } + + + /** + * Groups + */ + + public static Group createHFillGroup(Composite parent, String text, int margins) { + return createHFillGroup(parent, text, margins, 1); + } + + public static Group createHFillGroup(Composite parent, String text, int margins, int rows) { + final Group group= new Group(parent, SWT.NONE); + group.setFont(parent.getFont()); + group.setLayoutData(createHFillGridData()); + if (text != null) + group.setText(text); + group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); + return group; + } + + public static Group createHVFillGroup(Composite parent, String text, int margins) { + return createHVFillGroup(parent, text, margins, 1); + } + + public static Group createHVFillGroup(Composite parent, String text, int margins, int rows) { + final Group group= new Group(parent, SWT.NONE); + group.setFont(parent.getFont()); + group.setLayoutData(createHVFillGridData()); + if (text != null) + group.setText(text); + group.setLayout(createGridLayout(rows, new PixelConverter(parent), margins)); + return group; + } + + + /** + * Grid data + */ + + public static GridData createHVFillGridData() { + return createHVFillGridData(1); + } + + public static GridData createHVFillGridData(int span) { + final GridData gd= createGridData(0, 0, true, true); + gd.horizontalSpan= span; + return gd; + } + + + /** * Create a grid layout with the specified number of columns and the * standard spacings. * @@ -207,96 +207,96 @@ public class SWTUtils { * <code>MARGINS_NONE</code> or <code>MARGINS_DIALOG</code>. * @return the grid layout */ - public static GridLayout createGridLayout(int numColumns, PixelConverter converter, int margins) { - Assert.isTrue(margins == MARGINS_DEFAULT || margins == MARGINS_NONE || margins == MARGINS_DIALOG); - - final GridLayout layout= new GridLayout(numColumns, false); - layout.horizontalSpacing= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - layout.verticalSpacing= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - - switch (margins) { - case MARGINS_NONE: - layout.marginLeft= layout.marginRight= 0; - layout.marginTop= layout.marginBottom= 0; - break; - case MARGINS_DIALOG: - layout.marginLeft= layout.marginRight= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.marginTop= layout.marginBottom= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - break; - case MARGINS_DEFAULT: - layout.marginLeft= layout.marginRight= layout.marginWidth; - layout.marginTop= layout.marginBottom= layout.marginHeight; - } - layout.marginWidth= layout.marginHeight= 0; - return layout; - } - - - public static Label createLabel(Composite parent, String message) { - return createLabel(parent, message, 1); - } - - public static Label createLabel(Composite parent, String message, int span) { - final Label label= new Label(parent, SWT.WRAP); - if (message != null) - label.setText(message); - label.setLayoutData(createHFillGridData(span)); - return label; - } - - public static Button createCheckBox(Composite parent, String message) { - return createCheckBox(parent, message, 1); - } - - public static Button createCheckBox(Composite parent, String message, int span) { - final Button button= new Button(parent, SWT.CHECK); - button.setText(message); - button.setLayoutData(createHFillGridData(span)); - return button; - } - - public static Button createRadioButton(Composite parent, String message) { - return createRadioButton(parent, message, 1); - } - - public static Button createRadioButton(Composite parent, String message, int span) { - final Button button= new Button(parent, SWT.RADIO); - button.setText(message); - button.setLayoutData(createHFillGridData(span)); - return button; - } - - - public static Text createText(Composite parent) { - return createText(parent, 1); - } - - public static Text createText(Composite parent, int span) { - final Text text= new Text(parent, SWT.SINGLE | SWT.BORDER); - text.setLayoutData(createHFillGridData(span)); - return text; - } - - - public static Control createPlaceholder(Composite parent, int heightInChars, int span) { - Assert.isTrue(heightInChars > 0); - final Control placeHolder= new Composite(parent, SWT.NONE); - final GridData gd= new GridData(SWT.BEGINNING, SWT.TOP, false, false); - gd.heightHint= new PixelConverter(parent).convertHeightInCharsToPixels(heightInChars); - gd.horizontalSpan= span; - placeHolder.setLayoutData(gd); - return placeHolder; - } - - - public static Control createPlaceholder(Composite parent, int heightInChars) { - return createPlaceholder(parent, heightInChars, 1); - } - - public static PixelConverter createDialogPixelConverter(Control control) { - Dialog.applyDialogFont(control); - return new PixelConverter(control); - } + public static GridLayout createGridLayout(int numColumns, PixelConverter converter, int margins) { + Assert.isTrue(margins == MARGINS_DEFAULT || margins == MARGINS_NONE || margins == MARGINS_DIALOG); + + final GridLayout layout= new GridLayout(numColumns, false); + layout.horizontalSpacing= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + layout.verticalSpacing= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + + switch (margins) { + case MARGINS_NONE: + layout.marginLeft= layout.marginRight= 0; + layout.marginTop= layout.marginBottom= 0; + break; + case MARGINS_DIALOG: + layout.marginLeft= layout.marginRight= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.marginTop= layout.marginBottom= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + break; + case MARGINS_DEFAULT: + layout.marginLeft= layout.marginRight= layout.marginWidth; + layout.marginTop= layout.marginBottom= layout.marginHeight; + } + layout.marginWidth= layout.marginHeight= 0; + return layout; + } + + + public static Label createLabel(Composite parent, String message) { + return createLabel(parent, message, 1); + } + + public static Label createLabel(Composite parent, String message, int span) { + final Label label= new Label(parent, SWT.WRAP); + if (message != null) + label.setText(message); + label.setLayoutData(createHFillGridData(span)); + return label; + } + + public static Button createCheckBox(Composite parent, String message) { + return createCheckBox(parent, message, 1); + } + + public static Button createCheckBox(Composite parent, String message, int span) { + final Button button= new Button(parent, SWT.CHECK); + button.setText(message); + button.setLayoutData(createHFillGridData(span)); + return button; + } + + public static Button createRadioButton(Composite parent, String message) { + return createRadioButton(parent, message, 1); + } + + public static Button createRadioButton(Composite parent, String message, int span) { + final Button button= new Button(parent, SWT.RADIO); + button.setText(message); + button.setLayoutData(createHFillGridData(span)); + return button; + } + + + public static Text createText(Composite parent) { + return createText(parent, 1); + } + + public static Text createText(Composite parent, int span) { + final Text text= new Text(parent, SWT.SINGLE | SWT.BORDER); + text.setLayoutData(createHFillGridData(span)); + return text; + } + + + public static Control createPlaceholder(Composite parent, int heightInChars, int span) { + Assert.isTrue(heightInChars > 0); + final Control placeHolder= new Composite(parent, SWT.NONE); + final GridData gd= new GridData(SWT.BEGINNING, SWT.TOP, false, false); + gd.heightHint= new PixelConverter(parent).convertHeightInCharsToPixels(heightInChars); + gd.horizontalSpan= span; + placeHolder.setLayoutData(gd); + return placeHolder; + } + + + public static Control createPlaceholder(Composite parent, int heightInChars) { + return createPlaceholder(parent, heightInChars, 1); + } + + public static PixelConverter createDialogPixelConverter(Control control) { + Dialog.applyDialogFont(control); + return new PixelConverter(control); + } public static int calculateControlSize(PixelConverter converter, Control [] controls) { return calculateControlSize(converter, controls, 0, controls.length - 1); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamCapabilityHelper.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamCapabilityHelper.java index ec3b41b90..a864f5f78 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamCapabilityHelper.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamCapabilityHelper.java @@ -41,53 +41,53 @@ import org.eclipse.ui.activities.WorkbenchActivityHelper; * @since 3.0 */ public class TeamCapabilityHelper { - /** - * Mapping from repository provider id to IPluginContribution. Used for proper - * activity mapping of natures. - */ - private Map<String, IPluginContribution> providerIdToPluginId; + /** + * Mapping from repository provider id to IPluginContribution. Used for proper + * activity mapping of natures. + */ + private Map<String, IPluginContribution> providerIdToPluginId; - /** - * Singleton instance. - */ - private static TeamCapabilityHelper singleton; + /** + * Singleton instance. + */ + private static TeamCapabilityHelper singleton; - /** - * Get the singleton instance of this class. - * @return the singleton instance of this class. - * @since 3.0 - */ - public static TeamCapabilityHelper getInstance() { - if (singleton == null) { - singleton = new TeamCapabilityHelper(); - } - return singleton; - } + /** + * Get the singleton instance of this class. + * @return the singleton instance of this class. + * @since 3.0 + */ + public static TeamCapabilityHelper getInstance() { + if (singleton == null) { + singleton = new TeamCapabilityHelper(); + } + return singleton; + } - /** - * Create a new <code>IDEWorkbenchActivityHelper</code> which will listen - * for workspace changes and promote activities accordingly. - */ - private TeamCapabilityHelper() { - providerIdToPluginId = new HashMap<String, IPluginContribution>(); - loadRepositoryProviderIds(); + /** + * Create a new <code>IDEWorkbenchActivityHelper</code> which will listen + * for workspace changes and promote activities accordingly. + */ + private TeamCapabilityHelper() { + providerIdToPluginId = new HashMap<String, IPluginContribution>(); + loadRepositoryProviderIds(); - // crawl the initial projects - IProject [] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI.getWorkbench().getActivitySupport(); - for (int i = 0; i < projects.length; i++) { - try { - processProject(projects[i], workbenchActivitySupport); - } catch (CoreException e) { - // do nothing - } - } - } + // crawl the initial projects + IProject [] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); + IWorkbenchActivitySupport workbenchActivitySupport = PlatformUI.getWorkbench().getActivitySupport(); + for (int i = 0; i < projects.length; i++) { + try { + processProject(projects[i], workbenchActivitySupport); + } catch (CoreException e) { + // do nothing + } + } + } - /** - * Loads the list of registered provider types - */ - public void loadRepositoryProviderIds() { + /** + * Loads the list of registered provider types + */ + public void loadRepositoryProviderIds() { providerIdToPluginId.clear(); IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint("org.eclipse.team.core.repository"); //$NON-NLS-1$ if (point != null) { @@ -120,25 +120,25 @@ public class TeamCapabilityHelper { } } - /** - * Handle natures for the given project. - * - * @param project the project - * @param workbenchActivitySupport the activity support - */ - protected void processProject(IProject project, IWorkbenchActivitySupport workbenchActivitySupport) throws CoreException { + /** + * Handle natures for the given project. + * + * @param project the project + * @param workbenchActivitySupport the activity support + */ + protected void processProject(IProject project, IWorkbenchActivitySupport workbenchActivitySupport) throws CoreException { if (!project.isOpen()) return; String id = getProviderIdFor(project); processRepositoryId(id, workbenchActivitySupport); } - /** - * Helper method that enables the activities for the given repository provider. - * - * @param id the repository provider id - * @param workbenchActivitySupport the activity support - */ + /** + * Helper method that enables the activities for the given repository provider. + * + * @param id the repository provider id + * @param workbenchActivitySupport the activity support + */ public void processRepositoryId(String id, IWorkbenchActivitySupport workbenchActivitySupport) { if (id == null) return; @@ -159,27 +159,27 @@ public class TeamCapabilityHelper { workbenchActivitySupport.setEnabledActivityIds(activities); } - /** - * Returns the provider id for this project or <code>null</code> if no providers are mapped - * to this project. Note that this won't instantiate the provider, but instead will simply query - * the persistent property - * - * @param project the project to query. - * @return the provider id for this project or <code>null</code> if no providers are mapped - * to this project - * @throws CoreException - */ - public String getProviderIdFor(IProject project) throws CoreException { - if(project.isAccessible()) { + /** + * Returns the provider id for this project or <code>null</code> if no providers are mapped + * to this project. Note that this won't instantiate the provider, but instead will simply query + * the persistent property + * + * @param project the project to query. + * @return the provider id for this project or <code>null</code> if no providers are mapped + * to this project + * @throws CoreException + */ + public String getProviderIdFor(IProject project) throws CoreException { + if(project.isAccessible()) { //First, look for the session property Object prop = project.getSessionProperty(TeamPlugin.PROVIDER_PROP_KEY); if(prop != null && prop instanceof RepositoryProvider) { - RepositoryProvider provider = (RepositoryProvider) prop; - return provider.getID(); - } + RepositoryProvider provider = (RepositoryProvider) prop; + return provider.getID(); + } //Next, check if it has the ID as a persistent property return project.getPersistentProperty(TeamPlugin.PROVIDER_PROP_KEY); - } - return null; - } + } + return null; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIMessages.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIMessages.java index b854dd6f7..d2b238c3f 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIMessages.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIMessages.java @@ -37,7 +37,7 @@ public class TeamUIMessages extends NLS { public static String TextPreferencePage_ExtensionNotCompleted; - public static String CompareInputChangeNotifier_0; + public static String CompareInputChangeNotifier_0; public static String CompareInputChangeNotifier_1; @@ -279,7 +279,7 @@ public class TeamUIMessages extends NLS { public static String SyncInfoCompareInput_1; public static String SyncInfoCompareInput_2; public static String SyncInfoCompareInput_3; - public static String SyncInfoCompareInput_tooltip; + public static String SyncInfoCompareInput_tooltip; public static String SyncViewerPreferencePage_43; public static String SyncViewerPreferencePage_44; @@ -528,7 +528,7 @@ public class TeamUIMessages extends NLS { public static String HierarchicalModelProvider_0; public static String UIProjectSetSerializationContext_0; public static String UIProjectSetSerializationContext_1; - public static String UIProjectSetSerializationContext_2; + public static String UIProjectSetSerializationContext_2; public static String RemoveSynchronizeParticipantAction_0; public static String RemoveSynchronizeParticipantAction_1; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIPlugin.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIPlugin.java index 86990a54b..978e134ec 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIPlugin.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/TeamUIPlugin.java @@ -188,11 +188,11 @@ public class TeamUIPlugin extends AbstractUIPlugin { // Convert the old compressed folder preference to the new layout preference if (!store.isDefault(IPreferenceIds.SYNCVIEW_COMPRESS_FOLDERS) && !store.getBoolean(IPreferenceIds.SYNCVIEW_COMPRESS_FOLDERS)) { - // Set the compress folder preference to the default true) \ - // so will will ignore it in the future - store.setToDefault(IPreferenceIds.SYNCVIEW_COMPRESS_FOLDERS); - // Set the layout to tree (which was used when compress folder was false) - store.setDefault(IPreferenceIds.SYNCVIEW_DEFAULT_LAYOUT, IPreferenceIds.TREE_LAYOUT); + // Set the compress folder preference to the default true) \ + // so will will ignore it in the future + store.setToDefault(IPreferenceIds.SYNCVIEW_COMPRESS_FOLDERS); + // Set the layout to tree (which was used when compress folder was false) + store.setDefault(IPreferenceIds.SYNCVIEW_DEFAULT_LAYOUT, IPreferenceIds.TREE_LAYOUT); } } @@ -302,12 +302,12 @@ public class TeamUIPlugin extends AbstractUIPlugin { plugin.privateCreateImageDescriptor(id); } private void privateCreateImageDescriptor(String id) { - ImageDescriptor desc = ImageDescriptor.createFromURL(getImageUrl(id)); - imageDescriptors.put(id, desc); + ImageDescriptor desc = ImageDescriptor.createFromURL(getImageUrl(id)); + imageDescriptors.put(id, desc); } private void privateCreateImageDescriptor(String id, String imageUrl) { - ImageDescriptor desc = ImageDescriptor.createFromURL(getImageUrl(imageUrl)); - imageDescriptors.put(id, desc); + ImageDescriptor desc = ImageDescriptor.createFromURL(getImageUrl(imageUrl)); + imageDescriptors.put(id, desc); } /** @@ -423,9 +423,9 @@ public class TeamUIPlugin extends AbstractUIPlugin { createImageDescriptor(plugin, ITeamUIImages.IMG_LOCALREVISION_TABLE); } - private URL getImageUrl(String relative) { - return FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(ICON_PATH + relative), null); - } + private URL getImageUrl(String relative) { + return FileLocator.find(Platform.getBundle(PLUGIN_ID), new Path(ICON_PATH + relative), null); + } /** * Returns the standard display to be used. The method first checks, if the diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/UIProjectSetSerializationContext.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/UIProjectSetSerializationContext.java index 09ce5fe65..4b940cdd6 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/UIProjectSetSerializationContext.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/UIProjectSetSerializationContext.java @@ -89,21 +89,21 @@ public class UIProjectSetSerializationContext extends ProjectSetSerializationCon List resources = Arrays.asList(projects); @Override public boolean needsPrompt(IResource resource) { - if (resource instanceof IProject) { - IProject project = (IProject) resource; - return (project.exists() || getTargetFile(project).exists()) && resources.contains(resource); - } + if (resource instanceof IProject) { + IProject project = (IProject) resource; + return (project.exists() || getTargetFile(project).exists()) && resources.contains(resource); + } return false; } @Override public String promptMessage(IResource resource) { - if (resource.exists()) - return NLS.bind(TeamUIMessages.UIProjectSetSerializationContext_0, new String[] { resource.getName() }); - return NLS.bind(TeamUIMessages.UIProjectSetSerializationContext_2, new String[] { resource.getName(), getTargetFile((IProject)resource).getAbsolutePath() }); + if (resource.exists()) + return NLS.bind(TeamUIMessages.UIProjectSetSerializationContext_0, new String[] { resource.getName() }); + return NLS.bind(TeamUIMessages.UIProjectSetSerializationContext_2, new String[] { resource.getName(), getTargetFile((IProject)resource).getAbsolutePath() }); + } + public File getTargetFile(IProject project) { + return new File(project.getParent().getLocation().toFile(), project.getName()); } - public File getTargetFile(IProject project) { - return new File(project.getParent().getLocation().toFile(), project.getName()); - } }; PromptingDialog dialog = new PromptingDialog( diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Utils.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Utils.java index 683d378e2..6a900158d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Utils.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/Utils.java @@ -590,15 +590,15 @@ public class Utils { } } - public static String getString(String key, ResourceBundle b) { - try { - return b.getString(key); - } catch (MissingResourceException e) { - return key; - } catch (NullPointerException e) { - return "!" + key + "!"; //$NON-NLS-1$ //$NON-NLS-2$ - } - } + public static String getString(String key, ResourceBundle b) { + try { + return b.getString(key); + } catch (MissingResourceException e) { + return key; + } catch (NullPointerException e) { + return "!" + key + "!"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } public static String modeToString(int mode) { switch (mode) { @@ -628,42 +628,42 @@ public class Utils { boolean isResource = false; if (element instanceof IResource) { resources.add((IResource) element); - isResource = true; + isResource = true; } else if (element instanceof ISynchronizeModelElement){ - IResource resource = ((ISynchronizeModelElement) element).getResource(); - if (resource != null) { - resources.add(resource); - isResource = true; - } - } else if (element instanceof ResourceMapping) { - if (includeMappingResources) { - isResource = true; - getResources((ResourceMapping)element, resources); - } + IResource resource = ((ISynchronizeModelElement) element).getResource(); + if (resource != null) { + resources.add(resource); + isResource = true; + } + } else if (element instanceof ResourceMapping) { + if (includeMappingResources) { + isResource = true; + getResources((ResourceMapping)element, resources); + } } else if (element != null) { - Object adapted; - if (isContributed) { - adapted = getResource(element); - } else { - adapted = Adapters.adapt(element, IResource.class); - } - if (adapted instanceof IResource) { - IResource resource = (IResource) adapted; - isResource = true; - if (resource.getType() != IResource.ROOT) { - resources.add(resource); - } - } else { - if (isContributed) { - adapted = getResourceMapping(element); - } else { - adapted = Adapters.adapt(element, ResourceMapping.class); - } - if (adapted instanceof ResourceMapping && includeMappingResources) { - isResource = true; - getResources((ResourceMapping) adapted, resources); - } - } + Object adapted; + if (isContributed) { + adapted = getResource(element); + } else { + adapted = Adapters.adapt(element, IResource.class); + } + if (adapted instanceof IResource) { + IResource resource = (IResource) adapted; + isResource = true; + if (resource.getType() != IResource.ROOT) { + resources.add(resource); + } + } else { + if (isContributed) { + adapted = getResourceMapping(element); + } else { + adapted = Adapters.adapt(element, ResourceMapping.class); + } + if (adapted instanceof ResourceMapping && includeMappingResources) { + isResource = true; + getResources((ResourceMapping) adapted, resources); + } + } } if (!isResource) { if (nonResources != null) @@ -673,21 +673,21 @@ public class Utils { return resources.toArray(new IResource[resources.size()]); } - private static void getResources(ResourceMapping element, List<IResource> resources) { - try { - ResourceTraversal[] traversals = element.getTraversals(ResourceMappingContext.LOCAL_CONTEXT, null); - for (int k = 0; k < traversals.length; k++) { - ResourceTraversal traversal = traversals[k]; - IResource[] resourceArray = traversal.getResources(); - for (int j = 0; j < resourceArray.length; j++) { - IResource resource = resourceArray[j]; - resources.add(resource); - } - } - } catch (CoreException e) { - TeamUIPlugin.log(new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, "Error traversing resource mapping", e)); //$NON-NLS-1$ - } - } + private static void getResources(ResourceMapping element, List<IResource> resources) { + try { + ResourceTraversal[] traversals = element.getTraversals(ResourceMappingContext.LOCAL_CONTEXT, null); + for (int k = 0; k < traversals.length; k++) { + ResourceTraversal traversal = traversals[k]; + IResource[] resourceArray = traversal.getResources(); + for (int j = 0; j < resourceArray.length; j++) { + IResource resource = resourceArray[j]; + resources.add(resource); + } + } + } catch (CoreException e) { + TeamUIPlugin.log(new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, "Error traversing resource mapping", e)); //$NON-NLS-1$ + } + } public static Object[] getNonResources(Object[] elements) { List<Object> nonResources = new ArrayList<>(); @@ -699,9 +699,9 @@ public class Utils { return getResources(element, null, false /* isContributed */, false /* includeMappingResources */); } - public static IResource[] getContributedResources(Object[] elements) { - return getResources(elements, null, true /* isContributed */, true /* isIncudeMappings */); - } + public static IResource[] getContributedResources(Object[] elements) { + return getResources(elements, null, true /* isContributed */, true /* isIncudeMappings */); + } /** * Return whether any sync nodes in the given selection or their @@ -820,7 +820,7 @@ public class Utils { } public static String getKey(String id, String secondaryId) { - return secondaryId == null ? id : id + '/' + secondaryId; + return secondaryId == null ? id : id + '/' + secondaryId; } public static String convertSelection(IResource[] resources) { @@ -862,21 +862,21 @@ public class Utils { return manager.getParticipantDescriptor(participant.getId()).getName(); } - /** - * The viewer will only be updated if the viewer is not null, the control is not disposed, and - * this code is being run from the UI thread. - * @param viewer the viewer to be updated - * @return whether it is safe to update the viewer - */ - public static boolean canUpdateViewer(StructuredViewer viewer) { + /** + * The viewer will only be updated if the viewer is not null, the control is not disposed, and + * this code is being run from the UI thread. + * @param viewer the viewer to be updated + * @return whether it is safe to update the viewer + */ + public static boolean canUpdateViewer(StructuredViewer viewer) { if(viewer == null || viewer.getControl().isDisposed()) return false; Display display = viewer.getControl().getDisplay(); if (display == null) return false; if (display.getThread() != Thread.currentThread ()) return false; return true; - } + } - public static void asyncExec(final Runnable r, StructuredViewer v) { + public static void asyncExec(final Runnable r, StructuredViewer v) { if(v == null) return; final Control ctrl = v.getControl(); if (ctrl != null && !ctrl.isDisposed()) { @@ -888,11 +888,11 @@ public class Utils { } } - public static void syncExec(final Runnable r, StructuredViewer v) { + public static void syncExec(final Runnable r, StructuredViewer v) { if(v == null) return; final Control ctrl = v.getControl(); syncExec(r, ctrl); - } + } public static void syncExec(final Runnable r, final Control ctrl) { if (ctrl != null && !ctrl.isDisposed()) { @@ -914,12 +914,12 @@ public class Utils { } } - public static SyncInfo getSyncInfo(ISynchronizeModelElement node) { - if (node instanceof IAdaptable) { - return ((IAdaptable) node).getAdapter(SyncInfo.class); - } - return null; - } + public static SyncInfo getSyncInfo(ISynchronizeModelElement node) { + if (node instanceof IAdaptable) { + return ((IAdaptable) node).getAdapter(SyncInfo.class); + } + return null; + } public static ISynchronizationCompareAdapter getCompareAdapter(Object element) { ModelProvider provider = getModelProvider(element); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/CompareRevisionAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/CompareRevisionAction.java index c0326ad6b..447d6d50a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/CompareRevisionAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/CompareRevisionAction.java @@ -93,7 +93,7 @@ public class CompareRevisionAction extends BaseSelectionListenerAction { } if (file1 == null || file2 == null || - !file1.exists() || !file2.exists()){ + !file1.exists() || !file2.exists()){ MessageDialog.openError(page.getSite().getShell(), TeamUIMessages.OpenRevisionAction_DeletedRevTitle, TeamUIMessages.CompareRevisionAction_DeleteCompareMessage); return; } @@ -113,7 +113,7 @@ public class CompareRevisionAction extends BaseSelectionListenerAction { } ITypedElement right = new FileRevisionTypedElement(file2, getLocalEncoding()); - openInCompare(left, right); + openInCompare(left, right); } private String getLocalEncoding() { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/JobRunnableContext.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/JobRunnableContext.java index 21a704b83..7bfa52c38 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/JobRunnableContext.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/JobRunnableContext.java @@ -43,53 +43,53 @@ public class JobRunnableContext implements ITeamRunnableContext { * that subclasses can do belongsTo family checking. */ public interface IContextJob { - IRunnableWithProgress getRunnable(); + IRunnableWithProgress getRunnable(); } /* * Class that provides a basic job (i.e. no resource specific interactions) */ private class BasicJob extends Job implements IContextJob { - private final IRunnableWithProgress runnable; - public BasicJob(String name, IRunnableWithProgress runnable) { - super(name); - this.runnable = runnable; - } - @Override + private final IRunnableWithProgress runnable; + public BasicJob(String name, IRunnableWithProgress runnable) { + super(name); + this.runnable = runnable; + } + @Override public IStatus run(IProgressMonitor monitor) { return JobRunnableContext.this.run(runnable, monitor); } @Override public boolean belongsTo(Object family) { - return JobRunnableContext.this.belongsTo(this, family); + return JobRunnableContext.this.belongsTo(this, family); } - @Override + @Override public IRunnableWithProgress getRunnable() { - return runnable; - } + return runnable; + } } /* * Class that provides a resource job (i.e. resource specific interactions) */ private class ResourceJob extends WorkspaceJob implements IContextJob { - private final IRunnableWithProgress runnable; - public ResourceJob(String name, IRunnableWithProgress runnable) { - super(name); - this.runnable = runnable; - } - @Override + private final IRunnableWithProgress runnable; + public ResourceJob(String name, IRunnableWithProgress runnable) { + super(name); + this.runnable = runnable; + } + @Override public IStatus runInWorkspace(IProgressMonitor monitor) { return JobRunnableContext.this.run(runnable, monitor); } @Override public boolean belongsTo(Object family) { - return JobRunnableContext.this.belongsTo(this, family); + return JobRunnableContext.this.belongsTo(this, family); } - @Override + @Override public IRunnableWithProgress getRunnable() { - return runnable; - } + return runnable; + } } public JobRunnableContext(String jobName, IJobChangeListener listener, IWorkbenchSite site) { this.jobName = jobName; @@ -122,7 +122,7 @@ public class JobRunnableContext implements ITeamRunnableContext { if (schedulingRule != null) { job.setRule(schedulingRule); } - job.setUser(isUser()); + job.setUser(isUser()); } /** @@ -165,19 +165,19 @@ public class JobRunnableContext implements ITeamRunnableContext { * Return the completions status for the job. * By default, <code>Status.OK_STATUS</code> * is returned. - * @return the completions status for the job - */ - protected IStatus getCompletionStatus() { - return Status.OK_STATUS; - } + * @return the completions status for the job + */ + protected IStatus getCompletionStatus() { + return Status.OK_STATUS; + } - /** + /** * Return whether the job for this context is in the given family. * By default, <code>false</code> is returned. Subclasses may override. - * @param family the job family being queried - */ - protected boolean belongsTo(IContextJob job, Object family) { - return false; - } + * @param family the job family being queried + */ + protected boolean belongsTo(IContextJob job, Object family) { + return false; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/TeamAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/TeamAction.java index bab147fd1..a4f627bca 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/TeamAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/actions/TeamAction.java @@ -228,44 +228,44 @@ public abstract class TeamAction extends AbstractHandler implements IObjectActio } /** - * Return the selected resource mappins that contain resources in - * projects that are associated with a repository of the given id. - * @param providerId the repository provider id - * @return the resource mappings that contain resources associated with the given provider + * Return the selected resource mappins that contain resources in + * projects that are associated with a repository of the given id. + * @param providerId the repository provider id + * @return the resource mappings that contain resources associated with the given provider */ - protected ResourceMapping[] getSelectedResourceMappings(String providerId) { - Object[] elements = getSelection().toArray(); - ArrayList<ResourceMapping> providerMappings = new ArrayList<>(); - for (int i = 0; i < elements.length; i++) { - Object object = elements[i]; - Object adapted = getResourceMapping(object); - if (adapted instanceof ResourceMapping) { - ResourceMapping mapping = (ResourceMapping) adapted; - if (providerId == null || isMappedToProvider(mapping, providerId)) { - providerMappings.add(mapping); - } - } - } - return providerMappings.toArray(new ResourceMapping[providerMappings.size()]); - } - - private Object getResourceMapping(Object object) { - if (object instanceof ResourceMapping) - return object; - return Utils.getResourceMapping(object); - } - - private boolean isMappedToProvider(ResourceMapping element, String providerId) { - IProject[] projects = element.getProjects(); - for (int k = 0; k < projects.length; k++) { - IProject project = projects[k]; - RepositoryProvider provider = RepositoryProvider.getProvider(project); - if (provider != null && provider.getID().equals(providerId)) { - return true; - } - } - return false; - } + protected ResourceMapping[] getSelectedResourceMappings(String providerId) { + Object[] elements = getSelection().toArray(); + ArrayList<ResourceMapping> providerMappings = new ArrayList<>(); + for (int i = 0; i < elements.length; i++) { + Object object = elements[i]; + Object adapted = getResourceMapping(object); + if (adapted instanceof ResourceMapping) { + ResourceMapping mapping = (ResourceMapping) adapted; + if (providerId == null || isMappedToProvider(mapping, providerId)) { + providerMappings.add(mapping); + } + } + } + return providerMappings.toArray(new ResourceMapping[providerMappings.size()]); + } + + private Object getResourceMapping(Object object) { + if (object instanceof ResourceMapping) + return object; + return Utils.getResourceMapping(object); + } + + private boolean isMappedToProvider(ResourceMapping element, String providerId) { + IProject[] projects = element.getProjects(); + for (int k = 0; k < projects.length; k++) { + IProject project = projects[k]; + RepositoryProvider provider = RepositoryProvider.getProvider(project); + if (provider != null && provider.getID().equals(providerId)) { + return true; + } + } + return false; + } /** * Convenience method for getting the current shell. @@ -276,7 +276,7 @@ public abstract class TeamAction extends AbstractHandler implements IObjectActio if (shell != null) { return shell; } else if (targetPart != null) { - return targetPart.getSite().getShell(); + return targetPart.getSite().getShell(); } else if (window != null) { return window.getShell(); } else { @@ -413,13 +413,13 @@ public abstract class TeamAction extends AbstractHandler implements IObjectActio * @return IWorkbenchPart */ protected IWorkbenchPart getTargetPart() { - if(targetPart == null) { - IWorkbenchPage page = TeamUIPlugin.getActivePage(); - if (page != null) { - targetPart = page.getActivePart(); - } - } - return targetPart; + if(targetPart == null) { + IWorkbenchPage page = TeamUIPlugin.getActivePage(); + if (page != null) { + targetPart = page.getActivePart(); + } + } + return targetPart; } @@ -478,10 +478,10 @@ public abstract class TeamAction extends AbstractHandler implements IObjectActio targetPartListener = null; } // Don't hold on to anything when we are disposed to prevent memory leaks (see bug 195521) - selection = null; - window = null; - targetPart = null; - shell = null; + selection = null; + window = null; + targetPart = null; + shell = null; } /** @@ -573,24 +573,24 @@ public abstract class TeamAction extends AbstractHandler implements IObjectActio handle(e, TeamUIMessages.TeamAction_errorTitle, null); } - /** - * The <code>TeamAction</code> implementation of this - * <code>IActionDelegate2</code> method does nothing. Subclasses may - * reimplement. - */ - @Override + /** + * The <code>TeamAction</code> implementation of this + * <code>IActionDelegate2</code> method does nothing. Subclasses may + * reimplement. + */ + @Override public void init(IAction action) { - } - - /** - * The <code>TeamAction</code> implementation of this - * <code>IActionDelegate2</code> method redirects to the <code>run</code> - * method. Subclasses may reimplement. - */ - @Override + } + + /** + * The <code>TeamAction</code> implementation of this + * <code>IActionDelegate2</code> method redirects to the <code>run</code> + * method. Subclasses may reimplement. + */ + @Override final public void runWithEvent(IAction action, Event event) { - run(action); - } + run(action); + } @Override public void setEnabled(Object evaluationContext) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/AdditionalMappingsDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/AdditionalMappingsDialog.java index 261d26183..5d0e47d81 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/AdditionalMappingsDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/AdditionalMappingsDialog.java @@ -29,64 +29,64 @@ import org.eclipse.team.internal.ui.TeamUIMessages; public class AdditionalMappingsDialog extends DetailsDialog { - private ResourceMappingHierarchyArea selectedMappingsArea; - private ResourceMappingHierarchyArea allMappingsArea; + private ResourceMappingHierarchyArea selectedMappingsArea; + private ResourceMappingHierarchyArea allMappingsArea; private final ISynchronizationScope scope; private final ISynchronizationContext context; private String previewMessage; protected boolean forcePreview = true; - public AdditionalMappingsDialog(Shell parentShell, String dialogTitle, ISynchronizationScope scope, ISynchronizationContext context) { - super(parentShell, dialogTitle); + public AdditionalMappingsDialog(Shell parentShell, String dialogTitle, ISynchronizationScope scope, ISynchronizationContext context) { + super(parentShell, dialogTitle); this.scope = scope; this.context = context; - } + } @Override protected void createMainDialogArea(Composite parent) { - createWrappingLabel(parent, TeamUIMessages.AdditionalMappingsDialog_0); - createSelectedMappingsArea(parent); - createAllMappingsArea(parent); - createPreviewOptionArea(parent); - } + createWrappingLabel(parent, TeamUIMessages.AdditionalMappingsDialog_0); + createSelectedMappingsArea(parent); + createAllMappingsArea(parent); + createPreviewOptionArea(parent); + } /* - * Create a list that allows the selection of mappings via checkbox - */ - private void createSelectedMappingsArea(Composite parent) { - Composite composite = createComposite(parent); - GridLayout layout = new GridLayout(1, false); - layout.marginHeight = 0; - layout.marginWidth = 0; - composite.setLayout(layout); - selectedMappingsArea = ResourceMappingHierarchyArea.create(scope.asInputScope(), null /* no context */); - selectedMappingsArea.setDescription(TeamUIMessages.AdditionalMappingsDialog_1); - selectedMappingsArea.createArea(composite); - // Create a separator between the two sets of buttons - Label seperator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL); - seperator.setLayoutData(new GridData (GridData.FILL_HORIZONTAL)); - } - - /* - * Create a list that allows the selection of mappings via checkbox - */ - private void createAllMappingsArea(Composite parent) { - Composite composite = createComposite(parent); - GridLayout layout = new GridLayout(1, false); - layout.marginHeight = 0; - layout.marginWidth = 0; - composite.setLayout(layout); - allMappingsArea = ResourceMappingHierarchyArea.create(scope, context); - allMappingsArea.setDescription(TeamUIMessages.AdditionalMappingsDialog_2); - //allMappingsArea.addPropertyChangeListener(this); - allMappingsArea.createArea(composite); - } - - private void createPreviewOptionArea(Composite parent) { - if (previewMessage != null) { - final Button forcePreviewButton = SWTUtils.createCheckBox(parent, previewMessage); - forcePreviewButton.setSelection(forcePreview); - forcePreviewButton.addSelectionListener(new SelectionListener() { + * Create a list that allows the selection of mappings via checkbox + */ + private void createSelectedMappingsArea(Composite parent) { + Composite composite = createComposite(parent); + GridLayout layout = new GridLayout(1, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + composite.setLayout(layout); + selectedMappingsArea = ResourceMappingHierarchyArea.create(scope.asInputScope(), null /* no context */); + selectedMappingsArea.setDescription(TeamUIMessages.AdditionalMappingsDialog_1); + selectedMappingsArea.createArea(composite); + // Create a separator between the two sets of buttons + Label seperator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL); + seperator.setLayoutData(new GridData (GridData.FILL_HORIZONTAL)); + } + + /* + * Create a list that allows the selection of mappings via checkbox + */ + private void createAllMappingsArea(Composite parent) { + Composite composite = createComposite(parent); + GridLayout layout = new GridLayout(1, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + composite.setLayout(layout); + allMappingsArea = ResourceMappingHierarchyArea.create(scope, context); + allMappingsArea.setDescription(TeamUIMessages.AdditionalMappingsDialog_2); + //allMappingsArea.addPropertyChangeListener(this); + allMappingsArea.createArea(composite); + } + + private void createPreviewOptionArea(Composite parent) { + if (previewMessage != null) { + final Button forcePreviewButton = SWTUtils.createCheckBox(parent, previewMessage); + forcePreviewButton.setSelection(forcePreview); + forcePreviewButton.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { // Ignore @@ -96,25 +96,25 @@ public class AdditionalMappingsDialog extends DetailsDialog { forcePreview = forcePreviewButton.getSelection(); } }); - } + } } - @Override + @Override protected Composite createDropDownDialogArea(Composite parent) { - // TODO Auto-generated method stub - return null; - } + // TODO Auto-generated method stub + return null; + } - @Override + @Override protected void updateEnablements() { - // TODO Auto-generated method stub + // TODO Auto-generated method stub - } + } - @Override + @Override protected boolean includeDetailsButton() { - return false; - } + return false; + } public String getPreviewMessage() { return previewMessage; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialog.java index 7915698a3..40a59e754 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialog.java @@ -107,10 +107,10 @@ abstract public class DetailsDialog extends TrayDialog { protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(title); - String helpContextId = getHelpContextId(); - if (helpContextId != null) { - PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, helpContextId); - } + String helpContextId = getHelpContextId(); + if (helpContextId != null) { + PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, helpContextId); + } } @Override @@ -149,13 +149,13 @@ abstract public class DetailsDialog extends TrayDialog { // create composite Composite composite = (Composite)super.createDialogArea(parent); if (!isMainGrabVertical()) { - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); } - String helpContextId = getHelpContextId(); - if (helpContextId != null) { - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContextId); - } + String helpContextId = getHelpContextId(); + if (helpContextId != null) { + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, helpContextId); + } // create image String key = getImageKey(); @@ -194,7 +194,7 @@ abstract public class DetailsDialog extends TrayDialog { right.setLayoutData(new GridData(GridData.FILL_BOTH)); createMainDialogArea(right); } else { - createMainDialogArea(composite); + createMainDialogArea(composite); } if(includeErrorMessage()) { @@ -205,32 +205,32 @@ abstract public class DetailsDialog extends TrayDialog { errorMessageLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED)); } - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); return composite; } - /** - * Return the help context id to be used for the dialog. - * This context Id will be registered by this class. - * By default, this method returns <code>null</code>. - * @return the help context id to be used for the dialog. - */ + /** + * Return the help context id to be used for the dialog. + * This context Id will be registered by this class. + * By default, this method returns <code>null</code>. + * @return the help context id to be used for the dialog. + */ protected String getHelpContextId() { - return null; - } + return null; + } - /** + /** * Return whether the main area should grab excess vertical space. * The default is <code>true</code> but subclasses can override * in cases where the main is more or less fixed but the details * needs to grab. - * @return whether the main area should grab excess vertical space - */ - protected boolean isMainGrabVertical() { - return true; - } + * @return whether the main area should grab excess vertical space + */ + protected boolean isMainGrabVertical() { + return true; + } - /** + /** * Creates the dialog's top composite * * @param parent the parent composite @@ -262,7 +262,7 @@ abstract public class DetailsDialog extends TrayDialog { detailsCreated = true; detailsButton.setText(getDetailsButtonLabelHide()); } - Dialog.applyDialogFont(getContents()); + Dialog.applyDialogFont(getContents()); Point newSize = getContents().computeSize(SWT.DEFAULT, SWT.DEFAULT); getShell().setSize(new Point(windowSize.x, windowSize.y + (newSize.y - oldSize.y))); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialogWithProjects.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialogWithProjects.java index 45c6e8a5e..918a5b9aa 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialogWithProjects.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DetailsDialogWithProjects.java @@ -104,9 +104,9 @@ public class DetailsDialogWithProjects extends DetailsDialog { return includeCancelButton; } - @Override + @Override protected boolean isMainGrabVertical() { - return false; - } + return false; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DialogArea.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DialogArea.java index 27fbd4218..24ec1f7fe 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DialogArea.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/DialogArea.java @@ -197,10 +197,10 @@ public abstract class DialogArea { } protected int convertVerticalDLUsToPixels(int dlus) { - return Dialog.convertVerticalDLUsToPixels(fontMetrics, dlus); + return Dialog.convertVerticalDLUsToPixels(fontMetrics, dlus); } protected int convertHorizontalDLUsToPixels(int dlus) { - return Dialog.convertHorizontalDLUsToPixels(fontMetrics, dlus); + return Dialog.convertHorizontalDLUsToPixels(fontMetrics, dlus); } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/IResourceMappingResourceFilter.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/IResourceMappingResourceFilter.java index 116c0c4d6..32f5c3645 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/IResourceMappingResourceFilter.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/IResourceMappingResourceFilter.java @@ -24,13 +24,13 @@ import org.eclipse.core.runtime.CoreException; */ public interface IResourceMappingResourceFilter { - /** - * Return whether the resource should be included in this filter. - * @param resource the resource - * @param mapping the mapping chiehc containes the resource - * @param traversal the traversal from which the resource was obtained - * @return whether the resource passes the filter - * @throws CoreException - */ - boolean select(IResource resource, ResourceMapping mapping, ResourceTraversal traversal) throws CoreException; + /** + * Return whether the resource should be included in this filter. + * @param resource the resource + * @param mapping the mapping chiehc containes the resource + * @param traversal the traversal from which the resource was obtained + * @return whether the resource passes the filter + * @throws CoreException + */ + boolean select(IResource resource, ResourceMapping mapping, ResourceTraversal traversal) throws CoreException; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/NoChangesDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/NoChangesDialog.java index a06094bcc..38cb7c2cf 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/NoChangesDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/NoChangesDialog.java @@ -27,10 +27,10 @@ import org.eclipse.team.core.mapping.ISynchronizationScope; public class NoChangesDialog extends DetailsDialog { - private String message; - private Label messageLabel; - private Label imageLabel; - private ResourceMappingHierarchyArea selectedMappingsArea; + private String message; + private Label messageLabel; + private Label imageLabel; + private ResourceMappingHierarchyArea selectedMappingsArea; private final ISynchronizationScope scope; private final String description; @@ -56,20 +56,20 @@ public class NoChangesDialog extends DetailsDialog { layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - selectedMappingsArea = ResourceMappingHierarchyArea.create(scope, null /* no context */); - selectedMappingsArea.setDescription(description); - selectedMappingsArea.createArea(composite); - return composite; + selectedMappingsArea = ResourceMappingHierarchyArea.create(scope, null /* no context */); + selectedMappingsArea.setDescription(description); + selectedMappingsArea.createArea(composite); + return composite; } @Override protected void createMainDialogArea(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - composite.setLayout(layout); + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + composite.setLayout(layout); createMessageArea(composite); } @@ -82,60 +82,60 @@ public class NoChangesDialog extends DetailsDialog { * Code copied from IconandMessageDialog */ private Control createMessageArea(Composite composite) { - // create composite - // create image - Image image = getSWTImage(SWT.ICON_INFORMATION); - if (image != null) { - imageLabel = new Label(composite, SWT.NULL); - image.setBackground(imageLabel.getBackground()); - imageLabel.setImage(image); - imageLabel.setLayoutData(new GridData( - GridData.HORIZONTAL_ALIGN_CENTER - | GridData.VERTICAL_ALIGN_BEGINNING)); - } - // create message - if (message != null) { - messageLabel = new Label(composite, SWT.WRAP); - messageLabel.setText(message); - GridData data = new GridData(GridData.GRAB_HORIZONTAL - | GridData.HORIZONTAL_ALIGN_FILL - | GridData.VERTICAL_ALIGN_BEGINNING); - data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); - messageLabel.setLayoutData(data); - } - return composite; - } + // create composite + // create image + Image image = getSWTImage(SWT.ICON_INFORMATION); + if (image != null) { + imageLabel = new Label(composite, SWT.NULL); + image.setBackground(imageLabel.getBackground()); + imageLabel.setImage(image); + imageLabel.setLayoutData(new GridData( + GridData.HORIZONTAL_ALIGN_CENTER + | GridData.VERTICAL_ALIGN_BEGINNING)); + } + // create message + if (message != null) { + messageLabel = new Label(composite, SWT.WRAP); + messageLabel.setText(message); + GridData data = new GridData(GridData.GRAB_HORIZONTAL + | GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); + data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH); + messageLabel.setLayoutData(data); + } + return composite; + } /* * Code copied from IconandMessageDialog */ - private Image getSWTImage(final int imageID) { - Shell shell = getShell(); - final Display display; - if (shell == null) { - shell = getParentShell(); - } - if (shell == null) { - display = Display.getCurrent(); - } else { - display = shell.getDisplay(); - } - - final Image[] image = new Image[1]; - display.syncExec(() -> image[0] = display.getSystemImage(imageID)); - - return image[0]; - } - - @Override + private Image getSWTImage(final int imageID) { + Shell shell = getShell(); + final Display display; + if (shell == null) { + shell = getParentShell(); + } + if (shell == null) { + display = Display.getCurrent(); + } else { + display = shell.getDisplay(); + } + + final Image[] image = new Image[1]; + display.syncExec(() -> image[0] = display.getSystemImage(imageID)); + + return image[0]; + } + + @Override public boolean isHelpAvailable() { - return false; - } + return false; + } - @Override + @Override protected boolean includeCancelButton() { - return false; - } + return false; + } public static void open(Shell shell, String title, String message, String description, ISynchronizationScope scope) { new NoChangesDialog(shell, title, message, description, scope).open(); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/PreferencePageContainerDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/PreferencePageContainerDialog.java index 3dd65964a..008107569 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/PreferencePageContainerDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/PreferencePageContainerDialog.java @@ -88,8 +88,8 @@ public class PreferencePageContainerDialog extends TrayDialog * @see #setMinimumPageSize(Point) */ private Point fMinimumPageSize = new Point(200,200); - private TabFolder tabFolder; - private Map<TabItem, PreferencePage> pageMap = new HashMap<>(); + private TabFolder tabFolder; + private Map<TabItem, PreferencePage> pageMap = new HashMap<>(); /** * Must declare our own images as the JFaceResource images will not be created unless @@ -111,9 +111,9 @@ public class PreferencePageContainerDialog extends TrayDialog @Override protected void okPressed() { for (int i = 0; i < pages.length; i++) { - PreferencePage page = pages[i]; + PreferencePage page = pages[i]; page.performOk(); - } + } handleSave(); @@ -139,9 +139,9 @@ public class PreferencePageContainerDialog extends TrayDialog createDescriptionArea(composite); if (isSinglePage()) { - createSinglePageArea(composite, pages[0]); + createSinglePageArea(composite, pages[0]); } else { - createMultiplePageArea(composite); + createMultiplePageArea(composite); } // Build the separator line @@ -158,63 +158,63 @@ public class PreferencePageContainerDialog extends TrayDialog return composite; } - private void createMultiplePageArea(Composite composite) { + private void createMultiplePageArea(Composite composite) { // create a tab folder for the page tabFolder = new TabFolder(composite, SWT.NONE); tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); for (int i = 0; i < pages.length; i++) { - PreferencePage page = pages[i]; + PreferencePage page = pages[i]; // text decoration options TabItem tabItem = new TabItem(tabFolder, SWT.NONE); tabItem.setText(page.getTitle());// tabItem.setControl(createPageArea(tabFolder, page)); pageMap.put(tabItem, page); - } + } tabFolder.addSelectionListener(new SelectionAdapter() { - @Override + @Override public void widgetSelected(SelectionEvent e) { - updatePageSelection(); - } - }); + updatePageSelection(); + } + }); updatePageSelection(); - } - - protected void updatePageSelection() { - TabItem[] items = tabFolder.getSelection(); - if (items.length == 1) { - currentPage = pageMap.get(items[0]); - updateMessage(); - } - firePageChanged(new PageChangedEvent(this, currentPage)); - } - - private boolean isSinglePage() { - return pages.length == 1; - } - - /* - * Create the page contents for a single preferences page - */ - private void createSinglePageArea(Composite composite, PreferencePage page) { + } + + protected void updatePageSelection() { + TabItem[] items = tabFolder.getSelection(); + if (items.length == 1) { + currentPage = pageMap.get(items[0]); + updateMessage(); + } + firePageChanged(new PageChangedEvent(this, currentPage)); + } + + private boolean isSinglePage() { + return pages.length == 1; + } + + /* + * Create the page contents for a single preferences page + */ + private void createSinglePageArea(Composite composite, PreferencePage page) { createPageArea(composite, page); currentPage = page; updateMessage(); - } + } - private Control createPageArea(Composite composite, PreferencePage page) { - // Build the Page container + private Control createPageArea(Composite composite, PreferencePage page) { + // Build the Page container fPageContainer = createPageContainer(composite); fPageContainer.setLayoutData(new GridData(GridData.FILL_BOTH)); page.setContainer(this); page.createControl(fPageContainer); return fPageContainer; - } + } - private void createDescriptionArea(Composite composite) { - // Build the title area and separator line + private void createDescriptionArea(Composite composite) { + // Build the title area and separator line Composite titleComposite = new Composite(composite, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight = 0; @@ -229,9 +229,9 @@ public class PreferencePageContainerDialog extends TrayDialog Label titleBarSeparator = new Label(titleComposite, SWT.HORIZONTAL | SWT.SEPARATOR); GridData gd = new GridData(GridData.FILL_HORIZONTAL); titleBarSeparator.setLayoutData(gd); - } + } - /** + /** * Creates the dialog's title area. * * @param parent the SWT parent for the title area composite @@ -371,7 +371,7 @@ public class PreferencePageContainerDialog extends TrayDialog @Override public void updateMessage() { - if (currentPage != null) { + if (currentPage != null) { String pageMessage = currentPage.getMessage(); String pageErrorMessage = currentPage.getErrorMessage(); @@ -383,19 +383,19 @@ public class PreferencePageContainerDialog extends TrayDialog // Set the message and error message if (pageMessage == null) { - if (isSinglePage()) { - setMessage(TeamUIMessages.PreferencePageContainerDialog_6); - } else { - //remove mnemonic see bug 75886 - String title = currentPage.getTitle(); - title = title.replaceAll("&", "");//$NON-NLS-1$ //$NON-NLS-2$ - setMessage(title); - } + if (isSinglePage()) { + setMessage(TeamUIMessages.PreferencePageContainerDialog_6); + } else { + //remove mnemonic see bug 75886 + String title = currentPage.getTitle(); + title = title.replaceAll("&", "");//$NON-NLS-1$ //$NON-NLS-2$ + setMessage(title); + } } else { setMessage(pageMessage); } setErrorMessage(pageErrorMessage); - } + } } @Override @@ -406,14 +406,14 @@ public class PreferencePageContainerDialog extends TrayDialog @Override public void updateButtons() { if (fOkButton != null) { - boolean isValid = true; - for (int i = 0; i < pages.length; i++) { - PreferencePage page = pages[i]; - if (!page.isValid()) { - isValid = false; - break; - } - } + boolean isValid = true; + for (int i = 0; i < pages.length; i++) { + PreferencePage page = pages[i]; + if (!page.isValid()) { + isValid = false; + break; + } + } fOkButton.setEnabled(isValid); } } @@ -442,8 +442,8 @@ public class PreferencePageContainerDialog extends TrayDialog */ protected void handleSave() { // Save now in case tbe workbench does not shutdown cleanly - for (int i = 0; i < pages.length; i++) { - PreferencePage page = pages[i]; + for (int i = 0; i < pages.length; i++) { + PreferencePage page = pages[i]; IPreferenceStore store = page.getPreferenceStore(); if (store != null && store.needsSaving() @@ -454,13 +454,13 @@ public class PreferencePageContainerDialog extends TrayDialog Utils.handle(e); } } - } + } } - @Override + @Override public void addPageChangedListener(final IPageChangedListener listener) { - pageChangedListeners.add(listener); + pageChangedListeners.add(listener); } @Override @@ -474,17 +474,17 @@ public class PreferencePageContainerDialog extends TrayDialog } private void firePageChanged(final PageChangedEvent event) { - Object[] listeners = pageChangedListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) { - final IPageChangedListener l = (IPageChangedListener) listeners[i]; - SafeRunnable.run(new SafeRunnable() { - @Override + Object[] listeners = pageChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + final IPageChangedListener l = (IPageChangedListener) listeners[i]; + SafeRunnable.run(new SafeRunnable() { + @Override public void run() { - l.pageChanged(event); - } - }); - } - } + l.pageChanged(event); + } + }); + } + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingHierarchyArea.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingHierarchyArea.java index dc2abf5af..945e99362 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingHierarchyArea.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingHierarchyArea.java @@ -35,14 +35,14 @@ import org.eclipse.ui.navigator.INavigatorContentServiceListener; public class ResourceMappingHierarchyArea extends DialogArea implements INavigatorContentServiceListener { private static final String TEAM_NAVIGATOR_CONTENT = "org.eclipse.team.ui.navigatorViewer"; //$NON-NLS-1$ private String description; - private CommonViewer viewer; + private CommonViewer viewer; private final ISynchronizationScope scope; private final ISynchronizationContext context; - public static ResourceMappingHierarchyArea create(ISynchronizationScope scope, ISynchronizationContext context) { - return new ResourceMappingHierarchyArea(scope, context); - } + public static ResourceMappingHierarchyArea create(ISynchronizationScope scope, ISynchronizationContext context) { + return new ResourceMappingHierarchyArea(scope, context); + } private ResourceMappingHierarchyArea(ISynchronizationScope scope, ISynchronizationContext context) { this.scope = scope; @@ -51,31 +51,31 @@ public class ResourceMappingHierarchyArea extends DialogArea implements INavigat @Override public void createArea(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(1, false); - layout.marginHeight = 0; - layout.marginWidth = 0; - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_BOTH)); + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(1, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + composite.setLayout(layout); + composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - if (description != null) - createWrappingLabel(composite, description, 1); + if (description != null) + createWrappingLabel(composite, description, 1); - viewer = new CommonViewer(TEAM_NAVIGATOR_CONTENT, composite, SWT.BORDER); - viewer.setSorter(new CommonViewerSorter()); - viewer.setSorter(new TeamViewerSorter((CommonViewerSorter)viewer.getSorter())); - viewer.getNavigatorContentService().bindExtensions(TeamUI.getTeamContentProviderManager().getContentProviderIds(scope), true); - viewer.getNavigatorContentService().getActivationService().activateExtensions(TeamUI.getTeamContentProviderManager().getContentProviderIds(scope), true); - GridData data = new GridData(GridData.FILL_BOTH); - data.heightHint = 100; - data.widthHint = 300; - viewer.getControl().setLayoutData(data); - viewer.getNavigatorContentService().addListener(this); - viewer.setInput(getInitialInput()); - viewer.refresh(); - Object[] objects = getRootModelObjects(); - viewer.setSelection(new StructuredSelection(objects), true); - } + viewer = new CommonViewer(TEAM_NAVIGATOR_CONTENT, composite, SWT.BORDER); + viewer.setSorter(new CommonViewerSorter()); + viewer.setSorter(new TeamViewerSorter((CommonViewerSorter)viewer.getSorter())); + viewer.getNavigatorContentService().bindExtensions(TeamUI.getTeamContentProviderManager().getContentProviderIds(scope), true); + viewer.getNavigatorContentService().getActivationService().activateExtensions(TeamUI.getTeamContentProviderManager().getContentProviderIds(scope), true); + GridData data = new GridData(GridData.FILL_BOTH); + data.heightHint = 100; + data.widthHint = 300; + viewer.getControl().setLayoutData(data); + viewer.getNavigatorContentService().addListener(this); + viewer.setInput(getInitialInput()); + viewer.refresh(); + Object[] objects = getRootModelObjects(); + viewer.setSelection(new StructuredSelection(objects), true); + } private Object getInitialInput() { if (context != null) @@ -96,8 +96,8 @@ public class ResourceMappingHierarchyArea extends DialogArea implements INavigat } public void setDescription(String string) { - description = string; - } + description = string; + } @Override public void onLoad(INavigatorContentExtension anExtension) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingResourceDisplayArea.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingResourceDisplayArea.java index 7ae946eae..c3fdbf671 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingResourceDisplayArea.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingResourceDisplayArea.java @@ -49,367 +49,367 @@ import org.eclipse.ui.views.navigator.ResourceComparator; * Dialog area which displays the resources for a resource mapping */ public class ResourceMappingResourceDisplayArea extends DialogArea { - private ResourceMapping mapping; - private ResourceMappingContext context = ResourceMappingContext.LOCAL_CONTEXT; - private TreeViewer viewer; - private Label label; - private IResourceMappingResourceFilter filter; - private Map<ResourceMapping, Map<IResource, List<IResource>>> cachedFiltering = new HashMap<>(); - private String message; - - private static IWorkbenchAdapter getWorkbenchAdapter(IAdaptable o) { - return o.getAdapter(IWorkbenchAdapter.class); - } - - /** - * Return the label that should be used for the given mapping - * as determined using the IWorkbnchAdaptable for the mapping - * or it's model object. - * @param mapping the mappings - * @return it's label - */ - public static String getLabel(ResourceMapping mapping) { - Object o = mapping; - IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter((IAdaptable)o); - if (workbenchAdapter == null) { - Object modelObject = mapping.getModelObject(); - if (modelObject instanceof IAdaptable) { - workbenchAdapter = getWorkbenchAdapter((IAdaptable)modelObject); - o = modelObject; - } - } - if (workbenchAdapter == null) { - return mapping.toString(); - } - return workbenchAdapter.getLabel(o); - } - - public class ResourceMappingElement implements IWorkbenchAdapter, IAdaptable { - private ResourceMapping mapping; - private ResourceMappingContext context; - - public ResourceMappingElement(ResourceMapping mapping, ResourceMappingContext context) { - this.mapping = mapping; - this.context = context; - } - - @Override + private ResourceMapping mapping; + private ResourceMappingContext context = ResourceMappingContext.LOCAL_CONTEXT; + private TreeViewer viewer; + private Label label; + private IResourceMappingResourceFilter filter; + private Map<ResourceMapping, Map<IResource, List<IResource>>> cachedFiltering = new HashMap<>(); + private String message; + + private static IWorkbenchAdapter getWorkbenchAdapter(IAdaptable o) { + return o.getAdapter(IWorkbenchAdapter.class); + } + + /** + * Return the label that should be used for the given mapping + * as determined using the IWorkbnchAdaptable for the mapping + * or it's model object. + * @param mapping the mappings + * @return it's label + */ + public static String getLabel(ResourceMapping mapping) { + Object o = mapping; + IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter((IAdaptable)o); + if (workbenchAdapter == null) { + Object modelObject = mapping.getModelObject(); + if (modelObject instanceof IAdaptable) { + workbenchAdapter = getWorkbenchAdapter((IAdaptable)modelObject); + o = modelObject; + } + } + if (workbenchAdapter == null) { + return mapping.toString(); + } + return workbenchAdapter.getLabel(o); + } + + public class ResourceMappingElement implements IWorkbenchAdapter, IAdaptable { + private ResourceMapping mapping; + private ResourceMappingContext context; + + public ResourceMappingElement(ResourceMapping mapping, ResourceMappingContext context) { + this.mapping = mapping; + this.context = context; + } + + @Override public Object[] getChildren(Object o) { - ResourceTraversal[] traversals = getTraversals(); - List<ResourceTraversalElement> result = new ArrayList<>(); - for (int i = 0; i < traversals.length; i++) { - ResourceTraversal traversal = traversals[i]; - IResource[] resources = traversal.getResources(); - for (int j = 0; j < resources.length; j++) { - IResource resource = resources[j]; - if (isIncludedInFilter(resource, traversal)) - result.add(new ResourceTraversalElement(this, traversal, resource, context)); - } - } - return result.toArray(new Object[result.size()]); - } - - private ResourceTraversal[] getTraversals() { - return ResourceMappingResourceDisplayArea.getTraversals(mapping, context); - } - - @Override + ResourceTraversal[] traversals = getTraversals(); + List<ResourceTraversalElement> result = new ArrayList<>(); + for (int i = 0; i < traversals.length; i++) { + ResourceTraversal traversal = traversals[i]; + IResource[] resources = traversal.getResources(); + for (int j = 0; j < resources.length; j++) { + IResource resource = resources[j]; + if (isIncludedInFilter(resource, traversal)) + result.add(new ResourceTraversalElement(this, traversal, resource, context)); + } + } + return result.toArray(new Object[result.size()]); + } + + private ResourceTraversal[] getTraversals() { + return ResourceMappingResourceDisplayArea.getTraversals(mapping, context); + } + + @Override public ImageDescriptor getImageDescriptor(Object o) { - o = mapping; - IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter((IAdaptable)o); - if (workbenchAdapter == null) { - Object modelObject = mapping.getModelObject(); - if (modelObject instanceof IAdaptable) { - workbenchAdapter = getWorkbenchAdapter((IAdaptable)modelObject); - o = modelObject; - } - } - if (workbenchAdapter == null) { - return null; - } - return workbenchAdapter.getImageDescriptor(o); - } - - @Override + o = mapping; + IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter((IAdaptable)o); + if (workbenchAdapter == null) { + Object modelObject = mapping.getModelObject(); + if (modelObject instanceof IAdaptable) { + workbenchAdapter = getWorkbenchAdapter((IAdaptable)modelObject); + o = modelObject; + } + } + if (workbenchAdapter == null) { + return null; + } + return workbenchAdapter.getImageDescriptor(o); + } + + @Override public String getLabel(Object o) { - return ResourceMappingResourceDisplayArea.getLabel(mapping); - } + return ResourceMappingResourceDisplayArea.getLabel(mapping); + } - @Override + @Override public Object getParent(Object o) { - return null; - } + return null; + } @Override - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public <T> T getAdapter(Class<T> adapter) { - if (adapter == IWorkbenchAdapter.class) - return (T) this; - return null; - } - } - - /** - * The model element for resources that are obtained from a traversal. - */ - public class ResourceTraversalElement implements IWorkbenchAdapter, IAdaptable { - private ResourceTraversal traversal; - private ResourceMappingContext context; - private IResource resource; - private Object parent; - - public ResourceTraversalElement(Object parent, ResourceTraversal traversal, IResource resource, ResourceMappingContext context) { - this.parent = parent; - this.traversal = traversal; - this.resource = resource; - this.context = context; - } - - @Override + if (adapter == IWorkbenchAdapter.class) + return (T) this; + return null; + } + } + + /** + * The model element for resources that are obtained from a traversal. + */ + public class ResourceTraversalElement implements IWorkbenchAdapter, IAdaptable { + private ResourceTraversal traversal; + private ResourceMappingContext context; + private IResource resource; + private Object parent; + + public ResourceTraversalElement(Object parent, ResourceTraversal traversal, IResource resource, ResourceMappingContext context) { + this.parent = parent; + this.traversal = traversal; + this.resource = resource; + this.context = context; + } + + @Override public Object[] getChildren(Object o) { - if (traversal.getDepth() == IResource.DEPTH_INFINITE) { - return getChildren(true); - } else if (traversal.getDepth() == IResource.DEPTH_ONE && isTraversalRoot(resource)) { - return getChildren(false); - } - return new Object[0]; - } - - private Object[] getChildren(boolean includeFolders) { - try { - if (resource.getType() != IResource.FILE) { - IResource[] members = members(((IContainer)resource)); - List<ResourceTraversalElement> result = new ArrayList<ResourceTraversalElement>(); - for (int i = 0; i < members.length; i++) { - IResource child = members[i]; - if ((includeFolders || child.getType() == IResource.FILE) - && isIncludedInFilter(child, traversal)) - result.add(new ResourceTraversalElement(this, traversal, child, context)); - } - return result.toArray(new Object[result.size()]); - } - } catch (CoreException e) { - TeamUIPlugin.log(IStatus.ERROR, "An error occurred fetching the members of " + resource.getFullPath(), e); //$NON-NLS-1$ - } - return new Object[0]; - } - - private IResource[] members(IContainer container) throws CoreException { - if (context instanceof RemoteResourceMappingContext) { - RemoteResourceMappingContext remoteContext = (RemoteResourceMappingContext) context; - return ResourceMappingResourceDisplayArea.members(container, remoteContext); - } - return container.members(); - } - - @Override + if (traversal.getDepth() == IResource.DEPTH_INFINITE) { + return getChildren(true); + } else if (traversal.getDepth() == IResource.DEPTH_ONE && isTraversalRoot(resource)) { + return getChildren(false); + } + return new Object[0]; + } + + private Object[] getChildren(boolean includeFolders) { + try { + if (resource.getType() != IResource.FILE) { + IResource[] members = members(((IContainer)resource)); + List<ResourceTraversalElement> result = new ArrayList<ResourceTraversalElement>(); + for (int i = 0; i < members.length; i++) { + IResource child = members[i]; + if ((includeFolders || child.getType() == IResource.FILE) + && isIncludedInFilter(child, traversal)) + result.add(new ResourceTraversalElement(this, traversal, child, context)); + } + return result.toArray(new Object[result.size()]); + } + } catch (CoreException e) { + TeamUIPlugin.log(IStatus.ERROR, "An error occurred fetching the members of " + resource.getFullPath(), e); //$NON-NLS-1$ + } + return new Object[0]; + } + + private IResource[] members(IContainer container) throws CoreException { + if (context instanceof RemoteResourceMappingContext) { + RemoteResourceMappingContext remoteContext = (RemoteResourceMappingContext) context; + return ResourceMappingResourceDisplayArea.members(container, remoteContext); + } + return container.members(); + } + + @Override public ImageDescriptor getImageDescriptor(Object object) { - IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter(resource); - if (workbenchAdapter == null) - return null; - return workbenchAdapter.getImageDescriptor(resource); - } + IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter(resource); + if (workbenchAdapter == null) + return null; + return workbenchAdapter.getImageDescriptor(resource); + } - @Override + @Override public String getLabel(Object o) { - if (resource.getType() != IResource.PROJECT && isTraversalRoot(resource)) - return resource.getFullPath().toString(); - IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter(resource); - if (workbenchAdapter == null) - return resource.getName(); - return workbenchAdapter.getLabel(resource); - } - - private boolean isTraversalRoot(IResource resource) { - return ResourceMappingResourceDisplayArea.isTraversalRoot(traversal, resource); - } - - @Override + if (resource.getType() != IResource.PROJECT && isTraversalRoot(resource)) + return resource.getFullPath().toString(); + IWorkbenchAdapter workbenchAdapter = getWorkbenchAdapter(resource); + if (workbenchAdapter == null) + return resource.getName(); + return workbenchAdapter.getLabel(resource); + } + + private boolean isTraversalRoot(IResource resource) { + return ResourceMappingResourceDisplayArea.isTraversalRoot(traversal, resource); + } + + @Override public Object getParent(Object o) { - return parent; - } + return parent; + } @Override - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public <T> T getAdapter(Class<T> adapter) { - if (adapter == IWorkbenchAdapter.class) - return (T) this; - return null; - } - - public IResource getResource() { - return resource; - } - } - - /** - * Create a dialog area that will display the resources contained in the - * given mapping. - * - * @param mapping the mapping - * @param filter the filter - * @param string the message to display - */ - public ResourceMappingResourceDisplayArea(ResourceMapping mapping, String string, IResourceMappingResourceFilter filter) { - this.mapping = mapping; - this.filter = filter; - this.message = string; - } - - @Override + if (adapter == IWorkbenchAdapter.class) + return (T) this; + return null; + } + + public IResource getResource() { + return resource; + } + } + + /** + * Create a dialog area that will display the resources contained in the + * given mapping. + * + * @param mapping the mapping + * @param filter the filter + * @param string the message to display + */ + public ResourceMappingResourceDisplayArea(ResourceMapping mapping, String string, IResourceMappingResourceFilter filter) { + this.mapping = mapping; + this.filter = filter; + this.message = string; + } + + @Override public void createArea(Composite parent) { - Composite composite = createComposite(parent, 1, true); - - label = createWrappingLabel(composite, message, 1); - viewer = new TreeViewer(composite); - GridData gridData = new GridData(GridData.FILL_BOTH); - gridData.heightHint = 100; - viewer.getControl().setLayoutData(gridData); - viewer.setContentProvider(new WorkbenchContentProvider()); - viewer.setLabelProvider(new WorkbenchLabelProvider()); - viewer.setComparator(new ResourceComparator(ResourceComparator.NAME) { - @Override + Composite composite = createComposite(parent, 1, true); + + label = createWrappingLabel(composite, message, 1); + viewer = new TreeViewer(composite); + GridData gridData = new GridData(GridData.FILL_BOTH); + gridData.heightHint = 100; + viewer.getControl().setLayoutData(gridData); + viewer.setContentProvider(new WorkbenchContentProvider()); + viewer.setLabelProvider(new WorkbenchLabelProvider()); + viewer.setComparator(new ResourceComparator(ResourceComparator.NAME) { + @Override public int compare(Viewer viewer, Object o1, Object o2) { - if (o1 instanceof ResourceTraversalElement && o2 instanceof ResourceTraversalElement) { - ResourceTraversalElement e1 = (ResourceTraversalElement) o1; - ResourceTraversalElement e2 = (ResourceTraversalElement) o2; - return super.compare(viewer, e1.getResource(), e2.getResource()); - } - return super.compare(viewer, o1, o2); - } - }); - setInput(message); - Dialog.applyDialogFont(parent); - } - - private void setInput(String labelText) { - if (viewer != null) { - Object o = null; - if (mapping != null) - o = new ResourceMappingElement(mapping, context); - viewer.setInput(o); - } - if (label != null) { - this.message = labelText; - label.setText(labelText); - } - } - - public void setMapping(ResourceMapping mapping, String labelText) { - this.mapping = mapping; - setInput(labelText); - } - - private boolean isIncludedInFilter(IResource resource, ResourceTraversal traversal) { - if (filter == null) - return true; - Map<IResource, List<IResource>> mappingResources = cachedFiltering.get(mapping); - if (mappingResources == null) { - mappingResources = buildFilteredResourceMap(mapping, context); - cachedFiltering.put(mapping, mappingResources); - } - return mappingResources.containsKey(resource); - } - - private Map<IResource, List<IResource>> buildFilteredResourceMap(final ResourceMapping mapping, final ResourceMappingContext context) { - final Map<IResource, List<IResource>> result = new HashMap<>(); - try { - PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { - @Override + if (o1 instanceof ResourceTraversalElement && o2 instanceof ResourceTraversalElement) { + ResourceTraversalElement e1 = (ResourceTraversalElement) o1; + ResourceTraversalElement e2 = (ResourceTraversalElement) o2; + return super.compare(viewer, e1.getResource(), e2.getResource()); + } + return super.compare(viewer, o1, o2); + } + }); + setInput(message); + Dialog.applyDialogFont(parent); + } + + private void setInput(String labelText) { + if (viewer != null) { + Object o = null; + if (mapping != null) + o = new ResourceMappingElement(mapping, context); + viewer.setInput(o); + } + if (label != null) { + this.message = labelText; + label.setText(labelText); + } + } + + public void setMapping(ResourceMapping mapping, String labelText) { + this.mapping = mapping; + setInput(labelText); + } + + private boolean isIncludedInFilter(IResource resource, ResourceTraversal traversal) { + if (filter == null) + return true; + Map<IResource, List<IResource>> mappingResources = cachedFiltering.get(mapping); + if (mappingResources == null) { + mappingResources = buildFilteredResourceMap(mapping, context); + cachedFiltering.put(mapping, mappingResources); + } + return mappingResources.containsKey(resource); + } + + private Map<IResource, List<IResource>> buildFilteredResourceMap(final ResourceMapping mapping, final ResourceMappingContext context) { + final Map<IResource, List<IResource>> result = new HashMap<>(); + try { + PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { + @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - try { - monitor.beginTask(null, IProgressMonitor.UNKNOWN); - ResourceTraversal[] traversals = mapping.getTraversals(context, Policy.subMonitorFor(monitor, IProgressMonitor.UNKNOWN)); - for (int i = 0; i < traversals.length; i++) { - ResourceTraversal traversal = traversals[i]; - buildFilteredResourceMap(mapping, traversal, Policy.subMonitorFor(monitor, IProgressMonitor.UNKNOWN), result); - } - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - - private void buildFilteredResourceMap(final ResourceMapping mapping, - final ResourceTraversal traversal, IProgressMonitor monitor, - final Map<IResource, List<IResource>> result) throws CoreException { - traversal.accept(resource -> { - if (filter.select(resource, mapping, traversal)) { - // Add the resource to the result - result.put(resource, new ArrayList<>()); - // Make sure that there are parent folders for the resource up to the traversal root - IResource child = resource; - while (!isTraversalRoot(traversal, child)) { - IContainer parent = child.getParent(); - List<IResource> children = result.get(parent); - if (children == null) { - children = new ArrayList<>(); - result.put(parent, children); - } - children.add(child); - child = parent; - } - } - return true; + try { + monitor.beginTask(null, IProgressMonitor.UNKNOWN); + ResourceTraversal[] traversals = mapping.getTraversals(context, Policy.subMonitorFor(monitor, IProgressMonitor.UNKNOWN)); + for (int i = 0; i < traversals.length; i++) { + ResourceTraversal traversal = traversals[i]; + buildFilteredResourceMap(mapping, traversal, Policy.subMonitorFor(monitor, IProgressMonitor.UNKNOWN), result); + } + } catch (CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + + private void buildFilteredResourceMap(final ResourceMapping mapping, + final ResourceTraversal traversal, IProgressMonitor monitor, + final Map<IResource, List<IResource>> result) throws CoreException { + traversal.accept(resource -> { + if (filter.select(resource, mapping, traversal)) { + // Add the resource to the result + result.put(resource, new ArrayList<>()); + // Make sure that there are parent folders for the resource up to the traversal root + IResource child = resource; + while (!isTraversalRoot(traversal, child)) { + IContainer parent = child.getParent(); + List<IResource> children = result.get(parent); + if (children == null) { + children = new ArrayList<>(); + result.put(parent, children); + } + children.add(child); + child = parent; + } + } + return true; }); - } - }); - } catch (InvocationTargetException e) { - TeamUIPlugin.log(IStatus.ERROR, "An error occurred while filtering " + getLabel(mapping), e); //$NON-NLS-1$ - } catch (InterruptedException e) { - // Ignore - } - return result; - } - - /* private */ static ResourceTraversal[] getTraversals(final ResourceMapping mapping, final ResourceMappingContext context) { - final List<ResourceTraversal[]> traversals = new ArrayList<>(); - try { - PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { - try { - traversals.add(mapping.getTraversals(context, monitor)); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } + } + }); + } catch (InvocationTargetException e) { + TeamUIPlugin.log(IStatus.ERROR, "An error occurred while filtering " + getLabel(mapping), e); //$NON-NLS-1$ + } catch (InterruptedException e) { + // Ignore + } + return result; + } + + /* private */ static ResourceTraversal[] getTraversals(final ResourceMapping mapping, final ResourceMappingContext context) { + final List<ResourceTraversal[]> traversals = new ArrayList<>(); + try { + PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { + try { + traversals.add(mapping.getTraversals(context, monitor)); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } }); - return traversals.get(0); - } catch (InvocationTargetException e) { - TeamUIPlugin.log(IStatus.ERROR, "An error occurred while traversing " + getLabel(mapping), e); //$NON-NLS-1$ - } catch (InterruptedException e) { - // Ignore - } - return new ResourceTraversal[0]; - } - - /* private */ static IResource[] members(final IContainer container, final RemoteResourceMappingContext context) { - final List<IResource[]> members = new ArrayList<>(); - try { - PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { - try { - members.add(context.fetchMembers(container, monitor)); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } + return traversals.get(0); + } catch (InvocationTargetException e) { + TeamUIPlugin.log(IStatus.ERROR, "An error occurred while traversing " + getLabel(mapping), e); //$NON-NLS-1$ + } catch (InterruptedException e) { + // Ignore + } + return new ResourceTraversal[0]; + } + + /* private */ static IResource[] members(final IContainer container, final RemoteResourceMappingContext context) { + final List<IResource[]> members = new ArrayList<>(); + try { + PlatformUI.getWorkbench().getProgressService().busyCursorWhile(monitor -> { + try { + members.add(context.fetchMembers(container, monitor)); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } }); - return members.get(0); - } catch (InvocationTargetException e) { - TeamUIPlugin.log(IStatus.ERROR, "An error occurred while fetching the members of" + container.getFullPath(), e); //$NON-NLS-1$ - } catch (InterruptedException e) { - // Ignore - } - return new IResource[0]; - } - - /* private */ static boolean isTraversalRoot(ResourceTraversal traversal, IResource resource) { - IResource[] resources = traversal.getResources(); - for (int i = 0; i < resources.length; i++) { - IResource root = resources[i]; - if (root.equals(resource)) { - return true; - } - } - return false; - } + return members.get(0); + } catch (InvocationTargetException e) { + TeamUIPlugin.log(IStatus.ERROR, "An error occurred while fetching the members of" + container.getFullPath(), e); //$NON-NLS-1$ + } catch (InterruptedException e) { + // Ignore + } + return new IResource[0]; + } + + /* private */ static boolean isTraversalRoot(ResourceTraversal traversal, IResource resource) { + IResource[] resources = traversal.getResources(); + for (int i = 0; i < resources.length; i++) { + IResource root = resources[i]; + if (root.equals(resource)) { + return true; + } + } + return false; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingSelectionArea.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingSelectionArea.java index 9085ea2c2..7b0f31291 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingSelectionArea.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/dialogs/ResourceMappingSelectionArea.java @@ -37,64 +37,64 @@ import org.eclipse.ui.model.BaseWorkbenchContentProvider; public class ResourceMappingSelectionArea extends DialogArea { /** - * Property constant used to indicate that the selected mapping has changed. - * The object associated with the property is a <code>ResourceMapping</code>. - */ - public static final String SELECTED_MAPPING = "SelectedMapping"; //$NON-NLS-1$ - - /** - * Property constant used to indicate that the checked mappings have changed. - * The object associated with the property is a <code>ResourceMapping[]</code> - * (i.e. an array of mappings). - */ - public static final String CHECKED_MAPPINGS = "CheckedMappings"; //$NON-NLS-1$ - - private ResourceMapping[] mappings; - private TableViewer viewer; - private ResourceMapping[] checkedMappings; - private ResourceMapping selectedMapping; - private String description; + * Property constant used to indicate that the selected mapping has changed. + * The object associated with the property is a <code>ResourceMapping</code>. + */ + public static final String SELECTED_MAPPING = "SelectedMapping"; //$NON-NLS-1$ + + /** + * Property constant used to indicate that the checked mappings have changed. + * The object associated with the property is a <code>ResourceMapping[]</code> + * (i.e. an array of mappings). + */ + public static final String CHECKED_MAPPINGS = "CheckedMappings"; //$NON-NLS-1$ + + private ResourceMapping[] mappings; + private TableViewer viewer; + private ResourceMapping[] checkedMappings; + private ResourceMapping selectedMapping; + private String description; private boolean supportsChecking; private boolean supportsSelection; - public ResourceMappingSelectionArea(ResourceMapping[] mappings, boolean supportSelection, boolean supportChecking) { - this.mappings = mappings; - this.supportsChecking = supportChecking; - this.supportsSelection = supportSelection; - } + public ResourceMappingSelectionArea(ResourceMapping[] mappings, boolean supportSelection, boolean supportChecking) { + this.mappings = mappings; + this.supportsChecking = supportChecking; + this.supportsSelection = supportSelection; + } - @Override + @Override public void createArea(Composite parent) { - Composite composite = createComposite(parent, 1, true); - GridLayout layout = new GridLayout(1, false); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.verticalSpacing = 0; - layout.horizontalSpacing = 0; - composite.setLayout(layout); - - if (description != null) - createWrappingLabel(composite, description, 1); - - createViewer(composite); - GridData data = new GridData(GridData.FILL_BOTH); - data.heightHint = 100; - data.widthHint = 300; - viewer.getControl().setLayoutData(data); - viewer.setContentProvider(new BaseWorkbenchContentProvider()); - viewer.setLabelProvider(new ResourceMappingLabelProvider()); - viewer.setInput(new AdaptableList(mappings)); - if (isSupportsSelection()) { - viewer.addSelectionChangedListener(event -> { - ResourceMapping oldSelection = selectedMapping; - selectedMapping = internalGetSelectedMapping(); - if (oldSelection != selectedMapping) - firePropertyChangeChange(SELECTED_MAPPING, oldSelection, selectedMapping); + Composite composite = createComposite(parent, 1, true); + GridLayout layout = new GridLayout(1, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.verticalSpacing = 0; + layout.horizontalSpacing = 0; + composite.setLayout(layout); + + if (description != null) + createWrappingLabel(composite, description, 1); + + createViewer(composite); + GridData data = new GridData(GridData.FILL_BOTH); + data.heightHint = 100; + data.widthHint = 300; + viewer.getControl().setLayoutData(data); + viewer.setContentProvider(new BaseWorkbenchContentProvider()); + viewer.setLabelProvider(new ResourceMappingLabelProvider()); + viewer.setInput(new AdaptableList(mappings)); + if (isSupportsSelection()) { + viewer.addSelectionChangedListener(event -> { + ResourceMapping oldSelection = selectedMapping; + selectedMapping = internalGetSelectedMapping(); + if (oldSelection != selectedMapping) + firePropertyChangeChange(SELECTED_MAPPING, oldSelection, selectedMapping); }); - } - if (isSupportsChecking()) - initializeCheckboxViewer(composite); - } + } + if (isSupportsChecking()) + initializeCheckboxViewer(composite); + } private void initializeCheckboxViewer(Composite composite) { final CheckboxTableViewer checkboxViewer = getCheckboxTableViewer(); @@ -105,29 +105,29 @@ public class ResourceMappingSelectionArea extends DialogArea { firePropertyChangeChange(CHECKED_MAPPINGS, oldMappings, checkedMappings); }); checkboxViewer.setCheckedElements(mappings); - checkedMappings = mappings; + checkedMappings = mappings; - Composite buttons = createEmbeddedButtonComposite(composite); + Composite buttons = createEmbeddedButtonComposite(composite); - Button selectAll = new Button(buttons, SWT.PUSH); - selectAll.setText(TeamUIMessages.ResourceMappingSelectionArea_0); - selectAll.setLayoutData(new GridData(GridData.FILL_BOTH)); - selectAll.addSelectionListener(new SelectionAdapter() { - @Override + Button selectAll = new Button(buttons, SWT.PUSH); + selectAll.setText(TeamUIMessages.ResourceMappingSelectionArea_0); + selectAll.setLayoutData(new GridData(GridData.FILL_BOTH)); + selectAll.addSelectionListener(new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - checkboxViewer.setAllChecked(true); - } - }); - - Button deselectAll = new Button(buttons, SWT.PUSH); - deselectAll.setText(TeamUIMessages.ResourceMappingSelectionArea_1); - deselectAll.setLayoutData(new GridData(GridData.FILL_BOTH)); - deselectAll.addSelectionListener(new SelectionAdapter() { - @Override + checkboxViewer.setAllChecked(true); + } + }); + + Button deselectAll = new Button(buttons, SWT.PUSH); + deselectAll.setText(TeamUIMessages.ResourceMappingSelectionArea_1); + deselectAll.setLayoutData(new GridData(GridData.FILL_BOTH)); + deselectAll.addSelectionListener(new SelectionAdapter() { + @Override public void widgetSelected(SelectionEvent e) { - checkboxViewer.setAllChecked(false); - } - }); + checkboxViewer.setAllChecked(false); + } + }); } private void createViewer(Composite composite) { @@ -144,54 +144,54 @@ public class ResourceMappingSelectionArea extends DialogArea { return style; } - /* private */ ResourceMapping[] internalGetCheckedMappings() { - Object[] checked = getCheckboxTableViewer().getCheckedElements(); - ResourceMapping[] mappings = new ResourceMapping[checked.length]; - for (int i = 0; i < checked.length; i++) { - Object object = checked[i]; - mappings[i] = (ResourceMapping)object; - } - return mappings; - } - - private Composite createEmbeddedButtonComposite(Composite composite) { - GridData data; - Composite buttons = new Composite(composite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; // this is incremented by createButton - layout.makeColumnsEqualWidth = true; - layout.marginWidth = 0; - buttons.setLayout(layout); - data = new GridData(GridData.HORIZONTAL_ALIGN_END - | GridData.VERTICAL_ALIGN_CENTER); - buttons.setLayoutData(data); - return buttons; - } - - /* private */ ResourceMapping internalGetSelectedMapping() { - ISelection selection = viewer.getSelection(); - if (selection instanceof IStructuredSelection) { - IStructuredSelection ss = (IStructuredSelection) selection; - Object firstElement = ss.getFirstElement(); - if (firstElement instanceof ResourceMapping) - return (ResourceMapping)firstElement; - } - return null; - } - - public void setDescription(String description) { - this.description = description; - } - public ResourceMapping[] getCheckedMappings() { - return checkedMappings; - } - public ResourceMapping getSelectedMapping() { - return selectedMapping; - } - - private CheckboxTableViewer getCheckboxTableViewer() { - return (CheckboxTableViewer)viewer; - } + /* private */ ResourceMapping[] internalGetCheckedMappings() { + Object[] checked = getCheckboxTableViewer().getCheckedElements(); + ResourceMapping[] mappings = new ResourceMapping[checked.length]; + for (int i = 0; i < checked.length; i++) { + Object object = checked[i]; + mappings[i] = (ResourceMapping)object; + } + return mappings; + } + + private Composite createEmbeddedButtonComposite(Composite composite) { + GridData data; + Composite buttons = new Composite(composite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; // this is incremented by createButton + layout.makeColumnsEqualWidth = true; + layout.marginWidth = 0; + buttons.setLayout(layout); + data = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.VERTICAL_ALIGN_CENTER); + buttons.setLayoutData(data); + return buttons; + } + + /* private */ ResourceMapping internalGetSelectedMapping() { + ISelection selection = viewer.getSelection(); + if (selection instanceof IStructuredSelection) { + IStructuredSelection ss = (IStructuredSelection) selection; + Object firstElement = ss.getFirstElement(); + if (firstElement instanceof ResourceMapping) + return (ResourceMapping)firstElement; + } + return null; + } + + public void setDescription(String description) { + this.description = description; + } + public ResourceMapping[] getCheckedMappings() { + return checkedMappings; + } + public ResourceMapping getSelectedMapping() { + return selectedMapping; + } + + private CheckboxTableViewer getCheckboxTableViewer() { + return (CheckboxTableViewer)viewer; + } public boolean isSupportsChecking() { return supportsChecking; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryTableProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryTableProvider.java index 6cb46704e..a1aeb09b2 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryTableProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryTableProvider.java @@ -310,7 +310,7 @@ public class GenericHistoryTableProvider { */ private SelectionListener getColumnListener(final TableViewer tableViewer) { /** - * This class handles selections of the column headers. + * This class handles selections of the column headers. * Selection of the column header will cause resorting * of the shown tasks using that column's sorter. * Repeated selection of the header will toggle diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/HistoryPageSourceWorkbenchPart.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/HistoryPageSourceWorkbenchPart.java index b88b37e4c..a0e63578e 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/HistoryPageSourceWorkbenchPart.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/HistoryPageSourceWorkbenchPart.java @@ -31,7 +31,7 @@ public class HistoryPageSourceWorkbenchPart implements IWorkbenchPart { @Override public boolean equals(Object obj) { return (obj instanceof HistoryPageSourceWorkbenchPart) && - source.equals(((HistoryPageSourceWorkbenchPart)obj).getSource()); + source.equals(((HistoryPageSourceWorkbenchPart)obj).getSource()); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java index a0fe007ab..00f2c71c8 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/LocalHistoryPage.java @@ -272,7 +272,7 @@ public class LocalHistoryPage extends HistoryPage implements IHistoryCompareAdap IResourceDelta root = event.getDelta(); if (file == null) - return; + return; IResourceDelta resourceDelta = root.findMember(file.getFullPath()); if (resourceDelta != null){ @@ -424,7 +424,7 @@ public class LocalHistoryPage extends HistoryPage implements IHistoryCompareAdap } //TODO: Doc help - //PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, ); + //PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, ); // Click Compare action compareAction = createCompareAction(); @@ -633,11 +633,11 @@ public class LocalHistoryPage extends HistoryPage implements IHistoryCompareAdap return null; } - @Override + @Override public void dispose() { - shutdown = true; + shutdown = true; - if (resourceListener != null){ + if (resourceListener != null){ ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener); resourceListener = null; } @@ -658,7 +658,7 @@ public class LocalHistoryPage extends HistoryPage implements IHistoryCompareAdap currentFileRevision = new LocalFileRevision(file); return currentFileRevision; - } + } private Action getContextMenuAction(String title, final boolean needsProgressDialog, final IWorkspaceRunnable action) { return new Action(title) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java index 63e647d1c..661484491 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java @@ -160,34 +160,34 @@ public class CommonViewerAdvisor extends AbstractTreeViewerAdvisor implements IN getNavigatorContentService().getDnDService().bindDragAssistant(new ResourceDragAdapterAssistant()); super.initDragAndDrop(); } - /** - * Gets the expanded elements that are visible to the user. An expanded - * element is only visible if the parent is expanded. - * - * @return the visible expanded elements - * @since 2.0 - */ - public TreePath[] getVisibleExpandedPaths() { - ArrayList<TreePath> v = new ArrayList<>(); - internalCollectVisibleExpanded(v, getControl()); - return v.toArray(new TreePath[v.size()]); - } - - private void internalCollectVisibleExpanded(ArrayList<TreePath> result, Widget widget) { - Item[] items = getChildren(widget); - for (int i = 0; i < items.length; i++) { - Item item = items[i]; - if (getExpanded(item)) { - TreePath path = getTreePathFromItem(item); - if (path != null) { + /** + * Gets the expanded elements that are visible to the user. An expanded + * element is only visible if the parent is expanded. + * + * @return the visible expanded elements + * @since 2.0 + */ + public TreePath[] getVisibleExpandedPaths() { + ArrayList<TreePath> v = new ArrayList<>(); + internalCollectVisibleExpanded(v, getControl()); + return v.toArray(new TreePath[v.size()]); + } + + private void internalCollectVisibleExpanded(ArrayList<TreePath> result, Widget widget) { + Item[] items = getChildren(widget); + for (int i = 0; i < items.length; i++) { + Item item = items[i]; + if (getExpanded(item)) { + TreePath path = getTreePathFromItem(item); + if (path != null) { result.add(path); - } - //Only recurse if it is expanded - if - //not then the children aren't visible - internalCollectVisibleExpanded(result, item); - } - } - } + } + //Only recurse if it is expanded - if + //not then the children aren't visible + internalCollectVisibleExpanded(result, item); + } + } + } } /** @@ -335,8 +335,8 @@ public class CommonViewerAdvisor extends AbstractTreeViewerAdvisor implements IN configuration.addPropertyChangeListener(this); GridData data = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(data); - viewer.getNavigatorContentService().addListener(this); - initializeViewer(viewer); + viewer.getNavigatorContentService().addListener(this); + initializeViewer(viewer); IBaseLabelProvider provider = viewer.getLabelProvider(); if (provider instanceof DecoratingLabelProvider) { DecoratingLabelProvider dlp = (DecoratingLabelProvider) provider; @@ -407,8 +407,8 @@ public class CommonViewerAdvisor extends AbstractTreeViewerAdvisor implements IN @Override public void setInitialInput() { CommonViewer viewer = (CommonViewer)getViewer(); - viewer.setInput(getInitialInput()); - viewer.expandToLevel(2); + viewer.setInput(getInitialInput()); + viewer.expandToLevel(2); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java index 0db2beed3..1b242233f 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/DiffTreeChangesSection.java @@ -499,9 +499,9 @@ public class DiffTreeChangesSection extends ForwardingChangesSection implements IModelProviderDescriptor oldDesc = ModelProvider.getModelProviderDescriptor(oldId); String message; String modeToString = Utils.modeToString(getConfiguration().getMode()); - message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_0, new String[] { - provider.getDescriptor().getLabel(), - modeToString }); + message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_0, new String[] { + provider.getDescriptor().getLabel(), + modeToString }); message = NLS.bind(TeamUIMessages.DiffTreeChangesSection_1, new String[] { modeToString, oldDesc.getLabel(), message }); createDescriptionLabel(composite, message); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/FuzzFactorDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/FuzzFactorDialog.java index ee5c920d6..8859663e0 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/FuzzFactorDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/FuzzFactorDialog.java @@ -83,9 +83,9 @@ public class FuzzFactorDialog extends Dialog { Button guessButton = new Button(composite, SWT.NONE); guessButton.setText(TeamUIMessages.FuzzFactorDialog_guess); data = new GridData(); - int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); - Point minSize = guessButton.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); - data.widthHint = Math.max(widthHint, minSize.x); + int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); + Point minSize = guessButton.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + data.widthHint = Math.max(widthHint, minSize.x); guessButton.setLayoutData(data); guessButton.addSelectionListener(new SelectionAdapter() { @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/MergeAllOperation.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/MergeAllOperation.java index b681f06b6..2d2400afc 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/MergeAllOperation.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/MergeAllOperation.java @@ -82,16 +82,16 @@ public final class MergeAllOperation extends SynchronizationOperation { return (IMergeContext)getContext(); } private boolean promptToContinue(final IStatus status) { - final boolean[] result = new boolean[] { false }; - Runnable runnable = () -> { + final boolean[] result = new boolean[] { false }; + Runnable runnable = () -> { ErrorDialog dialog = new ErrorDialog(getShell(), TeamUIMessages.ModelMergeOperation_0, TeamUIMessages.ModelMergeOperation_1, status, IStatus.ERROR | IStatus.WARNING | IStatus.INFO) { @Override protected void createButtonsForButtonBar(Composite parent) { - createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, - false); + createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, + false); createButton(parent, IDialogConstants.NO_ID, IDialogConstants.NO_LABEL, true); - createDetailsButton(parent); + createDetailsButton(parent); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelCompareEditorInput.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelCompareEditorInput.java index 0be30321e..c857fb7db 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelCompareEditorInput.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelCompareEditorInput.java @@ -102,15 +102,15 @@ public class ModelCompareEditorInput extends SaveableCompareEditorInput implemen super.handleDispose(); participant.getContext().getCache().removeCacheListener(contextListener); getCompareConfiguration().removePropertyChangeListener(this); - ICompareNavigator navigator = (ICompareNavigator)synchronizeConfiguration.getProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR); - if (navigator != null && navigator == super.getNavigator()) { - synchronizeConfiguration.setProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR, new CompareNavigator() { + ICompareNavigator navigator = (ICompareNavigator)synchronizeConfiguration.getProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR); + if (navigator != null && navigator == super.getNavigator()) { + synchronizeConfiguration.setProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR, new CompareNavigator() { @Override protected INavigatable[] getNavigatables() { return new INavigatable[0]; } }); - } + } } @Override @@ -127,8 +127,8 @@ public class ModelCompareEditorInput extends SaveableCompareEditorInput implemen @Override protected ICompareInput prepareCompareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - monitor.beginTask(TeamUIMessages.SyncInfoCompareInput_3, 100); - monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); + monitor.beginTask(TeamUIMessages.SyncInfoCompareInput_3, 100); + monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); getCompareConfiguration().setLeftEditable(isLeftEditable(input)); getCompareConfiguration().setRightEditable(false); try { @@ -139,8 +139,8 @@ public class ModelCompareEditorInput extends SaveableCompareEditorInput implemen } catch (CoreException e) { throw new InvocationTargetException(e); } finally { - monitor.done(); - } + monitor.done(); + } return input; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelEnablementPreferencePage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelEnablementPreferencePage.java index 99e515b09..8eaec737d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelEnablementPreferencePage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ModelEnablementPreferencePage.java @@ -147,10 +147,10 @@ public class ModelEnablementPreferencePage extends PreferencePage implements IWo if (e1 instanceof ITeamContentProviderDescriptor && e2 instanceof ITeamContentProviderDescriptor) { ITeamContentProviderDescriptor d1 = (ITeamContentProviderDescriptor) e1; ITeamContentProviderDescriptor d2 = (ITeamContentProviderDescriptor) e2; - IModelProviderDescriptor md1 = ModelProvider.getModelProviderDescriptor(d1.getModelProviderId()); - IModelProviderDescriptor md2 = ModelProvider.getModelProviderDescriptor(d2.getModelProviderId()); - if (md1 != null && md2 != null) - return getLabel(md1).compareTo(getLabel(md2)); + IModelProviderDescriptor md1 = ModelProvider.getModelProviderDescriptor(d1.getModelProviderId()); + IModelProviderDescriptor md2 = ModelProvider.getModelProviderDescriptor(d2.getModelProviderId()); + if (md1 != null && md2 != null) + return getLabel(md1).compareTo(getLabel(md2)); } return super.compare(viewer, e1, e2); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceMappingLabelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceMappingLabelProvider.java index cddeab9d3..4abd2e7fe 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceMappingLabelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceMappingLabelProvider.java @@ -34,16 +34,16 @@ public class ResourceMappingLabelProvider extends LabelProvider { ModelProvider provider = (ModelProvider) element; return provider.getDescriptor().getLabel(); } - String text = provider.getText(element); - if (text != null && text.length() > 0) - return text; - return super.getText(element); + String text = provider.getText(element); + if (text != null && text.length() > 0) + return text; + return super.getText(element); } @Override public Image getImage(Object element) { - Image image = provider.getImage(element); - if (image != null) - return image; + Image image = provider.getImage(element); + if (image != null) + return image; if (element instanceof ResourceMapping) { ResourceMapping mapping = (ResourceMapping) element; image = provider.getImage(mapping.getModelObject()); @@ -52,9 +52,9 @@ public class ResourceMappingLabelProvider extends LabelProvider { } return super.getImage(element); } - @Override + @Override public void dispose() { - provider.dispose(); - super.dispose(); - } + provider.dispose(); + super.dispose(); + } }
\ No newline at end of file diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelActionProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelActionProvider.java index dd5473553..acda0cb5c 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelActionProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelActionProvider.java @@ -93,7 +93,7 @@ public class ResourceModelActionProvider extends SynchronizationActionProvider { @Override public void updateActionBars() { super.updateActionBars(); - if (refactorActions != null) refactorActions.updateActionBars(); + if (refactorActions != null) refactorActions.updateActionBars(); } @Override @@ -102,9 +102,9 @@ public class ResourceModelActionProvider extends SynchronizationActionProvider { if (refactorActions != null) refactorActions.dispose(); } - @Override + @Override public void setContext(ActionContext context) { - super.setContext(context); - if (refactorActions != null) refactorActions.setContext(context); - } + super.setContext(context); + if (refactorActions != null) refactorActions.setContext(context); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelLabelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelLabelProvider.java index 40e9429ce..0a018ee68 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelLabelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/ResourceModelLabelProvider.java @@ -175,7 +175,7 @@ public class ResourceModelLabelProvider extends if (!handledResources.isEmpty()) { final IResource[] resources = handledResources.toArray(new IResource[handledResources.size()]); - updateLabels(resources); + updateLabels(resources); } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/StorageStreamMerger.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/StorageStreamMerger.java index eb520d922..39d66957a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/StorageStreamMerger.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/StorageStreamMerger.java @@ -60,26 +60,26 @@ public class StorageStreamMerger implements IStorageMerger { if (status.getCode() == IStreamMerger.CONFLICT) return new Status(status.getSeverity(), status.getPlugin(), CONFLICT, status.getMessage(), status.getException()); return status; - } finally { - try { - if (ancestorStream != null) - ancestorStream.close(); - } catch (IOException e) { - // Ignore - } - try { - if (remoteStream != null) - remoteStream.close(); - } catch (IOException e) { - // Ignore - } - try { - if (targetStream != null) - targetStream.close(); - } catch (IOException e) { - // Ignore - } - } + } finally { + try { + if (ancestorStream != null) + ancestorStream.close(); + } catch (IOException e) { + // Ignore + } + try { + if (remoteStream != null) + remoteStream.close(); + } catch (IOException e) { + // Ignore + } + try { + if (targetStream != null) + targetStream.close(); + } catch (IOException e) { + // Ignore + } + } } private String getEncoding(IStorage ancestorStorage, String outputEncoding) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/TeamViewerSorter.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/TeamViewerSorter.java index 8311bf122..e875cb58a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/TeamViewerSorter.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/TeamViewerSorter.java @@ -50,11 +50,11 @@ public class TeamViewerSorter extends TreePathViewerSorter { public int compare(Viewer viewer, TreePath parentPath, Object e1, Object e2) { if (parentPath == null || parentPath.getSegmentCount() == 0) { // We need to handle the sorting at the top level - int cat1 = category(e1); - int cat2 = category(e2); + int cat1 = category(e1); + int cat2 = category(e2); - if (cat1 != cat2) - return cat1 - cat2; + if (cat1 != cat2) + return cat1 - cat2; if (e1 instanceof ModelProvider && e2 instanceof ModelProvider) { ModelProvider mp1 = (ModelProvider) e1; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/FileTypeTable.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/FileTypeTable.java index fab8c854c..dec006fa7 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/FileTypeTable.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/FileTypeTable.java @@ -42,26 +42,26 @@ import org.eclipse.team.internal.ui.TeamUIMessages; public class FileTypeTable implements ICellModifier, IStructuredContentProvider, ITableLabelProvider { - private final static int COMBO_INDEX_BINARY= 0; - private final static int COMBO_INDEX_TEXT= 1; - private final static String [] MODES_TEXT= { TeamUIMessages.FileTypeTable_0, TeamUIMessages.FileTypeTable_1 }; // + private final static int COMBO_INDEX_BINARY= 0; + private final static int COMBO_INDEX_TEXT= 1; + private final static String [] MODES_TEXT= { TeamUIMessages.FileTypeTable_0, TeamUIMessages.FileTypeTable_1 }; // - private final static int COMBO_INDEX_SAVE= 0; - private final static int COMBO_INDEX_DONT_SAVE= 1; - private static final String [] SAVE_TEXT= { TeamUIMessages.FileTypeTable_2, TeamUIMessages.FileTypeTable_3 }; // + private final static int COMBO_INDEX_SAVE= 0; + private final static int COMBO_INDEX_DONT_SAVE= 1; + private static final String [] SAVE_TEXT= { TeamUIMessages.FileTypeTable_2, TeamUIMessages.FileTypeTable_3 }; // - private static final class FileTypeComparator extends ViewerComparator { + private static final class FileTypeComparator extends ViewerComparator { - public FileTypeComparator() { - } + public FileTypeComparator() { + } private int getCategory(Object element) { - if (element instanceof Extension) - return 0; - if (element instanceof Name) { - return 1; - } - return 2; + if (element instanceof Extension) + return 0; + if (element instanceof Name) { + return 1; + } + return 2; } @Override @@ -74,41 +74,41 @@ public class FileTypeTable implements ICellModifier, IStructuredContentProvider, } public abstract static class Item implements Comparable { - public final String name; - public boolean save; - public int mode; - public boolean contributed; + public final String name; + public boolean save; + public int mode; + public boolean contributed; - public Item(String name, boolean contributed) { this.name= name; this.contributed = contributed; save= true; mode= Team.BINARY; } + public Item(String name, boolean contributed) { this.name= name; this.contributed = contributed; save= true; mode= Team.BINARY; } @Override public int compareTo(Object o) { return name.compareTo(((Item)o).name); } - } + } - public static class Extension extends Item { - public Extension(String name, boolean contributed) { super(name, contributed); } - } + public static class Extension extends Item { + public Extension(String name, boolean contributed) { super(name, contributed); } + } - public static class Name extends Item { - public Name(String name, boolean contributed) { super(name, contributed); } - } + public static class Name extends Item { + public Name(String name, boolean contributed) { super(name, contributed); } + } - private final static int COLUMN_PADDING = 5; + private final static int COLUMN_PADDING = 5; - protected static final String ITEM = "item"; //$NON-NLS-1$ - protected static final String PROPERTY_MODE= "mode"; //$NON-NLS-1$ - protected static final String PROPERTY_SAVE= "save"; //$NON-NLS-1$ + protected static final String ITEM = "item"; //$NON-NLS-1$ + protected static final String PROPERTY_MODE= "mode"; //$NON-NLS-1$ + protected static final String PROPERTY_SAVE= "save"; //$NON-NLS-1$ - private final TableViewer fTableViewer; - private final List fItems; - private final boolean fShowSaveColumn; + private final TableViewer fTableViewer; + private final List fItems; + private final boolean fShowSaveColumn; public FileTypeTable(Composite composite, List items, boolean showSaveColumn) { - fShowSaveColumn= showSaveColumn; - fItems= items; + fShowSaveColumn= showSaveColumn; + fItems= items; /** @@ -119,7 +119,7 @@ public class FileTypeTable implements ICellModifier, IStructuredContentProvider, table.setLinesVisible(true); table.setHeaderVisible(true); - final PixelConverter converter= SWTUtils.createDialogPixelConverter(composite); + final PixelConverter converter= SWTUtils.createDialogPixelConverter(composite); /** * The 'Extension' column @@ -133,24 +133,24 @@ public class FileTypeTable implements ICellModifier, IStructuredContentProvider, */ final TableColumn modeColumn = new TableColumn(table, SWT.NONE, 1); int length; - try { - length = TeamUIMessages.FileTypeTable_5.length(); - length = Math.max(length, TeamUIMessages.FileTypeTable_0.length()); - length = Math.max(length, TeamUIMessages.FileTypeTable_1.length()); - } catch (RuntimeException e) { - // There may be an unbound message so just pick a reasonable length - length = 15; - } - modeColumn.setWidth(converter.convertWidthInCharsToPixels(length + COLUMN_PADDING)); + try { + length = TeamUIMessages.FileTypeTable_5.length(); + length = Math.max(length, TeamUIMessages.FileTypeTable_0.length()); + length = Math.max(length, TeamUIMessages.FileTypeTable_1.length()); + } catch (RuntimeException e) { + // There may be an unbound message so just pick a reasonable length + length = 15; + } + modeColumn.setWidth(converter.convertWidthInCharsToPixels(length + COLUMN_PADDING)); modeColumn.setText(TeamUIMessages.FileTypeTable_5); /** * The 'Save' column */ if (fShowSaveColumn) { - final TableColumn saveColumn = new TableColumn(table, SWT.NONE, 2); - saveColumn.setWidth(converter.convertWidthInCharsToPixels(TeamUIMessages.FileTypeTable_6.length() + COLUMN_PADDING)); - saveColumn.setText(TeamUIMessages.FileTypeTable_6); + final TableColumn saveColumn = new TableColumn(table, SWT.NONE, 2); + saveColumn.setWidth(converter.convertWidthInCharsToPixels(TeamUIMessages.FileTypeTable_6.length() + COLUMN_PADDING)); + saveColumn.setText(TeamUIMessages.FileTypeTable_6); } /** @@ -170,11 +170,11 @@ public class FileTypeTable implements ICellModifier, IStructuredContentProvider, final CellEditor saveEditor= new ComboBoxCellEditor(table, SAVE_TEXT, SWT.READ_ONLY); if (fShowSaveColumn) { - fTableViewer.setCellEditors(new CellEditor[] { null, modeEditor, saveEditor }); - fTableViewer.setColumnProperties(new String [] { ITEM, PROPERTY_MODE, PROPERTY_SAVE }); + fTableViewer.setCellEditors(new CellEditor[] { null, modeEditor, saveEditor }); + fTableViewer.setColumnProperties(new String [] { ITEM, PROPERTY_MODE, PROPERTY_SAVE }); } else { - fTableViewer.setCellEditors(new CellEditor [] { null, modeEditor }); - fTableViewer.setColumnProperties(new String [] { ITEM, PROPERTY_MODE }); + fTableViewer.setCellEditors(new CellEditor [] { null, modeEditor }); + fTableViewer.setColumnProperties(new String [] { ITEM, PROPERTY_MODE }); } fTableViewer.setCellModifier(this); @@ -183,116 +183,116 @@ public class FileTypeTable implements ICellModifier, IStructuredContentProvider, } - @Override + @Override public Object getValue(Object element, String property) { - final Item item= (Item)element; + final Item item= (Item)element; - if (PROPERTY_MODE.equals(property)) { - if (item.mode == Team.BINARY) - return Integer.valueOf(COMBO_INDEX_BINARY); - if (item.mode == Team.TEXT) - return Integer.valueOf(COMBO_INDEX_TEXT); - } + if (PROPERTY_MODE.equals(property)) { + if (item.mode == Team.BINARY) + return Integer.valueOf(COMBO_INDEX_BINARY); + if (item.mode == Team.TEXT) + return Integer.valueOf(COMBO_INDEX_TEXT); + } - if (fShowSaveColumn && PROPERTY_SAVE.equals(property)) { - return Integer.valueOf(item.save ? COMBO_INDEX_SAVE : COMBO_INDEX_DONT_SAVE); - } - return null; - } + if (fShowSaveColumn && PROPERTY_SAVE.equals(property)) { + return Integer.valueOf(item.save ? COMBO_INDEX_SAVE : COMBO_INDEX_DONT_SAVE); + } + return null; + } - @Override + @Override public boolean canModify(Object element, String property) { - return PROPERTY_MODE.equals(property) || (fShowSaveColumn && PROPERTY_SAVE.equals(property)); - } + return PROPERTY_MODE.equals(property) || (fShowSaveColumn && PROPERTY_SAVE.equals(property)); + } - @Override + @Override public void modify(Object element, String property, Object value) { - final IStructuredSelection selection = fTableViewer.getStructuredSelection(); - final Item item= (Item)selection.getFirstElement(); - if (item == null) - return; + final IStructuredSelection selection = fTableViewer.getStructuredSelection(); + final Item item= (Item)selection.getFirstElement(); + if (item == null) + return; - final int comboIndex = ((Integer)value).intValue(); + final int comboIndex = ((Integer)value).intValue(); - if (PROPERTY_MODE.equals(property)) { - if (comboIndex == COMBO_INDEX_BINARY) - item.mode= Team.BINARY; - if (comboIndex == COMBO_INDEX_TEXT) - item.mode= Team.TEXT; - } + if (PROPERTY_MODE.equals(property)) { + if (comboIndex == COMBO_INDEX_BINARY) + item.mode= Team.BINARY; + if (comboIndex == COMBO_INDEX_TEXT) + item.mode= Team.TEXT; + } - if (fShowSaveColumn && PROPERTY_SAVE.equals(property)) { - item.save= COMBO_INDEX_SAVE == comboIndex; - } - fTableViewer.refresh(item); - } + if (fShowSaveColumn && PROPERTY_SAVE.equals(property)) { + item.save= COMBO_INDEX_SAVE == comboIndex; + } + fTableViewer.refresh(item); + } - @Override + @Override public Image getColumnImage(Object element, int columnIndex) { - return null; - } + return null; + } - @Override + @Override public String getColumnText(Object element, int columnIndex) { - final Item item= (Item) element; + final Item item= (Item) element; - if (columnIndex == 0) { - String label = (item instanceof Extension ? "*." : "") + item.name; //$NON-NLS-1$ //$NON-NLS-2$ - label = TextProcessor.process(label, ".*"); //$NON-NLS-1$ + if (columnIndex == 0) { + String label = (item instanceof Extension ? "*." : "") + item.name; //$NON-NLS-1$ //$NON-NLS-2$ + label = TextProcessor.process(label, ".*"); //$NON-NLS-1$ return label; - } + } - if (columnIndex == 1) { - if (item.mode == Team.BINARY) { - return MODES_TEXT[COMBO_INDEX_BINARY]; - } else if (item.mode == Team.TEXT) { - return MODES_TEXT[COMBO_INDEX_TEXT]; - } - } + if (columnIndex == 1) { + if (item.mode == Team.BINARY) { + return MODES_TEXT[COMBO_INDEX_BINARY]; + } else if (item.mode == Team.TEXT) { + return MODES_TEXT[COMBO_INDEX_TEXT]; + } + } - if (columnIndex == 2) { - if (fShowSaveColumn) return SAVE_TEXT[item.save ? COMBO_INDEX_SAVE : COMBO_INDEX_DONT_SAVE]; - } + if (columnIndex == 2) { + if (fShowSaveColumn) return SAVE_TEXT[item.save ? COMBO_INDEX_SAVE : COMBO_INDEX_DONT_SAVE]; + } - return null; - } + return null; + } - @Override + @Override public void addListener(ILabelProviderListener listener) {} - @Override + @Override public void dispose() {} - @Override + @Override public boolean isLabelProperty(Object element, String property) { - return false; - } + return false; + } - @Override + @Override public void removeListener(ILabelProviderListener listener) {} - @Override + @Override public Object[] getElements(Object inputElement) { - return ((Collection)inputElement).toArray(); - } + return ((Collection)inputElement).toArray(); + } - @Override + @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {} - public IStructuredSelection getSelection() { - return fTableViewer.getStructuredSelection(); - } + public IStructuredSelection getSelection() { + return fTableViewer.getStructuredSelection(); + } - public void setInput(List items) { - fItems.clear(); - fItems.addAll(items); - fTableViewer.refresh(); - } + public void setInput(List items) { + fItems.clear(); + fItems.addAll(items); + fTableViewer.refresh(); + } - public TableViewer getViewer() { - return fTableViewer; - } + public TableViewer getViewer() { + return fTableViewer; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/IgnorePreferencePage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/IgnorePreferencePage.java index 8e35b7160..e5e0a119e 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/IgnorePreferencePage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/IgnorePreferencePage.java @@ -100,8 +100,8 @@ public class IgnorePreferencePage extends PreferencePage implements IWorkbenchPr setButtonLayoutData(addButton); setButtonLayoutData(removeButton); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.IGNORE_PREFERENCE_PAGE); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.IGNORE_PREFERENCE_PAGE); return parent; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/ResourceModelPreferencePage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/ResourceModelPreferencePage.java index 9330b3d3f..ed1958d8f 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/ResourceModelPreferencePage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/ResourceModelPreferencePage.java @@ -38,21 +38,21 @@ public class ResourceModelPreferencePage extends FieldEditorPreferencePage imple @Override public void createControl(Composite parent) { super.createControl(parent); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.RESOURCE_MODEL_PREFERENCE_PAGE); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.RESOURCE_MODEL_PREFERENCE_PAGE); } @Override protected void createFieldEditors() { - defaultLayout = new RadioGroupFieldEditor(SYNCVIEW_DEFAULT_LAYOUT, - TeamUIMessages.SyncViewerPreferencePage_0, 3, - new String[][] { - {TeamUIMessages.SyncViewerPreferencePage_1, FLAT_LAYOUT}, - {TeamUIMessages.SyncViewerPreferencePage_2, TREE_LAYOUT}, - {TeamUIMessages.SyncViewerPreferencePage_3, COMPRESSED_LAYOUT} - }, - getFieldEditorParent(), true /* use a group */); - addField(defaultLayout); + defaultLayout = new RadioGroupFieldEditor(SYNCVIEW_DEFAULT_LAYOUT, + TeamUIMessages.SyncViewerPreferencePage_0, 3, + new String[][] { + {TeamUIMessages.SyncViewerPreferencePage_1, FLAT_LAYOUT}, + {TeamUIMessages.SyncViewerPreferencePage_2, TREE_LAYOUT}, + {TeamUIMessages.SyncViewerPreferencePage_3, COMPRESSED_LAYOUT} + }, + getFieldEditorParent(), true /* use a group */); + addField(defaultLayout); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/SyncViewerPreferencePage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/SyncViewerPreferencePage.java index 45471da2a..71d3d5ac7 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/SyncViewerPreferencePage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/SyncViewerPreferencePage.java @@ -49,8 +49,8 @@ public class SyncViewerPreferencePage extends FieldEditorPreferencePage implemen private BooleanFieldEditor showSyncInLabels = null; private RadioGroupFieldEditor synchronizePerspectiveSwitch = null; - private RadioGroupFieldEditor defaultLayout = null; - private boolean includeDefaultLayout = true; + private RadioGroupFieldEditor defaultLayout = null; + private boolean includeDefaultLayout = true; private static class PerspectiveDescriptorComparator implements Comparator { @Override @@ -74,8 +74,8 @@ public class SyncViewerPreferencePage extends FieldEditorPreferencePage implemen @Override public void createControl(Composite parent) { super.createControl(parent); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.SYNC_PREFERENCE_PAGE); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.SYNC_PREFERENCE_PAGE); } @Override @@ -84,45 +84,45 @@ public class SyncViewerPreferencePage extends FieldEditorPreferencePage implemen addField(showSyncInLabels); addField(new BooleanFieldEditor( - SHOW_AUTHOR_IN_COMPARE_EDITOR, - TeamUIMessages.SyncViewerPreferencePage_43, + SHOW_AUTHOR_IN_COMPARE_EDITOR, + TeamUIMessages.SyncViewerPreferencePage_43, BooleanFieldEditor.DEFAULT, getFieldEditorParent())); addField(new BooleanFieldEditor( MAKE_FILE_WRITTABLE_IF_CONTEXT_MISSING, - TeamUIMessages.SyncViewerPreferencePage_44, + TeamUIMessages.SyncViewerPreferencePage_44, BooleanFieldEditor.DEFAULT, getFieldEditorParent())); addField(new BooleanFieldEditor( REUSE_OPEN_COMPARE_EDITOR, - TeamUIMessages.SyncViewerPreferencePage_45, + TeamUIMessages.SyncViewerPreferencePage_45, BooleanFieldEditor.DEFAULT, getFieldEditorParent())); addField(new BooleanFieldEditor( RUN_IMPORT_IN_BACKGROUND, - TeamUIMessages.SyncViewerPreferencePage_46, + TeamUIMessages.SyncViewerPreferencePage_46, BooleanFieldEditor.DEFAULT, getFieldEditorParent())); addField(new BooleanFieldEditor( APPLY_PATCH_IN_SYNCHRONIZE_VIEW, - TeamUIMessages.SyncViewerPreferencePage_47, + TeamUIMessages.SyncViewerPreferencePage_47, BooleanFieldEditor.DEFAULT, getFieldEditorParent())); if (isIncludeDefaultLayout()) { - defaultLayout = new RadioGroupFieldEditor(SYNCVIEW_DEFAULT_LAYOUT, - TeamUIMessages.SyncViewerPreferencePage_0, 3, - new String[][] { - {TeamUIMessages.SyncViewerPreferencePage_1, FLAT_LAYOUT}, - {TeamUIMessages.SyncViewerPreferencePage_2, TREE_LAYOUT}, - {TeamUIMessages.SyncViewerPreferencePage_3, COMPRESSED_LAYOUT} - }, - getFieldEditorParent(), true /* use a group */); - addField(defaultLayout); + defaultLayout = new RadioGroupFieldEditor(SYNCVIEW_DEFAULT_LAYOUT, + TeamUIMessages.SyncViewerPreferencePage_0, 3, + new String[][] { + {TeamUIMessages.SyncViewerPreferencePage_1, FLAT_LAYOUT}, + {TeamUIMessages.SyncViewerPreferencePage_2, TREE_LAYOUT}, + {TeamUIMessages.SyncViewerPreferencePage_3, COMPRESSED_LAYOUT} + }, + getFieldEditorParent(), true /* use a group */); + addField(defaultLayout); } synchronizePerspectiveSwitch= new RadioGroupFieldEditor(SYNCHRONIZING_COMPLETE_PERSPECTIVE, TeamUIMessages.SyncViewerPreferencePage_13, 3, diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/TextPreferencePage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/TextPreferencePage.java index b28c64aca..036b52df9 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/TextPreferencePage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/preferences/TextPreferencePage.java @@ -112,48 +112,48 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref private Button fRemoveButton; private Button fChangeButton; - protected FileTypeTable fTable; + protected FileTypeTable fTable; - public TextPreferencePage() { - fItems= new ArrayList<>(); - initializeItems(); - } + public TextPreferencePage() { + fItems= new ArrayList<>(); + initializeItems(); + } - private void initializeItems() { + private void initializeItems() { - fItems.clear(); + fItems.clear(); - final IFileContentManager manager= Team.getFileContentManager(); + final IFileContentManager manager= Team.getFileContentManager(); - final IStringMapping [] extensionInfoArray= manager.getExtensionMappings(); - final IStringMapping [] nameInfoArray= manager.getNameMappings(); + final IStringMapping [] extensionInfoArray= manager.getExtensionMappings(); + final IStringMapping [] nameInfoArray= manager.getNameMappings(); - Set fPluginNames= makeSetOfStrings(manager.getDefaultNameMappings()); - Set fPluginExtensions= makeSetOfStrings(manager.getDefaultExtensionMappings()); + Set fPluginNames= makeSetOfStrings(manager.getDefaultNameMappings()); + Set fPluginExtensions= makeSetOfStrings(manager.getDefaultExtensionMappings()); - for (int i = 0; i < extensionInfoArray.length; i++) { - final IStringMapping info= extensionInfoArray[i]; - final FileTypeTable.Extension extension= new FileTypeTable.Extension(info.getString(), fPluginExtensions.contains(info.getString())); - extension.mode= info.getType(); - fItems.add(extension); - } + for (int i = 0; i < extensionInfoArray.length; i++) { + final IStringMapping info= extensionInfoArray[i]; + final FileTypeTable.Extension extension= new FileTypeTable.Extension(info.getString(), fPluginExtensions.contains(info.getString())); + extension.mode= info.getType(); + fItems.add(extension); + } - for (int i = 0; i < nameInfoArray.length; i++) { - final IStringMapping info= nameInfoArray[i]; - final FileTypeTable.Name name= new FileTypeTable.Name(info.getString(), fPluginNames.contains(info.getString())); - name.mode= info.getType(); - fItems.add(name); - } + for (int i = 0; i < nameInfoArray.length; i++) { + final IStringMapping info= nameInfoArray[i]; + final FileTypeTable.Name name= new FileTypeTable.Name(info.getString(), fPluginNames.contains(info.getString())); + name.mode= info.getType(); + fItems.add(name); + } - } + } - private static Set<String> makeSetOfStrings(IStringMapping [] mappings) { - final Set<String> set= new HashSet<>(mappings.length); - for (int i = 0; i < mappings.length; i++) { + private static Set<String> makeSetOfStrings(IStringMapping [] mappings) { + final Set<String> set= new HashSet<>(mappings.length); + for (int i = 0; i < mappings.length; i++) { set.add(mappings[i].getString()); } - return set; - } + return set; + } @Override public void init(IWorkbench workbench) { @@ -216,8 +216,8 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref Dialog.applyDialogFont(parent); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.FILE_TYPE_PREFERENCE_PAGE); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.FILE_TYPE_PREFERENCE_PAGE); return composite; } @@ -227,7 +227,7 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref super.performDefaults(); initializeItems(); if (fTable != null) - fTable.getViewer().refresh(); + fTable.getViewer().refresh(); } /** @@ -237,32 +237,32 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref */ @Override public boolean performOk() { - final ArrayList<String> extensionsList= new ArrayList<>(); - final ArrayList<Integer> extensionsModesList= new ArrayList<>(); + final ArrayList<String> extensionsList= new ArrayList<>(); + final ArrayList<Integer> extensionsModesList= new ArrayList<>(); - final ArrayList<String> namesList= new ArrayList<>(); - final ArrayList<Integer> namesModesList= new ArrayList<>(); + final ArrayList<String> namesList= new ArrayList<>(); + final ArrayList<Integer> namesModesList= new ArrayList<>(); - for (final Iterator iter = fItems.iterator(); iter.hasNext();) { - final FileTypeTable.Item item= (FileTypeTable.Item) iter.next(); + for (final Iterator iter = fItems.iterator(); iter.hasNext();) { + final FileTypeTable.Item item= (FileTypeTable.Item) iter.next(); - if (item instanceof FileTypeTable.Extension) { - extensionsList.add(item.name); - extensionsModesList.add(Integer.valueOf(item.mode)); - } else if (item instanceof FileTypeTable.Name) { - namesList.add(item.name); - namesModesList.add(Integer.valueOf(item.mode)); - } - } + if (item instanceof FileTypeTable.Extension) { + extensionsList.add(item.name); + extensionsModesList.add(Integer.valueOf(item.mode)); + } else if (item instanceof FileTypeTable.Name) { + namesList.add(item.name); + namesModesList.add(Integer.valueOf(item.mode)); + } + } - final String [] extensions= extensionsList.toArray(new String [extensionsList.size()]); - final String [] names= namesList.toArray(new String [namesList.size()]); + final String [] extensions= extensionsList.toArray(new String [extensionsList.size()]); + final String [] names= namesList.toArray(new String [namesList.size()]); - final int [] extensionsModes= integerListToIntArray(extensionsModesList); - final int [] namesModes= integerListToIntArray(namesModesList); + final int [] extensionsModes= integerListToIntArray(extensionsModesList); + final int [] namesModes= integerListToIntArray(namesModesList); - Team.getFileContentManager().setExtensionMappings(extensions, extensionsModes); - Team.getFileContentManager().setNameMappings(names, namesModes); + Team.getFileContentManager().setExtensionMappings(extensions, extensionsModes); + Team.getFileContentManager().setNameMappings(names, namesModes); TeamUIPlugin.broadcastPropertyChange(new PropertyChangeEvent(this, TeamUI.GLOBAL_FILE_TYPES_CHANGED, null, null)); @@ -270,11 +270,11 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref } private static int [] integerListToIntArray(List integers) { - final int [] array= new int [integers.size()]; - int index= 0; - for (Iterator iter = integers.iterator(); iter.hasNext();) - array[index++]= ((Integer)iter.next()).intValue(); - return array; + final int [] array= new int [integers.size()]; + int index= 0; + for (Iterator iter = integers.iterator(); iter.hasNext();) + array[index++]= ((Integer)iter.next()).intValue(); + return array; } /** @@ -341,13 +341,13 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref fItems.remove(item); } fTable.getViewer().refresh(); - handleSelection(); + handleSelection(); } /** * Toggle the selected items' content types */ void changePattern() { - final IStructuredSelection selection = fTable.getSelection(); + final IStructuredSelection selection = fTable.getSelection(); if (selection == null) return; @@ -363,7 +363,7 @@ public class TextPreferencePage extends PreferencePage implements IWorkbenchPref */ void handleSelection() { final boolean empty = fTable.getSelection().isEmpty(); - FileTypeTable.Item selectedItem = (Item) fTable.getSelection().getFirstElement(); + FileTypeTable.Item selectedItem = (Item) fTable.getSelection().getFirstElement(); fRemoveButton.setEnabled(!empty && !selectedItem.contributed); fChangeButton.setEnabled(!empty); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/registry/RegistryReader.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/registry/RegistryReader.java index 52a1a100d..ce3abbdbf 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/registry/RegistryReader.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/registry/RegistryReader.java @@ -34,55 +34,55 @@ public abstract class RegistryReader { protected static final String TAG_DESCRIPTION = "description"; //$NON-NLS-1$ protected static Hashtable<String, IExtension[]> extensionPoints = new Hashtable<>(); - /** - * Creates an extension. If the extension plugin has not - * been loaded a busy cursor will be activated during the duration of - * the load. - * - * @param element the configuration element defining the extension - * @param classAttribute the name of the attribute carrying the class - * @return the extension object - * @throws CoreException if the extension cannot be created - */ - public static Object createExtension(final IConfigurationElement element, - final String classAttribute) throws CoreException { - try { - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - if (isActivated(element.getDeclaringExtension() - .getContributor().getName())) { - return element.createExecutableExtension(classAttribute); - } - final Object[] ret = new Object[1]; - final CoreException[] exc = new CoreException[1]; - BusyIndicator.showWhile(null, () -> { - try { - ret[0] = element - .createExecutableExtension(classAttribute); - } catch (CoreException e) { - exc[0] = e; - } + /** + * Creates an extension. If the extension plugin has not + * been loaded a busy cursor will be activated during the duration of + * the load. + * + * @param element the configuration element defining the extension + * @param classAttribute the name of the attribute carrying the class + * @return the extension object + * @throws CoreException if the extension cannot be created + */ + public static Object createExtension(final IConfigurationElement element, + final String classAttribute) throws CoreException { + try { + // If plugin has been loaded create extension. + // Otherwise, show busy cursor then create extension. + if (isActivated(element.getDeclaringExtension() + .getContributor().getName())) { + return element.createExecutableExtension(classAttribute); + } + final Object[] ret = new Object[1]; + final CoreException[] exc = new CoreException[1]; + BusyIndicator.showWhile(null, () -> { + try { + ret[0] = element + .createExecutableExtension(classAttribute); + } catch (CoreException e) { + exc[0] = e; + } }); - if (exc[0] != null) { + if (exc[0] != null) { throw exc[0]; } - return ret[0]; + return ret[0]; - } catch (CoreException core) { - throw core; - } catch (Exception e) { - throw new CoreException(new Status(IStatus.ERROR, TeamUIPlugin.ID, - IStatus.ERROR, NLS.bind(TeamUIMessages.RegistryReader_0, element.getNamespaceIdentifier(), element.getName()),e)); - } - } + } catch (CoreException core) { + throw core; + } catch (Exception e) { + throw new CoreException(new Status(IStatus.ERROR, TeamUIPlugin.ID, + IStatus.ERROR, NLS.bind(TeamUIMessages.RegistryReader_0, element.getNamespaceIdentifier(), element.getName()),e)); + } + } - private static boolean isActivated(String bundleId) { - return isActivated(Platform.getBundle(bundleId)); - } + private static boolean isActivated(String bundleId) { + return isActivated(Platform.getBundle(bundleId)); + } - private static boolean isActivated(Bundle bundle) { - return bundle != null && (bundle.getState() & (Bundle.ACTIVE | Bundle.STOPPING)) != 0; - } + private static boolean isActivated(Bundle bundle) { + return bundle != null && (bundle.getState() & (Bundle.ACTIVE | Bundle.STOPPING)) != 0; + } /** * The constructor. diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractSynchronizeModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractSynchronizeModelProvider.java index a2616f7d8..c570a8ba8 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractSynchronizeModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractSynchronizeModelProvider.java @@ -97,11 +97,11 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo private boolean disposed = false; - private SynchronizePageActionGroup actionGroup; + private SynchronizePageActionGroup actionGroup; - private ListenerList<IPropertyChangeListener> listeners; + private ListenerList<IPropertyChangeListener> listeners; - private static final boolean DEBUG = false; + private static final boolean DEBUG = false; /** * Constructor for creating a sub-provider @@ -117,22 +117,22 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo this.set = set; this.configuration = configuration; if (parentProvider == null) { - // The update handler will register for sync change events - // with the sync set when the handler is activated - updateHandler = new SynchronizeModelUpdateHandler(this); - getTree().addTreeListener(this); + // The update handler will register for sync change events + // with the sync set when the handler is activated + updateHandler = new SynchronizeModelUpdateHandler(this); + getTree().addTreeListener(this); } else { - // We will use the parent's update handler and register for changes with the given set - updateHandler = parentProvider.updateHandler; - set.addSyncSetChangedListener(this); + // We will use the parent's update handler and register for changes with the given set + updateHandler = parentProvider.updateHandler; + set.addSyncSetChangedListener(this); } } private Tree getTree() { - return ((Tree)((AbstractTreeViewer)getViewer()).getControl()); - } + return ((Tree)((AbstractTreeViewer)getViewer()).getControl()); + } - /** + /** * Constructor for creating a root model provider. * @param configuration the sync page configuration * @param set the sync info set from which the model is built @@ -150,41 +150,41 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo // Register the action group for this provider, since it is the root provider SynchronizePageActionGroup actionGroup = getActionGroup(); if (actionGroup != null) { - configuration.addActionContribution(actionGroup); + configuration.addActionContribution(actionGroup); } } /** * Return the action group for this provider or <code>null</code> - * if there are no actions associated with this provider. The action - * group will be registered with the configuration if this is - * the root provider. If this provider is a sub-provider, it - * is up to the parent provider to register the action group. - * <p> - * The action group for a provider is created by calling the - * <code>createdActionGroup</code> method. If this method returns - * a non-null group, it is cached so it can be disposed - * when the provider is disposed. - * @return the action group for this provider or <code>null</code> - * if there are no actions associated with this provider - */ - public final synchronized SynchronizePageActionGroup getActionGroup() { - if (actionGroup == null) { - actionGroup = createActionGroup(); - } - return actionGroup; - } - - /** - * Create the action group for this provider. By default, - * a <code>null</code> is returned. Subclasses may override. - * @return the action group for this provider or <code>null</code> - */ - protected SynchronizePageActionGroup createActionGroup() { - return null; - } - - /** + * if there are no actions associated with this provider. The action + * group will be registered with the configuration if this is + * the root provider. If this provider is a sub-provider, it + * is up to the parent provider to register the action group. + * <p> + * The action group for a provider is created by calling the + * <code>createdActionGroup</code> method. If this method returns + * a non-null group, it is cached so it can be disposed + * when the provider is disposed. + * @return the action group for this provider or <code>null</code> + * if there are no actions associated with this provider + */ + public final synchronized SynchronizePageActionGroup getActionGroup() { + if (actionGroup == null) { + actionGroup = createActionGroup(); + } + return actionGroup; + } + + /** + * Create the action group for this provider. By default, + * a <code>null</code> is returned. Subclasses may override. + * @return the action group for this provider or <code>null</code> + */ + protected SynchronizePageActionGroup createActionGroup() { + return null; + } + + /** * Return the set that contains the elements this provider is using as * a basis for creating a presentation model. This cannot be null. * @@ -225,9 +225,9 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo public StructuredViewer getViewer() { ISynchronizePage page = configuration.getPage(); if (page == null) return null; - Viewer viewer = page.getViewer(); + Viewer viewer = page.getViewer(); if (viewer instanceof AbstractTreeViewer) { - return (AbstractTreeViewer)viewer; + return (AbstractTreeViewer)viewer; } return null; } @@ -239,11 +239,11 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo public ISynchronizeModelElement prepareInput(IProgressMonitor monitor) { // Connect to the sync set which will register us as a listener and give us a reset event // in a background thread - if (isRootProvider()) { - updateHandler.connect(monitor); - } else { - getSyncInfoSet().connect(this, monitor); - } + if (isRootProvider()) { + updateHandler.connect(monitor); + } else { + getSyncInfoSet().connect(this, monitor); + } return getModelRoot(); } @@ -298,22 +298,22 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo } } } else if (resource == null) { - // For non-resource elements, show the same propogaqted marker as the children - IDiffElement[] children = element.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement child = children[i]; - if (child instanceof ISynchronizeModelElement) { - ISynchronizeModelElement childElement = (ISynchronizeModelElement)child; - if (childElement.getProperty(ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY)) { - property = ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY; - break; - } else if (childElement.getProperty(ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY)) { + // For non-resource elements, show the same propogaqted marker as the children + IDiffElement[] children = element.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement child = children[i]; + if (child instanceof ISynchronizeModelElement) { + ISynchronizeModelElement childElement = (ISynchronizeModelElement)child; + if (childElement.getProperty(ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY)) { + property = ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY; + break; + } else if (childElement.getProperty(ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY)) { property = ISynchronizeModelElement.PROPAGATED_WARNING_MARKER_PROPERTY; // Keep going because there may be errors on other resources } - } - } + } + } } return property; } @@ -337,10 +337,10 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo updateHandler.queueForLabelUpdate(diffNode); } - /** - * Throw away any old state associated with this provider and - * rebuild the model from scratch. - */ + /** + * Throw away any old state associated with this provider and + * rebuild the model from scratch. + */ protected void reset() { // save expansion state if(isRootProvider() && hasViewerState()) { @@ -360,40 +360,40 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo } if (Utils.canUpdateViewer(getViewer())) { - // If we can update the viewer, that means that the view was updated - // when the model was rebuilt. - refreshModelRoot(); + // If we can update the viewer, that means that the view was updated + // when the model was rebuilt. + refreshModelRoot(); } else { - // Only refresh the view if there is now background update in - // progress. If there is, the background update will refresh - if (!updateHandler.isPerformingBackgroundUpdate()) { + // Only refresh the view if there is now background update in + // progress. If there is, the background update will refresh + if (!updateHandler.isPerformingBackgroundUpdate()) { Utils.asyncExec((Runnable) () -> refreshModelRoot(), getViewer()); - } + } } } - private void refreshModelRoot() { - StructuredViewer viewer = getViewer(); + private void refreshModelRoot() { + StructuredViewer viewer = getViewer(); if (viewer != null && !viewer.getControl().isDisposed()) { try { viewer.getControl().setRedraw(false); if (isRootProvider() || getModelRoot().getParent() == null) { - // Refresh the entire view - viewer.refresh(); + // Refresh the entire view + viewer.refresh(); } else { - // Only refresh the model root bu also ensure that - // the parents of the model root and the model root - // itself are added to the view - addToViewer(getModelRoot()); + // Only refresh the model root bu also ensure that + // the parents of the model root and the model root + // itself are added to the view + addToViewer(getModelRoot()); } // restore expansion state if (isRootProvider()) - restoreViewerState(); + restoreViewerState(); } finally { viewer.getControl().setRedraw(true); } } - } + } /** * For each node create children based on the contents of @@ -404,85 +404,85 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo /** * Returns whether the viewer has state to be saved. - * @return whether the viewer has state to be saved - */ - protected abstract boolean hasViewerState(); - - /* - * Return all the resources that are expanded in the page. - * This method should only be called in the UI thread - * after validating that the viewer is still valid. - */ - protected IResource[] getExpandedResources() { - Set<IResource> expanded = new HashSet<>(); - IResource[] savedExpansionState = getCachedResources(P_VIEWER_EXPANSION_STATE); - for (int i = 0; i < savedExpansionState.length; i++) { - IResource resource = savedExpansionState[i]; - expanded.add(resource); - } - StructuredViewer viewer = getViewer(); - Object[] objects = ((AbstractTreeViewer) viewer).getVisibleExpandedElements(); - IResource[] currentExpansionState = getResources(objects); - for (int i = 0; i < currentExpansionState.length; i++) { - IResource resource = currentExpansionState[i]; - expanded.add(resource); - } - return expanded.toArray(new IResource[expanded.size()]); - } - - /* - * Return all the resources that are selected in the page. - * This method should only be called in the UI thread - * after validating that the viewer is still valid. - */ - protected IResource[] getSelectedResources() { - StructuredViewer viewer = getViewer(); - return getResources(viewer.getStructuredSelection().toArray()); - } - - /* - * Return all the resources that are checked in the page. - * This method should only be called in the UI thread - * after validating that the viewer is still valid. - */ - protected IResource[] getCheckedResources() { - StructuredViewer viewer = getViewer(); - if (viewer instanceof CheckboxTreeViewer){ - return getResources(((CheckboxTreeViewer)viewer).getCheckedElements()); - } - - return new IResource[0]; - } - - /* - * Expand the resources if they appear in the page. - * This method should only be called in the UI thread - * after validating that the viewer is still valid. - */ - protected void expandResources(IResource[] resources) { - Set<ISynchronizeModelElement> expandedElements = new HashSet<>(); - StructuredViewer viewer = getViewer(); - for (int j = 0; j < resources.length; j++) { - IResource resource = resources[j]; + * @return whether the viewer has state to be saved + */ + protected abstract boolean hasViewerState(); + + /* + * Return all the resources that are expanded in the page. + * This method should only be called in the UI thread + * after validating that the viewer is still valid. + */ + protected IResource[] getExpandedResources() { + Set<IResource> expanded = new HashSet<>(); + IResource[] savedExpansionState = getCachedResources(P_VIEWER_EXPANSION_STATE); + for (int i = 0; i < savedExpansionState.length; i++) { + IResource resource = savedExpansionState[i]; + expanded.add(resource); + } + StructuredViewer viewer = getViewer(); + Object[] objects = ((AbstractTreeViewer) viewer).getVisibleExpandedElements(); + IResource[] currentExpansionState = getResources(objects); + for (int i = 0; i < currentExpansionState.length; i++) { + IResource resource = currentExpansionState[i]; + expanded.add(resource); + } + return expanded.toArray(new IResource[expanded.size()]); + } + + /* + * Return all the resources that are selected in the page. + * This method should only be called in the UI thread + * after validating that the viewer is still valid. + */ + protected IResource[] getSelectedResources() { + StructuredViewer viewer = getViewer(); + return getResources(viewer.getStructuredSelection().toArray()); + } + + /* + * Return all the resources that are checked in the page. + * This method should only be called in the UI thread + * after validating that the viewer is still valid. + */ + protected IResource[] getCheckedResources() { + StructuredViewer viewer = getViewer(); + if (viewer instanceof CheckboxTreeViewer){ + return getResources(((CheckboxTreeViewer)viewer).getCheckedElements()); + } + + return new IResource[0]; + } + + /* + * Expand the resources if they appear in the page. + * This method should only be called in the UI thread + * after validating that the viewer is still valid. + */ + protected void expandResources(IResource[] resources) { + Set<ISynchronizeModelElement> expandedElements = new HashSet<>(); + StructuredViewer viewer = getViewer(); + for (int j = 0; j < resources.length; j++) { + IResource resource = resources[j]; ISynchronizeModelElement[] elements = getModelObjects(resource); - // Only expand when there is one element per resource - if (elements.length == 1) { - for (int i = 0; i < elements.length; i++) { - ISynchronizeModelElement element = elements[i]; - // Add all parents of the element to the expansion set - while (element != null) { - expandedElements.add(element); - element = (ISynchronizeModelElement)element.getParent(); - } - } - } + // Only expand when there is one element per resource + if (elements.length == 1) { + for (int i = 0; i < elements.length; i++) { + ISynchronizeModelElement element = elements[i]; + // Add all parents of the element to the expansion set + while (element != null) { + expandedElements.add(element); + element = (ISynchronizeModelElement)element.getParent(); + } + } + } } - if (!expandedElements.isEmpty()) - ((AbstractTreeViewer) viewer).setExpandedElements(expandedElements.toArray()); - } + if (!expandedElements.isEmpty()) + ((AbstractTreeViewer) viewer).setExpandedElements(expandedElements.toArray()); + } - protected IResource[] getResources(Object[] objects) { - Set<IResource> result = new HashSet<>(); + protected IResource[] getResources(Object[] objects) { + Set<IResource> result = new HashSet<>(); if (objects.length > 0) { for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof ISynchronizeModelElement) { @@ -493,13 +493,13 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo } } return result.toArray(new IResource[result.size()]); - } + } - private void clearResourceCache(String configProperty) { - getConfiguration().setProperty(configProperty, null); - } + private void clearResourceCache(String configProperty) { + getConfiguration().setProperty(configProperty, null); + } - private void cacheResources(IResource[] resources, String configProperty) { + private void cacheResources(IResource[] resources, String configProperty) { if (resources.length > 0) { ISynchronizePageConfiguration config = getConfiguration(); ArrayList<String> paths = new ArrayList<>(); @@ -507,40 +507,40 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo IResource resource = resources[i]; String path = resource.getFullPath().toString(); if (resource.getType() != IResource.FILE && path.charAt(path.length() - 1) != IPath.SEPARATOR) { - // Include a trailing slash on folders and projects. - // It is used when recreating cached resources that don't exist locally - path += IPath.SEPARATOR; + // Include a trailing slash on folders and projects. + // It is used when recreating cached resources that don't exist locally + path += IPath.SEPARATOR; } - paths.add(path); + paths.add(path); } config.setProperty(configProperty, paths); } else { - clearResourceCache(configProperty); + clearResourceCache(configProperty); } - } + } - private IResource[] getCachedResources(String configProperty) { - List paths = (List)getConfiguration().getProperty(configProperty); - if (paths == null) - return new IResource[0]; + private IResource[] getCachedResources(String configProperty) { + List paths = (List)getConfiguration().getProperty(configProperty); + if (paths == null) + return new IResource[0]; IContainer container = ResourcesPlugin.getWorkspace().getRoot(); ArrayList<IResource> resources = new ArrayList<>(); for (Iterator it = paths.iterator(); it.hasNext();) { String path = (String) it.next(); IResource resource = getResourceForPath(container, path); if (resource != null) { - resources.add(resource); + resources.add(resource); } } return resources.toArray(new IResource[resources.size()]); - } + } - /** - * Save the viewer state (expansion and selection) - */ + /** + * Save the viewer state (expansion and selection) + */ protected void saveViewerState() { // save visible expanded elements and selection - final StructuredViewer viewer = getViewer(); + final StructuredViewer viewer = getViewer(); if (viewer != null && !viewer.getControl().isDisposed() && viewer instanceof AbstractTreeViewer) { //check to see if we should store the checked states of the tree @@ -550,10 +550,10 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo final IResource[][] checkedResources = new IResource[1][0]; viewer.getControl().getDisplay().syncExec(() -> { if (viewer != null && !viewer.getControl().isDisposed()) { - expandedResources[0] = getExpandedResources(); - selectedResources[0] = getSelectedResources(); - if (storeChecks) - checkedResources [0] = getCheckedResources(); + expandedResources[0] = getExpandedResources(); + selectedResources[0] = getSelectedResources(); + if (storeChecks) + checkedResources [0] = getCheckedResources(); } }); @@ -571,15 +571,15 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo */ protected void restoreViewerState() { // restore expansion state and selection state - final StructuredViewer viewer = getViewer(); + final StructuredViewer viewer = getViewer(); if (viewer != null && !viewer.getControl().isDisposed() && viewer instanceof AbstractTreeViewer) { - IResource[] resourcesToExpand = getCachedResources(P_VIEWER_EXPANSION_STATE); - IResource[] resourcesToSelect = getCachedResources(P_VIEWER_SELECTION_STATE); - if (((SynchronizePageConfiguration)configuration).getViewerStyle() == SynchronizePageConfiguration.CHECKBOX){ - IResource[] resourcesToCheck = getCachedResources(P_VIEWER_CHECKED_STATE); - checkResources(resourcesToCheck); - } - expandResources(resourcesToExpand); + IResource[] resourcesToExpand = getCachedResources(P_VIEWER_EXPANSION_STATE); + IResource[] resourcesToSelect = getCachedResources(P_VIEWER_SELECTION_STATE); + if (((SynchronizePageConfiguration)configuration).getViewerStyle() == SynchronizePageConfiguration.CHECKBOX){ + IResource[] resourcesToCheck = getCachedResources(P_VIEWER_CHECKED_STATE); + checkResources(resourcesToCheck); + } + expandResources(resourcesToExpand); selectResources(resourcesToSelect); } } @@ -588,96 +588,96 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo * Select the given resources in the view. This method can * only be invoked from the UI thread. */ - protected void selectResources(IResource[] resourcesToSelect) { - StructuredViewer viewer = getViewer(); - final ArrayList<ISynchronizeModelElement> selectedElements = new ArrayList<>(); - for (int i = 0; i < resourcesToSelect.length; i++) { - IResource resource = resourcesToSelect[i]; - ISynchronizeModelElement[] elements = getModelObjects(resource); - // Only preserve the selection if there is one element for the resource - if (elements.length == 1) { - selectedElements.add(elements[0]); - } - } - if (!selectedElements.isEmpty()) - viewer.setSelection(new StructuredSelection(selectedElements)); - } - - /* + protected void selectResources(IResource[] resourcesToSelect) { + StructuredViewer viewer = getViewer(); + final ArrayList<ISynchronizeModelElement> selectedElements = new ArrayList<>(); + for (int i = 0; i < resourcesToSelect.length; i++) { + IResource resource = resourcesToSelect[i]; + ISynchronizeModelElement[] elements = getModelObjects(resource); + // Only preserve the selection if there is one element for the resource + if (elements.length == 1) { + selectedElements.add(elements[0]); + } + } + if (!selectedElements.isEmpty()) + viewer.setSelection(new StructuredSelection(selectedElements)); + } + + /* * Check the given resources in the view. This method can * only be invoked from the UI thread. */ - protected void checkResources(IResource[] resourcesToCheck) { - Set<ISynchronizeModelElement> checkedElements = new HashSet<>(); - StructuredViewer viewer = getViewer(); - if (!(viewer instanceof CheckboxTreeViewer)) - return; - - for (int j = 0; j < resourcesToCheck.length; j++) { - IResource resource = resourcesToCheck[j]; - if (resource.getType() != IResource.FILE) - continue; - - ISynchronizeModelElement[] elements = getModelObjects(resource); - // Only expand when there is one element per resource - if (elements.length == 1) { - for (int i = 0; i < elements.length; i++) { - ISynchronizeModelElement element = elements[i]; - checkedElements.add(element); - } - } - } - if (!checkedElements.isEmpty()) - ((CheckboxTreeViewer) viewer).setCheckedElements(checkedElements.toArray()); - } - - /* - * Convert a path to a resource by first looking in the resource - * tree and, if that fails, by using the path format to create - * a handle. - */ - private IResource getResourceForPath(IContainer container, String path) { - IResource resource = container.findMember(path, true /* include phantoms */); - if (resource == null) { - try { - // The resource doesn't have an entry on the resources tree - // but may still appear in the view so try to deduce the type - // from the path - if (path.endsWith(Character.toString(IPath.SEPARATOR))) { - resource = container.getFolder(new Path(null, path)); - } else { - resource = container.getFile(new Path(null, path)); - } - } catch (IllegalArgumentException e) { - // Couldn't get a resource handle so ignore - } - } - return resource; - } - - @Override + protected void checkResources(IResource[] resourcesToCheck) { + Set<ISynchronizeModelElement> checkedElements = new HashSet<>(); + StructuredViewer viewer = getViewer(); + if (!(viewer instanceof CheckboxTreeViewer)) + return; + + for (int j = 0; j < resourcesToCheck.length; j++) { + IResource resource = resourcesToCheck[j]; + if (resource.getType() != IResource.FILE) + continue; + + ISynchronizeModelElement[] elements = getModelObjects(resource); + // Only expand when there is one element per resource + if (elements.length == 1) { + for (int i = 0; i < elements.length; i++) { + ISynchronizeModelElement element = elements[i]; + checkedElements.add(element); + } + } + } + if (!checkedElements.isEmpty()) + ((CheckboxTreeViewer) viewer).setCheckedElements(checkedElements.toArray()); + } + + /* + * Convert a path to a resource by first looking in the resource + * tree and, if that fails, by using the path format to create + * a handle. + */ + private IResource getResourceForPath(IContainer container, String path) { + IResource resource = container.findMember(path, true /* include phantoms */); + if (resource == null) { + try { + // The resource doesn't have an entry on the resources tree + // but may still appear in the view so try to deduce the type + // from the path + if (path.endsWith(Character.toString(IPath.SEPARATOR))) { + resource = container.getFolder(new Path(null, path)); + } else { + resource = container.getFile(new Path(null, path)); + } + } catch (IllegalArgumentException e) { + // Couldn't get a resource handle so ignore + } + } + return resource; + } + + @Override public void treeCollapsed(TreeEvent e) { - clearResourceCache(P_VIEWER_EXPANSION_STATE); - } + clearResourceCache(P_VIEWER_EXPANSION_STATE); + } - @Override + @Override public void treeExpanded(TreeEvent e) { - clearResourceCache(P_VIEWER_EXPANSION_STATE); - } + clearResourceCache(P_VIEWER_EXPANSION_STATE); + } - /** + /** * Return all the model objects in this provider that represent the given resource - * @param resource the resource - * @return the model objects for the resource - */ - protected abstract ISynchronizeModelElement[] getModelObjects(IResource resource); + * @param resource the resource + * @return the model objects for the resource + */ + protected abstract ISynchronizeModelElement[] getModelObjects(IResource resource); @Override public void saveState() { saveViewerState(); } - /** + /** * Method invoked when a sync element is added or removed or its state changes. * This method can be invoked from the UI thread or a background thread. * @param element synchronize element @@ -708,41 +708,41 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo */ @Override public void dispose() { - // Only dispose the update handler if it is - // directly associated with this provider - if (isRootProvider()) { - updateHandler.dispose(); - getTree().removeTreeListener(this); - } else { - set.removeSyncSetChangedListener(this); - } - if (actionGroup != null) { - Utils.syncExec((Runnable) () -> actionGroup.dispose(), getViewer()); - } + // Only dispose the update handler if it is + // directly associated with this provider + if (isRootProvider()) { + updateHandler.dispose(); + getTree().removeTreeListener(this); + } else { + set.removeSyncSetChangedListener(this); + } + if (actionGroup != null) { + Utils.syncExec((Runnable) () -> actionGroup.dispose(), getViewer()); + } this.disposed = true; } - private boolean isRootProvider() { - return updateHandler.getProvider() == this; - } + private boolean isRootProvider() { + return updateHandler.getProvider() == this; + } - /** + /** * Return whether this provide has been disposed. - * @return whether this provide has been disposed - */ + * @return whether this provide has been disposed + */ public boolean isDisposed() { - return disposed; - } - - /** - * Return the closest parent elements that represents a model element that - * could contains the given resource. Multiple elements need only be returned - * if two or more logical views are being shown and each view has an element - * that could contain the resource. - * @param resource the resource - * @return one or more lowest level parents that could contain the resource - */ - public abstract ISynchronizeModelElement[] getClosestExistingParents(IResource resource); + return disposed; + } + + /** + * Return the closest parent elements that represents a model element that + * could contains the given resource. Multiple elements need only be returned + * if two or more logical views are being shown and each view has an element + * that could contain the resource. + * @param resource the resource + * @return one or more lowest level parents that could contain the resource + */ + public abstract ISynchronizeModelElement[] getClosestExistingParents(IResource resource); /** * Handle the changes made to the viewer's <code>SyncInfoSet</code>. @@ -758,7 +758,7 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo handleResourceAdditions(event); } - /** + /** * Update the viewer for the sync set additions in the provided event. This * method is invoked by <code>handleChanges(ISyncInfoSetChangeEvent)</code>. * Subclasses may override. @@ -782,30 +782,30 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo */ protected abstract void handleResourceRemovals(ISyncInfoTreeChangeEvent event); - @Override + @Override public void syncInfoChanged(final ISyncInfoSetChangeEvent event, final IProgressMonitor monitor) { if (! (event instanceof ISyncInfoTreeChangeEvent)) { reset(); } else { - updateHandler.runViewUpdate(() -> handleChanges((ISyncInfoTreeChangeEvent)event, monitor), true /* preserve expansion */); + updateHandler.runViewUpdate(() -> handleChanges((ISyncInfoTreeChangeEvent)event, monitor), true /* preserve expansion */); } - } + } - @Override + @Override public void syncInfoSetErrors(SyncInfoSet set, ITeamStatus[] errors, IProgressMonitor monitor) { - // Not handled + // Not handled - } + } - @Override + @Override public void syncInfoSetReset(SyncInfoSet set, IProgressMonitor monitor) { - reset(); - } + reset(); + } protected void addToViewer(ISynchronizeModelElement node) { - if (DEBUG) { - System.out.println("Adding model element " + node.getName()); //$NON-NLS-1$ - } + if (DEBUG) { + System.out.println("Adding model element " + node.getName()); //$NON-NLS-1$ + } propogateConflictState(node, false); // Set the marker property on this node. // There is no need to propagate this to the parents @@ -824,50 +824,50 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo } /* - * Propagate the marker property to the parent if it is not already there. - * Only propagate warnings if the parent isn't an error already. - */ - private void propogateMarkerPropertyToParent(ISynchronizeModelElement node, String property) { - ISynchronizeModelElement parent = (ISynchronizeModelElement)node.getParent(); - if (parent != null - && !parent.getProperty(property) - && !parent.getProperty(ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY)) { - parent.setProperty(property, true); - propogateMarkerPropertyToParent(parent, property); - } - } - - /** + * Propagate the marker property to the parent if it is not already there. + * Only propagate warnings if the parent isn't an error already. + */ + private void propogateMarkerPropertyToParent(ISynchronizeModelElement node, String property) { + ISynchronizeModelElement parent = (ISynchronizeModelElement)node.getParent(); + if (parent != null + && !parent.getProperty(property) + && !parent.getProperty(ISynchronizeModelElement.PROPAGATED_ERROR_MARKER_PROPERTY)) { + parent.setProperty(property, true); + propogateMarkerPropertyToParent(parent, property); + } + } + + /** * Remove any traces of the model element and any of it's descendants in the * hierarchy defined by the content provider from the content provider and * the viewer it is associated with. * @param nodes the model elements to remove */ protected void removeFromViewer(ISynchronizeModelElement[] nodes) { - List<ISynchronizeModelElement> rootsToClear = new ArrayList<>(); - for (int i = 0; i < nodes.length; i++) { - ISynchronizeModelElement node = nodes[i]; - if (DEBUG) { - System.out.println("Removing model element " + node.getName()); //$NON-NLS-1$ - } + List<ISynchronizeModelElement> rootsToClear = new ArrayList<>(); + for (int i = 0; i < nodes.length; i++) { + ISynchronizeModelElement node = nodes[i]; + if (DEBUG) { + System.out.println("Removing model element " + node.getName()); //$NON-NLS-1$ + } ISynchronizeModelElement rootToClear= getRootToClear(node); if (DEBUG) { if (rootToClear != node) { System.out.println("Removing parent element " + rootToClear.getName()); //$NON-NLS-1$ } - } + } propogateConflictState(rootToClear, true /* clear the conflict */); clearModelObjects(rootToClear); rootsToClear.add(rootToClear); - } - ISynchronizeModelElement[] roots = rootsToClear.toArray(new ISynchronizeModelElement[rootsToClear.size()]); + } + ISynchronizeModelElement[] roots = rootsToClear.toArray(new ISynchronizeModelElement[rootsToClear.size()]); if (Utils.canUpdateViewer(getViewer())) { doRemove(roots); } for (int i = 0; i < roots.length; i++) { - ISynchronizeModelElement element = roots[i]; + ISynchronizeModelElement element = roots[i]; updateHandler.nodeRemoved(element, this); - } + } } /** @@ -878,92 +878,92 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo * @param node the root node */ protected final void clearModelObjects(ISynchronizeModelElement node) { - // When clearing model objects, any parents of the node - // That are not out-of-sync, not the model root and that would - // be empty as a result of this clear, should also be cleared. - ISynchronizeModelElement rootToClear = getRootToClear(node); - // Recursively clear the nodes from the root - recursiveClearModelObjects(rootToClear); - if (node == getModelRoot()) { - IDiffElement[] children = node.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - ((SynchronizeModelElement)node).remove(element); - } - } else { - SynchronizeModelElement parent = ((SynchronizeModelElement)node.getParent()); - if (parent != null) parent.remove(node); - } + // When clearing model objects, any parents of the node + // That are not out-of-sync, not the model root and that would + // be empty as a result of this clear, should also be cleared. + ISynchronizeModelElement rootToClear = getRootToClear(node); + // Recursively clear the nodes from the root + recursiveClearModelObjects(rootToClear); + if (node == getModelRoot()) { + IDiffElement[] children = node.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + ((SynchronizeModelElement)node).remove(element); + } + } else { + SynchronizeModelElement parent = ((SynchronizeModelElement)node.getParent()); + if (parent != null) parent.remove(node); + } } /** * Method that subclasses can override when clearing model objects. - * @param node the node to be cleared recursively - */ - protected void recursiveClearModelObjects(ISynchronizeModelElement node) { - // Clear all the children of the node + * @param node the node to be cleared recursively + */ + protected void recursiveClearModelObjects(ISynchronizeModelElement node) { + // Clear all the children of the node IDiffElement[] children = node.getChildren(); for (int i = 0; i < children.length; i++) { IDiffElement element = children[i]; if (element instanceof ISynchronizeModelElement) { - ISynchronizeModelElement sme = (ISynchronizeModelElement) element; - ISynchronizeModelProvider provider = getProvider(sme); - if (provider != null && provider instanceof AbstractSynchronizeModelProvider) { - ((AbstractSynchronizeModelProvider)provider).recursiveClearModelObjects(sme); - } else { - recursiveClearModelObjects(sme); - } + ISynchronizeModelElement sme = (ISynchronizeModelElement) element; + ISynchronizeModelProvider provider = getProvider(sme); + if (provider != null && provider instanceof AbstractSynchronizeModelProvider) { + ((AbstractSynchronizeModelProvider)provider).recursiveClearModelObjects(sme); + } else { + recursiveClearModelObjects(sme); + } } } // Notify the update handler that the node has been cleared if (node != getModelRoot()) updateHandler.modelObjectCleared(node); - } - - /* - * Remove to root should only remove to the root of the provider and not the - * diff tree. - */ - private ISynchronizeModelElement getRootToClear(ISynchronizeModelElement node) { - if (node == getModelRoot()) return node; - ISynchronizeModelElement parent = (ISynchronizeModelElement)node.getParent(); + } + + /* + * Remove to root should only remove to the root of the provider and not the + * diff tree. + */ + private ISynchronizeModelElement getRootToClear(ISynchronizeModelElement node) { + if (node == getModelRoot()) return node; + ISynchronizeModelElement parent = (ISynchronizeModelElement)node.getParent(); if (parent != null && parent != getModelRoot() && !isOutOfSync(parent) && parent.getChildren().length == 1) { - return getRootToClear(parent); + return getRootToClear(parent); } return node; - } - - /* - * Return whether the node represents an out-of-sync resource. - */ - protected boolean isOutOfSync(ISynchronizeModelElement node) { - SyncInfo info = Utils.getSyncInfo(node); - return (info != null && info.getKind() != SyncInfo.IN_SYNC); - } - - protected boolean isOutOfSync(IResource resource) { - SyncInfo info = getSyncInfoSet().getSyncInfo(resource); - return (info != null && info.getKind() != SyncInfo.IN_SYNC); - } - - /** + } + + /* + * Return whether the node represents an out-of-sync resource. + */ + protected boolean isOutOfSync(ISynchronizeModelElement node) { + SyncInfo info = Utils.getSyncInfo(node); + return (info != null && info.getKind() != SyncInfo.IN_SYNC); + } + + protected boolean isOutOfSync(IResource resource) { + SyncInfo info = getSyncInfoSet().getSyncInfo(resource); + return (info != null && info.getKind() != SyncInfo.IN_SYNC); + } + + /** * Return the provider that created and manages the given * model element. The default is to return the receiver. * Subclasses may override. - * @param element the synchronize model element - * @return the provider that created the element - */ - protected ISynchronizeModelProvider getProvider(ISynchronizeModelElement element) { - return this; - } - - /** - * Add the element to the viewer. - * @param parent the parent of the element which is already added to the viewer - * @param element the element to be added to the viewer - */ + * @param element the synchronize model element + * @return the provider that created the element + */ + protected ISynchronizeModelProvider getProvider(ISynchronizeModelElement element) { + return this; + } + + /** + * Add the element to the viewer. + * @param parent the parent of the element which is already added to the viewer + * @param element the element to be added to the viewer + */ protected void doAdd(ISynchronizeModelElement parent, ISynchronizeModelElement element) { - updateHandler.doAdd(parent, element); + updateHandler.doAdd(parent, element); } /** @@ -973,17 +973,17 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo protected void doRemove(ISynchronizeModelElement[] elements) { AbstractTreeViewer viewer = (AbstractTreeViewer)getViewer(); try { - viewer.remove(elements); - } catch (SWTException e) { - // The remove failed due to an SWT exception. Log it and continue - TeamUIPlugin.log(IStatus.ERROR, "An error occurred removing elements from the synchronize view", e); //$NON-NLS-1$ - } - if (DEBUG) { - for (int i = 0; i < elements.length; i++) { - ISynchronizeModelElement element = elements[i]; - System.out.println("Removing view item " + element.getName()); //$NON-NLS-1$ - } - } + viewer.remove(elements); + } catch (SWTException e) { + // The remove failed due to an SWT exception. Log it and continue + TeamUIPlugin.log(IStatus.ERROR, "An error occurred removing elements from the synchronize view", e); //$NON-NLS-1$ + } + if (DEBUG) { + for (int i = 0; i < elements.length; i++) { + ISynchronizeModelElement element = elements[i]; + System.out.println("Removing view item " + element.getName()); //$NON-NLS-1$ + } + } } /** @@ -994,7 +994,7 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo * @param provider the provider that added the node */ protected void nodeAdded(ISynchronizeModelElement node, AbstractSynchronizeModelProvider provider) { - // Default is to do nothing + // Default is to do nothing } /** @@ -1006,46 +1006,46 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo * @param node */ protected void nodeRemoved(ISynchronizeModelElement node, AbstractSynchronizeModelProvider provider) { - // Default is to do nothing + // Default is to do nothing } - /** + /** * This is a callback from the model update handler that gets invoked * when a node is cleared from the model. It is only invoked for the * root level model provider. This callback is deep in the sense that * a callback is sent for each node that is cleared. - * @param node the node that was cleared. - */ - public void modelObjectCleared(ISynchronizeModelElement node) { - // Default is to do nothing - } + * @param node the node that was cleared. + */ + public void modelObjectCleared(ISynchronizeModelElement node) { + // Default is to do nothing + } - @Override + @Override public void addPropertyChangeListener(IPropertyChangeListener listener) { - synchronized (this) { - if (listeners == null) { - listeners = new ListenerList<>(ListenerList.IDENTITY); - } - listeners.add(listener); - } - - } - @Override + synchronized (this) { + if (listeners == null) { + listeners = new ListenerList<>(ListenerList.IDENTITY); + } + listeners.add(listener); + } + + } + @Override public void removePropertyChangeListener(IPropertyChangeListener listener) { - if (listeners != null) { - synchronized (this) { - listeners.remove(listener); - if (listeners.isEmpty()) { - listeners = null; - } - } - } - } + if (listeners != null) { + synchronized (this) { + listeners.remove(listener); + if (listeners.isEmpty()) { + listeners = null; + } + } + } + } protected void firePropertyChange(String key, Object oldValue, Object newValue) { Object[] allListeners; synchronized(this) { - allListeners = listeners.getListeners(); + allListeners = listeners.getListeners(); } final PropertyChangeEvent event = new PropertyChangeEvent(this, key, oldValue, newValue); for (int i = 0; i < allListeners.length; i++) { @@ -1063,13 +1063,13 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo } } - /** - * Wait until the provider is done processing any events and - * the page content are up-to-date. - * This method is for testing purposes only. - * @param monitor - */ - public void waitUntilDone(IProgressMonitor monitor) { + /** + * Wait until the provider is done processing any events and + * the page content are up-to-date. + * This method is for testing purposes only. + * @param monitor + */ + public void waitUntilDone(IProgressMonitor monitor) { monitor.worked(1); // wait for the event handler to process changes. while(updateHandler.getEventHandlerJob().getState() != Job.NONE) { @@ -1081,32 +1081,32 @@ public abstract class AbstractSynchronizeModelProvider implements ISynchronizeMo Policy.checkCanceled(monitor); } monitor.worked(1); - } + } - @Override + @Override public String toString() { - ISynchronizeModelElement element = getModelRoot(); - String name = getClass().getName(); - int index = name.lastIndexOf("."); //$NON-NLS-1$ - if (index != -1) { - name = name.substring(index + 1); - } - String name2 = element.getName(); - if (name2.length() == 0) { - name2 = "/"; //$NON-NLS-1$ - } - return name + ": " + name2; //$NON-NLS-1$ - } - - /** - * Execute a runnable which performs an update of the model being displayed - * by this provider. The runnable should be executed in a thread-safe manner - * which results in the view being updated. - * @param runnable the runnable which updates the model. - * @param preserveExpansion whether the expansion of the view should be preserver - * @param runInUIThread - */ - public void performUpdate(IWorkspaceRunnable runnable, boolean preserveExpansion, boolean runInUIThread) { - updateHandler.performUpdate(runnable, preserveExpansion, runInUIThread); - } + ISynchronizeModelElement element = getModelRoot(); + String name = getClass().getName(); + int index = name.lastIndexOf("."); //$NON-NLS-1$ + if (index != -1) { + name = name.substring(index + 1); + } + String name2 = element.getName(); + if (name2.length() == 0) { + name2 = "/"; //$NON-NLS-1$ + } + return name + ": " + name2; //$NON-NLS-1$ + } + + /** + * Execute a runnable which performs an update of the model being displayed + * by this provider. The runnable should be executed in a thread-safe manner + * which results in the view being updated. + * @param runnable the runnable which updates the model. + * @param preserveExpansion whether the expansion of the view should be preserver + * @param runInUIThread + */ + public void performUpdate(IWorkspaceRunnable runnable, boolean preserveExpansion, boolean runInUIThread) { + updateHandler.performUpdate(runnable, preserveExpansion, runInUIThread); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractTreeViewerAdvisor.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractTreeViewerAdvisor.java index 2f69a6675..734b49f35 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractTreeViewerAdvisor.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/AbstractTreeViewerAdvisor.java @@ -360,7 +360,7 @@ public abstract class AbstractTreeViewerAdvisor extends StructuredViewerAdvisor /* * Allow adding an advisor to the PartNavigator and support coordinated - * navigation between several objects. + * navigation between several objects. * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ @SuppressWarnings("unchecked") diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ActiveChangeSetCollector.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ActiveChangeSetCollector.java index 797249982..6d76eb831 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ActiveChangeSetCollector.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ActiveChangeSetCollector.java @@ -50,301 +50,301 @@ import org.eclipse.team.ui.synchronize.SubscriberParticipant; */ public class ActiveChangeSetCollector implements IDiffChangeListener { - private final ISynchronizePageConfiguration configuration; + private final ISynchronizePageConfiguration configuration; - /* - * Map active change sets to infos displayed by the participant - */ - private final Map<ChangeSet, SyncInfoSet> activeSets = new HashMap<>(); + /* + * Map active change sets to infos displayed by the participant + */ + private final Map<ChangeSet, SyncInfoSet> activeSets = new HashMap<>(); - /* - * Set which contains those changes that are not part of an active set - */ - private SyncInfoTree rootSet = new SyncInfoTree(); + /* + * Set which contains those changes that are not part of an active set + */ + private SyncInfoTree rootSet = new SyncInfoTree(); - private final ChangeSetModelProvider provider; + private final ChangeSetModelProvider provider; - /* - * Listener registered with active change set manager - */ - private IChangeSetChangeListener activeChangeSetListener = new IChangeSetChangeListener() { + /* + * Listener registered with active change set manager + */ + private IChangeSetChangeListener activeChangeSetListener = new IChangeSetChangeListener() { - @Override + @Override public void setAdded(final ChangeSet set) { - // Remove any resources that are in the new set - provider.performUpdate(monitor -> { - remove(set.getResources()); - createSyncInfoSet(set); + // Remove any resources that are in the new set + provider.performUpdate(monitor -> { + remove(set.getResources()); + createSyncInfoSet(set); }, true, true); - } + } - @Override + @Override public void defaultSetChanged(final ChangeSet previousDefault, final ChangeSet set) { - provider.performUpdate(monitor -> { - if (listener != null) - listener.defaultSetChanged(previousDefault, set); + provider.performUpdate(monitor -> { + if (listener != null) + listener.defaultSetChanged(previousDefault, set); }, true, true); - } + } - @Override + @Override public void setRemoved(final ChangeSet set) { - provider.performUpdate(monitor -> { - remove(set); - if (!set.isEmpty()) { - add(getSyncInfos(set).getSyncInfos()); - } + provider.performUpdate(monitor -> { + remove(set); + if (!set.isEmpty()) { + add(getSyncInfos(set).getSyncInfos()); + } }, true, true); - } + } - @Override + @Override public void nameChanged(final ChangeSet set) { - provider.performUpdate(monitor -> { - if (listener != null) - listener.nameChanged(set); + provider.performUpdate(monitor -> { + if (listener != null) + listener.nameChanged(set); }, true, true); - } + } - @Override + @Override public void resourcesChanged(final ChangeSet set, final IPath[] paths) { - // Look for any resources that were removed from the set but are still out-of sync. - // Re-add those resources - final List<SyncInfo> outOfSync = new ArrayList<>(); - for (int i = 0; i < paths.length; i++) { + // Look for any resources that were removed from the set but are still out-of sync. + // Re-add those resources + final List<SyncInfo> outOfSync = new ArrayList<>(); + for (int i = 0; i < paths.length; i++) { IPath path = paths[i]; - if (!((DiffChangeSet)set).contains(path)) { - SyncInfo info = getSyncInfo(path); - if (info != null && info.getKind() != SyncInfo.IN_SYNC) { - outOfSync.add(info); - } - } - } - if (!outOfSync.isEmpty()) { - provider.performUpdate(monitor -> add(outOfSync.toArray(new SyncInfo[outOfSync.size()])), true, true); - } - } - }; - - /** - * Listener that wants to receive change events from this collector - */ - private IChangeSetChangeListener listener; - - public ActiveChangeSetCollector(ISynchronizePageConfiguration configuration, ChangeSetModelProvider provider) { - this.configuration = configuration; - this.provider = provider; - getActiveChangeSetManager().addListener(activeChangeSetListener); - } - - public ISynchronizePageConfiguration getConfiguration() { - return configuration; - } - - public ActiveChangeSetManager getActiveChangeSetManager() { - ISynchronizeParticipant participant = getConfiguration().getParticipant(); - if (participant instanceof IChangeSetProvider) { - return ((IChangeSetProvider)participant).getChangeSetCapability().getActiveChangeSetManager(); - } - return null; - } - - /** - * Re-populate the change sets from the seed set. - * If <code>null</code> is passed, the state - * of the collector is cleared but the set is not - * re-populated. - * <p> - * This method is invoked by the model provider when the - * model provider changes state. It should not - * be invoked by other clients. The model provider - * will invoke this method from a particular thread (which may - * or may not be the UI thread). Updates done to the collector - * from within this thread will be thread-safe and update the view - * properly. Updates done from other threads should use the - * <code>performUpdate</code> method to ensure the view is - * updated properly. - * @param seedSet - */ - public void reset(SyncInfoSet seedSet) { - // First, clean up - rootSet.clear(); - ChangeSet[] sets = activeSets.keySet().toArray(new ChangeSet[activeSets.size()]); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - remove(set); - } - activeSets.clear(); - - // Now re-populate - if (seedSet != null) { - if (getConfiguration().getComparisonType() == ISynchronizePageConfiguration.THREE_WAY) { - // Show all active change sets even if they are empty - sets = getActiveChangeSetManager().getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - add(set); - } - // The above will add all sync info that are contained in sets. - // We still need to add uncontained infos to the root set - SyncInfo[] syncInfos = seedSet.getSyncInfos(); - for (int i = 0; i < syncInfos.length; i++) { - SyncInfo info = syncInfos[i]; - if (isLocalChange(info)) { - ChangeSet[] containingSets = findChangeSets(info); - if (containingSets.length == 0) { - rootSet.add(info); - } - } - } - } else { - add(seedSet.getSyncInfos()); - } - } - } - - /** - * Handle a sync info set change event from the provider's - * seed set. - * <p> - * This method is invoked by the model provider when the - * model provider changes state. It should not - * be invoked by other clients. The model provider - * will invoke this method from a particular thread (which may - * or may not be the UI thread). Updates done to the collector - * from within this thread will be thread-safe and update the view - * properly. Updates done from other threads should use the - * <code>performUpdate</code> method to ensure the view is - * updated properly. - */ - public void handleChange(ISyncInfoSetChangeEvent event) { - List<IResource> removals = new ArrayList<>(); - List<SyncInfo> additions = new ArrayList<>(); - removals.addAll(Arrays.asList(event.getRemovedResources())); - additions.addAll(Arrays.asList(event.getAddedResources())); - SyncInfo[] changed = event.getChangedResources(); - for (int i = 0; i < changed.length; i++) { - SyncInfo info = changed[i]; - additions.add(info); - removals.add(info.getLocal()); - } - if (!removals.isEmpty()) { - remove(removals.toArray(new IResource[removals.size()])); - } - if (!additions.isEmpty()) { - add(additions.toArray(new SyncInfo[additions.size()])); - } - } - - /** - * Remove the given resources from all sets of this collector. - * @param resources the resources to be removed - */ - protected void remove(IResource[] resources) { - for (Iterator iter = activeSets.values().iterator(); iter.hasNext();) { - SyncInfoSet set = (SyncInfoSet) iter.next(); - set.removeAll(resources); - } - rootSet.removeAll(resources); - } - - protected void add(SyncInfo[] infos) { - rootSet.beginInput(); - for (int i = 0; i < infos.length; i++) { - SyncInfo info = infos[i]; - if (isLocalChange(info) && select(info)) { - ChangeSet[] sets = findChangeSets(info); - if (sets.length == 0) { - rootSet.add(info); - } else { - for (int j = 0; j < sets.length; j++) { - ChangeSet set = sets[j]; - SyncInfoSet targetSet = getSyncInfoSet(set); - if (targetSet == null) { - // This will add all the appropriate sync info to the set - createSyncInfoSet(set); - } else { - targetSet.add(info); - } - } - } - } - } - rootSet.endInput(null); - } - - private ChangeSet[] findChangeSets(SyncInfo info) { - ActiveChangeSetManager manager = getActiveChangeSetManager(); - ChangeSet[] sets = manager.getSets(); - List<ChangeSet> result = new ArrayList<>(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - if (set.contains(info.getLocal())) { - result.add(set); - } - } - return result.toArray(new ChangeSet[result.size()]); - } - - /* + if (!((DiffChangeSet)set).contains(path)) { + SyncInfo info = getSyncInfo(path); + if (info != null && info.getKind() != SyncInfo.IN_SYNC) { + outOfSync.add(info); + } + } + } + if (!outOfSync.isEmpty()) { + provider.performUpdate(monitor -> add(outOfSync.toArray(new SyncInfo[outOfSync.size()])), true, true); + } + } + }; + + /** + * Listener that wants to receive change events from this collector + */ + private IChangeSetChangeListener listener; + + public ActiveChangeSetCollector(ISynchronizePageConfiguration configuration, ChangeSetModelProvider provider) { + this.configuration = configuration; + this.provider = provider; + getActiveChangeSetManager().addListener(activeChangeSetListener); + } + + public ISynchronizePageConfiguration getConfiguration() { + return configuration; + } + + public ActiveChangeSetManager getActiveChangeSetManager() { + ISynchronizeParticipant participant = getConfiguration().getParticipant(); + if (participant instanceof IChangeSetProvider) { + return ((IChangeSetProvider)participant).getChangeSetCapability().getActiveChangeSetManager(); + } + return null; + } + + /** + * Re-populate the change sets from the seed set. + * If <code>null</code> is passed, the state + * of the collector is cleared but the set is not + * re-populated. + * <p> + * This method is invoked by the model provider when the + * model provider changes state. It should not + * be invoked by other clients. The model provider + * will invoke this method from a particular thread (which may + * or may not be the UI thread). Updates done to the collector + * from within this thread will be thread-safe and update the view + * properly. Updates done from other threads should use the + * <code>performUpdate</code> method to ensure the view is + * updated properly. + * @param seedSet + */ + public void reset(SyncInfoSet seedSet) { + // First, clean up + rootSet.clear(); + ChangeSet[] sets = activeSets.keySet().toArray(new ChangeSet[activeSets.size()]); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + remove(set); + } + activeSets.clear(); + + // Now re-populate + if (seedSet != null) { + if (getConfiguration().getComparisonType() == ISynchronizePageConfiguration.THREE_WAY) { + // Show all active change sets even if they are empty + sets = getActiveChangeSetManager().getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + add(set); + } + // The above will add all sync info that are contained in sets. + // We still need to add uncontained infos to the root set + SyncInfo[] syncInfos = seedSet.getSyncInfos(); + for (int i = 0; i < syncInfos.length; i++) { + SyncInfo info = syncInfos[i]; + if (isLocalChange(info)) { + ChangeSet[] containingSets = findChangeSets(info); + if (containingSets.length == 0) { + rootSet.add(info); + } + } + } + } else { + add(seedSet.getSyncInfos()); + } + } + } + + /** + * Handle a sync info set change event from the provider's + * seed set. + * <p> + * This method is invoked by the model provider when the + * model provider changes state. It should not + * be invoked by other clients. The model provider + * will invoke this method from a particular thread (which may + * or may not be the UI thread). Updates done to the collector + * from within this thread will be thread-safe and update the view + * properly. Updates done from other threads should use the + * <code>performUpdate</code> method to ensure the view is + * updated properly. + */ + public void handleChange(ISyncInfoSetChangeEvent event) { + List<IResource> removals = new ArrayList<>(); + List<SyncInfo> additions = new ArrayList<>(); + removals.addAll(Arrays.asList(event.getRemovedResources())); + additions.addAll(Arrays.asList(event.getAddedResources())); + SyncInfo[] changed = event.getChangedResources(); + for (int i = 0; i < changed.length; i++) { + SyncInfo info = changed[i]; + additions.add(info); + removals.add(info.getLocal()); + } + if (!removals.isEmpty()) { + remove(removals.toArray(new IResource[removals.size()])); + } + if (!additions.isEmpty()) { + add(additions.toArray(new SyncInfo[additions.size()])); + } + } + + /** + * Remove the given resources from all sets of this collector. + * @param resources the resources to be removed + */ + protected void remove(IResource[] resources) { + for (Iterator iter = activeSets.values().iterator(); iter.hasNext();) { + SyncInfoSet set = (SyncInfoSet) iter.next(); + set.removeAll(resources); + } + rootSet.removeAll(resources); + } + + protected void add(SyncInfo[] infos) { + rootSet.beginInput(); + for (int i = 0; i < infos.length; i++) { + SyncInfo info = infos[i]; + if (isLocalChange(info) && select(info)) { + ChangeSet[] sets = findChangeSets(info); + if (sets.length == 0) { + rootSet.add(info); + } else { + for (int j = 0; j < sets.length; j++) { + ChangeSet set = sets[j]; + SyncInfoSet targetSet = getSyncInfoSet(set); + if (targetSet == null) { + // This will add all the appropriate sync info to the set + createSyncInfoSet(set); + } else { + targetSet.add(info); + } + } + } + } + } + rootSet.endInput(null); + } + + private ChangeSet[] findChangeSets(SyncInfo info) { + ActiveChangeSetManager manager = getActiveChangeSetManager(); + ChangeSet[] sets = manager.getSets(); + List<ChangeSet> result = new ArrayList<>(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + if (set.contains(info.getLocal())) { + result.add(set); + } + } + return result.toArray(new ChangeSet[result.size()]); + } + + /* * Return if this sync info is an outgoing change. */ private boolean isLocalChange(SyncInfo info) { - if (!info.getComparator().isThreeWay()) { - try { - // Obtain the sync info from the subscriber and use it to see if the change is local - info = ((SubscriberChangeSetManager)getActiveChangeSetManager()).getSubscriber().getSyncInfo(info.getLocal()); - } catch (TeamException e) { - TeamUIPlugin.log(e); - } - } + if (!info.getComparator().isThreeWay()) { + try { + // Obtain the sync info from the subscriber and use it to see if the change is local + info = ((SubscriberChangeSetManager)getActiveChangeSetManager()).getSubscriber().getSyncInfo(info.getLocal()); + } catch (TeamException e) { + TeamUIPlugin.log(e); + } + } return (info.getComparator().isThreeWay() - && ((info.getKind() & SyncInfo.DIRECTION_MASK) == SyncInfo.OUTGOING || - (info.getKind() & SyncInfo.DIRECTION_MASK) == SyncInfo.CONFLICTING)); + && ((info.getKind() & SyncInfo.DIRECTION_MASK) == SyncInfo.OUTGOING || + (info.getKind() & SyncInfo.DIRECTION_MASK) == SyncInfo.CONFLICTING)); + } + + public SyncInfoTree getRootSet() { + return rootSet; + } + + /* + * Add the set from the collector. + */ + public void add(ChangeSet set) { + SyncInfoSet targetSet = getSyncInfoSet(set); + if (targetSet == null) { + createSyncInfoSet(set); + } + if (listener != null) { + listener.setAdded(set); + } } - public SyncInfoTree getRootSet() { - return rootSet; - } - - /* - * Add the set from the collector. - */ - public void add(ChangeSet set) { - SyncInfoSet targetSet = getSyncInfoSet(set); - if (targetSet == null) { - createSyncInfoSet(set); - } - if (listener != null) { - listener.setAdded(set); - } - } - - private SyncInfoTree createSyncInfoSet(ChangeSet set) { - SyncInfoTree sis = getSyncInfoSet(set); - // Register the listener last since the add will - // look for new elements - boolean added = false; - // Use a variable to ensure that both begin and end are invoked - try { - if (sis == null) { - sis = new SyncInfoTree(); - activeSets.put(set, sis); - added = true; - } - sis.beginInput(); - if (!sis.isEmpty()) - sis.removeAll(sis.getResources()); - sis.addAll(getSyncInfos(set)); - } finally { - if (sis != null) - sis.endInput(null); - } - if (added) { - ((DiffChangeSet)set).getDiffTree().addDiffChangeListener(this); - if (listener != null) - listener.setAdded(set); - } - return sis; - } + private SyncInfoTree createSyncInfoSet(ChangeSet set) { + SyncInfoTree sis = getSyncInfoSet(set); + // Register the listener last since the add will + // look for new elements + boolean added = false; + // Use a variable to ensure that both begin and end are invoked + try { + if (sis == null) { + sis = new SyncInfoTree(); + activeSets.put(set, sis); + added = true; + } + sis.beginInput(); + if (!sis.isEmpty()) + sis.removeAll(sis.getResources()); + sis.addAll(getSyncInfos(set)); + } finally { + if (sis != null) + sis.endInput(null); + } + if (added) { + ((DiffChangeSet)set).getDiffTree().addDiffChangeListener(this); + if (listener != null) + listener.setAdded(set); + } + return sis; + } private SyncInfoSet getSyncInfos(ChangeSet set) { IDiff[] diffs = ((ResourceDiffTree)((DiffChangeSet)set).getDiffTree()).getDiffs(); @@ -364,7 +364,7 @@ public class ActiveChangeSetCollector implements IDiffChangeListener { return result; } - private SyncInfo asSyncInfo(IDiff diff) { + private SyncInfo asSyncInfo(IDiff diff) { try { return ((SubscriberParticipant)getConfiguration().getParticipant()).getSubscriber().getSyncInfo(ResourceDiffTree.getResourceFor(diff)); } catch (TeamException e) { @@ -374,7 +374,7 @@ public class ActiveChangeSetCollector implements IDiffChangeListener { } private boolean select(IDiff diff) { - return getSeedSet().getSyncInfo(ResourceDiffTree.getResourceFor(diff)) != null; + return getSeedSet().getSyncInfo(ResourceDiffTree.getResourceFor(diff)) != null; } /* private */ SyncInfo getSyncInfo(IPath path) { @@ -404,73 +404,73 @@ public class ActiveChangeSetCollector implements IDiffChangeListener { } /* - * Remove the set from the collector. - */ - public void remove(ChangeSet set) { - ((DiffChangeSet)set).getDiffTree().removeDiffChangeListener(this); - activeSets.remove(set); - if (listener != null) { - listener.setRemoved(set); - } - } - - /* - * Return the sync info set for the given active change set - * or null if there isn't one. - */ - public SyncInfoTree getSyncInfoSet(ChangeSet set) { - return (SyncInfoTree)activeSets.get(set); - } - - private ChangeSet getChangeSet(IDiffTree tree) { - for (Iterator iter = activeSets.keySet().iterator(); iter.hasNext();) { - ChangeSet changeSet = (ChangeSet) iter.next(); - if (((DiffChangeSet)changeSet).getDiffTree() == tree) { - return changeSet; - } - } - return null; - } - - private boolean select(SyncInfo info) { - return getSeedSet().getSyncInfo(info.getLocal()) != null; - } - - private SyncInfoSet getSeedSet() { - return provider.getSyncInfoSet(); - } - - public void dispose() { - getActiveChangeSetManager().removeListener(activeChangeSetListener); - } - - /** - * Set the change set listener for this collector. There is - * only one for this type of collector. - * @param listener change set change listener - */ - public void setChangeSetChangeListener(IChangeSetChangeListener listener) { - this.listener = listener; - if (listener == null) { - getActiveChangeSetManager().removeListener(activeChangeSetListener); - } else { - getActiveChangeSetManager().addListener(activeChangeSetListener); - } - } + * Remove the set from the collector. + */ + public void remove(ChangeSet set) { + ((DiffChangeSet)set).getDiffTree().removeDiffChangeListener(this); + activeSets.remove(set); + if (listener != null) { + listener.setRemoved(set); + } + } + + /* + * Return the sync info set for the given active change set + * or null if there isn't one. + */ + public SyncInfoTree getSyncInfoSet(ChangeSet set) { + return (SyncInfoTree)activeSets.get(set); + } + + private ChangeSet getChangeSet(IDiffTree tree) { + for (Iterator iter = activeSets.keySet().iterator(); iter.hasNext();) { + ChangeSet changeSet = (ChangeSet) iter.next(); + if (((DiffChangeSet)changeSet).getDiffTree() == tree) { + return changeSet; + } + } + return null; + } + + private boolean select(SyncInfo info) { + return getSeedSet().getSyncInfo(info.getLocal()) != null; + } + + private SyncInfoSet getSeedSet() { + return provider.getSyncInfoSet(); + } + + public void dispose() { + getActiveChangeSetManager().removeListener(activeChangeSetListener); + } + + /** + * Set the change set listener for this collector. There is + * only one for this type of collector. + * @param listener change set change listener + */ + public void setChangeSetChangeListener(IChangeSetChangeListener listener) { + this.listener = listener; + if (listener == null) { + getActiveChangeSetManager().removeListener(activeChangeSetListener); + } else { + getActiveChangeSetManager().addListener(activeChangeSetListener); + } + } @Override public void diffsChanged(final IDiffChangeEvent event, IProgressMonitor monitor) { - provider.performUpdate(monitor1 -> { - ChangeSet changeSet = getChangeSet(event.getTree()); - if (changeSet != null) { - SyncInfoSet targetSet = getSyncInfoSet(changeSet); - if (targetSet != null) { - targetSet.removeAll(getResources(targetSet, event.getRemovals())); - targetSet.addAll(asSyncInfoSet(event.getAdditions())); - targetSet.addAll(asSyncInfoSet(event.getChanges())); - rootSet.removeAll(((IResourceDiffTree)event.getTree()).getAffectedResources()); - } - } + provider.performUpdate(monitor1 -> { + ChangeSet changeSet = getChangeSet(event.getTree()); + if (changeSet != null) { + SyncInfoSet targetSet = getSyncInfoSet(changeSet); + if (targetSet != null) { + targetSet.removeAll(getResources(targetSet, event.getRemovals())); + targetSet.addAll(asSyncInfoSet(event.getAdditions())); + targetSet.addAll(asSyncInfoSet(event.getChanges())); + rootSet.removeAll(((IResourceDiffTree)event.getTree()).getAffectedResources()); + } + } }, true /* preserver expansion */, true /* run in UI thread */); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetCapability.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetCapability.java index 69ade459b..c0a1ca9f3 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetCapability.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetCapability.java @@ -27,132 +27,132 @@ import org.eclipse.team.ui.synchronize.SynchronizePageActionGroup; */ public abstract class ChangeSetCapability { - /** - * Return whether the associated participant supports - * the display of checked-in change sets. The default is - * unsupported (<code>false</code>). If subclasses support - * checked-in change sets, they must override the - * <code>createCheckedInChangeSetCollector</code> - * method to return an appropriate values. - * @return whether the associated participant supports - * the display of checked-in change sets - */ - public boolean supportsCheckedInChangeSets() { - return false; - } + /** + * Return whether the associated participant supports + * the display of checked-in change sets. The default is + * unsupported (<code>false</code>). If subclasses support + * checked-in change sets, they must override the + * <code>createCheckedInChangeSetCollector</code> + * method to return an appropriate values. + * @return whether the associated participant supports + * the display of checked-in change sets + */ + public boolean supportsCheckedInChangeSets() { + return false; + } - /** - * Return whether the associated participant supports - * the use of active change sets. The default is unsupported - * (<code>false</code>). If a subclass overrides this method in - * order to support active change sets, they must also override the methods - * <code>getActiveChangeSetManager</code>, - * <code>createChangeSet</code> and <code>editChangeSet</code>. - * @return whether the associated participant supports - * the use of active change sets - */ - public boolean supportsActiveChangeSets() { - return false; - } + /** + * Return whether the associated participant supports + * the use of active change sets. The default is unsupported + * (<code>false</code>). If a subclass overrides this method in + * order to support active change sets, they must also override the methods + * <code>getActiveChangeSetManager</code>, + * <code>createChangeSet</code> and <code>editChangeSet</code>. + * @return whether the associated participant supports + * the use of active change sets + */ + public boolean supportsActiveChangeSets() { + return false; + } - /** - * Return the change set collector that manages the active change - * set for the participant associated with this capability. A <code>null</code> - * is returned if active change sets are not supported. The default is to - * return <code>null</code>. This method must be - * overridden by subclasses that support active change sets. - * @return the change set collector that manages the active change - * set for the participant associated with this capability or - * <code>null</code> if active change sets are not supported. - */ - public ActiveChangeSetManager getActiveChangeSetManager() { - return null; - } + /** + * Return the change set collector that manages the active change + * set for the participant associated with this capability. A <code>null</code> + * is returned if active change sets are not supported. The default is to + * return <code>null</code>. This method must be + * overridden by subclasses that support active change sets. + * @return the change set collector that manages the active change + * set for the participant associated with this capability or + * <code>null</code> if active change sets are not supported. + */ + public ActiveChangeSetManager getActiveChangeSetManager() { + return null; + } - /** - * Create a change set from the given manager that contains the given sync info. - * This method is invoked from the UI thread. A <code>null</code> - * is returned if active change sets are not supported. The default is to - * return <code>null</code>. This method must be - * overridden by subclasses that support active change sets. - * @param configuration the configuration of the page displaying the change sets - * @param diffs the sync info to be added to the change set - * @return the created set. - */ - public ActiveChangeSet createChangeSet(ISynchronizePageConfiguration configuration, IDiff[] diffs) { - return null; - } + /** + * Create a change set from the given manager that contains the given sync info. + * This method is invoked from the UI thread. A <code>null</code> + * is returned if active change sets are not supported. The default is to + * return <code>null</code>. This method must be + * overridden by subclasses that support active change sets. + * @param configuration the configuration of the page displaying the change sets + * @param diffs the sync info to be added to the change set + * @return the created set. + */ + public ActiveChangeSet createChangeSet(ISynchronizePageConfiguration configuration, IDiff[] diffs) { + return null; + } - /** - * Edit the title and comment of the given change set. This method must be - * overridden by subclasses that support active change sets. - * This method is invoked from the UI thread. - * @param configuration the configuration of the page displaying the change sets - * @param set the set to be edited - */ - public void editChangeSet(ISynchronizePageConfiguration configuration, ActiveChangeSet set) { - // Default is to do nothing - } + /** + * Edit the title and comment of the given change set. This method must be + * overridden by subclasses that support active change sets. + * This method is invoked from the UI thread. + * @param configuration the configuration of the page displaying the change sets + * @param set the set to be edited + */ + public void editChangeSet(ISynchronizePageConfiguration configuration, ActiveChangeSet set) { + // Default is to do nothing + } - /** - * Return a collector that can be used to group a set of checked-in changes - * into a set of checked-in change sets. This method must be - * overridden by subclasses that support checked-in change sets. - * @param configuration the configuration for the page that will be displaying the change sets - * @return a change set collector - */ - public SyncInfoSetChangeSetCollector createSyncInfoSetChangeSetCollector(ISynchronizePageConfiguration configuration) { - return null; - } + /** + * Return a collector that can be used to group a set of checked-in changes + * into a set of checked-in change sets. This method must be + * overridden by subclasses that support checked-in change sets. + * @param configuration the configuration for the page that will be displaying the change sets + * @return a change set collector + */ + public SyncInfoSetChangeSetCollector createSyncInfoSetChangeSetCollector(ISynchronizePageConfiguration configuration) { + return null; + } - /** - * Return an action group for contributing context menu items - * to the synchronize page while change sets are enabled. - * Return <code>null</code> if no custom actions are required. - * Note that only context menus can be contributed since the view menu - * and toolbar menu are fixed. This method can be overridden by subclasses - * who wish to support custom change set actions. - * @return an action group for contributing context menu items - * to the synchronize page while change sets are enabled or <code>null</code> - */ - public SynchronizePageActionGroup getActionGroup() { - return null; - } + /** + * Return an action group for contributing context menu items + * to the synchronize page while change sets are enabled. + * Return <code>null</code> if no custom actions are required. + * Note that only context menus can be contributed since the view menu + * and toolbar menu are fixed. This method can be overridden by subclasses + * who wish to support custom change set actions. + * @return an action group for contributing context menu items + * to the synchronize page while change sets are enabled or <code>null</code> + */ + public SynchronizePageActionGroup getActionGroup() { + return null; + } - /** - * Returns whether checked-in change sets should be enabled for the given state - * in the configuration. The default is to enable for three-way incoming mode and - * two-way. - * @param configuration the configuration for a synchronize page - * @return whether checked-in change sets should be enabled for the given state - * in the configuration - */ - public boolean enableCheckedInChangeSetsFor(ISynchronizePageConfiguration configuration) { - return supportsCheckedInChangeSets() && - (configuration.getMode() == ISynchronizePageConfiguration.INCOMING_MODE || - configuration.getComparisonType() == ISynchronizePageConfiguration.TWO_WAY); - } + /** + * Returns whether checked-in change sets should be enabled for the given state + * in the configuration. The default is to enable for three-way incoming mode and + * two-way. + * @param configuration the configuration for a synchronize page + * @return whether checked-in change sets should be enabled for the given state + * in the configuration + */ + public boolean enableCheckedInChangeSetsFor(ISynchronizePageConfiguration configuration) { + return supportsCheckedInChangeSets() && + (configuration.getMode() == ISynchronizePageConfiguration.INCOMING_MODE || + configuration.getComparisonType() == ISynchronizePageConfiguration.TWO_WAY); + } - /** - * Returns whether active change sets should be enabled for the given state - * in the configuration. The default is to enable for three-way outgoing mode. - * @param configuration the configuration for a synchronize page - * @return whether active change sets should be enabled for the given state - * in the configuration - */ - public boolean enableActiveChangeSetsFor(ISynchronizePageConfiguration configuration) { - return supportsActiveChangeSets() && - configuration.getMode() == ISynchronizePageConfiguration.OUTGOING_MODE; - } + /** + * Returns whether active change sets should be enabled for the given state + * in the configuration. The default is to enable for three-way outgoing mode. + * @param configuration the configuration for a synchronize page + * @return whether active change sets should be enabled for the given state + * in the configuration + */ + public boolean enableActiveChangeSetsFor(ISynchronizePageConfiguration configuration) { + return supportsActiveChangeSets() && + configuration.getMode() == ISynchronizePageConfiguration.OUTGOING_MODE; + } - /** - * Return whether change sets should be enabled by default on pages - * that display the participant. - * @return whether change sets should be enabled by default on pages - * that display the participant - */ - public boolean enableChangeSetsByDefault() { - return false; - } + /** + * Return whether change sets should be enabled by default on pages + * that display the participant. + * @return whether change sets should be enabled by default on pages + * that display the participant + */ + public boolean enableChangeSetsByDefault() { + return false; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetDiffNode.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetDiffNode.java index 17476c81b..2077a04a4 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetDiffNode.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetDiffNode.java @@ -25,21 +25,21 @@ import org.eclipse.team.internal.ui.TeamUIPlugin; */ public class ChangeSetDiffNode extends SynchronizeModelElement { - private final ChangeSet set; + private final ChangeSet set; - public ChangeSetDiffNode(IDiffContainer parent, ChangeSet set) { - super(parent); - this.set = set; - } + public ChangeSetDiffNode(IDiffContainer parent, ChangeSet set) { + super(parent); + this.set = set; + } - @Override + @Override public IResource getResource() { - return null; - } + return null; + } - public ChangeSet getSet() { - return set; - } + public ChangeSet getSet() { + return set; + } @Override public ImageDescriptor getImageDescriptor(Object object) { @@ -56,25 +56,25 @@ public class ChangeSetDiffNode extends SynchronizeModelElement { return getName(); } - @Override + @Override public int hashCode() { - return set.hashCode(); - } + return set.hashCode(); + } - @Override + @Override public boolean equals(Object object) { - if (object instanceof ChangeSetDiffNode) { - return((ChangeSetDiffNode)object).getSet() == set; - } - return super.equals(object); - } + if (object instanceof ChangeSetDiffNode) { + return((ChangeSetDiffNode)object).getSet() == set; + } + return super.equals(object); + } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapter) { - if (adapter.equals(ChangeSet.class)) { - return (T) set; - } - return super.getAdapter(adapter); - } + if (adapter.equals(ChangeSet.class)) { + return (T) set; + } + return super.getAdapter(adapter); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetLabelDecorator.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetLabelDecorator.java index 3dae67dcf..60bf1dd88 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetLabelDecorator.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetLabelDecorator.java @@ -38,21 +38,21 @@ public class ChangeSetLabelDecorator extends LabelProvider implements ILabelDeco private Font boldFont; private ActiveChangeSetManager collector; - public ChangeSetLabelDecorator(ISynchronizePageConfiguration configuration) { - ISynchronizeParticipant participant = configuration.getParticipant(); - if (participant instanceof IChangeSetProvider) { - this.collector = ((IChangeSetProvider)participant).getChangeSetCapability().getActiveChangeSetManager(); - } - } + public ChangeSetLabelDecorator(ISynchronizePageConfiguration configuration) { + ISynchronizeParticipant participant = configuration.getParticipant(); + if (participant instanceof IChangeSetProvider) { + this.collector = ((IChangeSetProvider)participant).getChangeSetCapability().getActiveChangeSetManager(); + } + } - @Override + @Override public String decorateText(String input, Object element) { String text = input; if (element instanceof ChangeSetDiffNode) { - ChangeSet set = ((ChangeSetDiffNode)element).getSet(); - if (set instanceof ActiveChangeSet && isDefaultActiveSet((ActiveChangeSet)set)) { - text = NLS.bind(TeamUIMessages.CommitSetDiffNode_0, new String[] { text }); - } + ChangeSet set = ((ChangeSetDiffNode)element).getSet(); + if (set instanceof ActiveChangeSet && isDefaultActiveSet((ActiveChangeSet)set)) { + text = NLS.bind(TeamUIMessages.CommitSetDiffNode_0, new String[] { text }); + } } return text; } @@ -67,9 +67,9 @@ public class ChangeSetLabelDecorator extends LabelProvider implements ILabelDeco @Override public Font decorateFont(Object element) { if (element instanceof ChangeSetDiffNode) { - ChangeSet set = ((ChangeSetDiffNode)element).getSet(); - if (set instanceof ActiveChangeSet && isDefaultActiveSet((ActiveChangeSet)set)) { - if (boldFont == null) { + ChangeSet set = ((ChangeSetDiffNode)element).getSet(); + if (set instanceof ActiveChangeSet && isDefaultActiveSet((ActiveChangeSet)set)) { + if (boldFont == null) { Font defaultFont = JFaceResources.getDefaultFont(); FontData[] data = defaultFont.getFontData(); for (int i = 0; i < data.length; i++) { @@ -78,18 +78,18 @@ public class ChangeSetLabelDecorator extends LabelProvider implements ILabelDeco boldFont = new Font(TeamUIPlugin.getStandardDisplay(), data); } return boldFont; - } + } } return null; } private boolean isDefaultActiveSet(ActiveChangeSet set) { - return collector.isDefault(set); + return collector.isDefault(set); } - @Override + @Override public Image decorateImage(Image image, Object element) { - return image; - } + return image; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelManager.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelManager.java index 26595c5a4..f234c33ae 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelManager.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelManager.java @@ -29,80 +29,80 @@ import org.eclipse.team.ui.synchronize.SynchronizePageActionGroup; */ public class ChangeSetModelManager extends HierarchicalModelManager implements IPropertyChangeListener { - private static final String P_COMMIT_SET_ENABLED = TeamUIPlugin.ID + ".P_COMMIT_SET_ENABLED"; //$NON-NLS-1$ + private static final String P_COMMIT_SET_ENABLED = TeamUIPlugin.ID + ".P_COMMIT_SET_ENABLED"; //$NON-NLS-1$ - public static final String CHANGE_SET_GROUP = "ChangeSet"; //$NON-NLS-1$ + public static final String CHANGE_SET_GROUP = "ChangeSet"; //$NON-NLS-1$ boolean enabled = false; private class ToggleCommitSetAction extends Action { - public ToggleCommitSetAction() { - super(TeamUIMessages.ChangeLogModelManager_0, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_CHANGE_SET)); - setToolTipText(TeamUIMessages.ChangeLogModelManager_0); - update(); - } - @Override + public ToggleCommitSetAction() { + super(TeamUIMessages.ChangeLogModelManager_0, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_CHANGE_SET)); + setToolTipText(TeamUIMessages.ChangeLogModelManager_0); + update(); + } + @Override public void run() { - setCommitSetsEnabled(!enabled); - update(); - } - private void update() { - setChecked(enabled); - } + setCommitSetsEnabled(!enabled); + update(); + } + private void update() { + setChecked(enabled); + } } private ToggleCommitSetAction toggleCommitSetAction; private class CommitSetActionContribution extends SynchronizePageActionGroup { - @Override + @Override public void initialize(ISynchronizePageConfiguration configuration) { super.initialize(configuration); toggleCommitSetAction = new ToggleCommitSetAction(); - appendToGroup( + appendToGroup( ISynchronizePageConfiguration.P_TOOLBAR_MENU, CHANGE_SET_GROUP, toggleCommitSetAction); - updateEnablement(); + updateEnablement(); } } public ChangeSetModelManager(ISynchronizePageConfiguration configuration) { - super(configuration); + super(configuration); configuration.addPropertyChangeListener(this); configuration.addMenuGroup(ISynchronizePageConfiguration.P_TOOLBAR_MENU, CHANGE_SET_GROUP); configuration.addActionContribution(new CommitSetActionContribution()); ChangeSetCapability changeSetCapability = getChangeSetCapability(configuration); - if (changeSetCapability != null && changeSetCapability.supportsActiveChangeSets()) { - configuration.addLabelDecorator(new ChangeSetLabelDecorator(configuration)); + if (changeSetCapability != null && changeSetCapability.supportsActiveChangeSets()) { + configuration.addLabelDecorator(new ChangeSetLabelDecorator(configuration)); } configuration.addPropertyChangeListener(event -> { - if (event.getProperty().equals(ISynchronizePageConfiguration.P_MODE)) { - updateEnablement(); - } + if (event.getProperty().equals(ISynchronizePageConfiguration.P_MODE)) { + updateEnablement(); + } }); } - private ChangeSetCapability getChangeSetCapability(ISynchronizePageConfiguration configuration) { - ISynchronizeParticipant participant = configuration.getParticipant(); - if (participant instanceof IChangeSetProvider) { - IChangeSetProvider provider = (IChangeSetProvider) participant; - return provider.getChangeSetCapability(); - } - return null; - } - - private void updateEnablement() { - if (toggleCommitSetAction != null) { - ISynchronizePageConfiguration configuration = getConfiguration(); - ChangeSetCapability changeSetCapability = getChangeSetCapability(configuration); - boolean enabled = changeSetCapability != null && (changeSetCapability.enableActiveChangeSetsFor(configuration) - || changeSetCapability.enableCheckedInChangeSetsFor(configuration)); - toggleCommitSetAction.setEnabled(enabled); - } - - } + private ChangeSetCapability getChangeSetCapability(ISynchronizePageConfiguration configuration) { + ISynchronizeParticipant participant = configuration.getParticipant(); + if (participant instanceof IChangeSetProvider) { + IChangeSetProvider provider = (IChangeSetProvider) participant; + return provider.getChangeSetCapability(); + } + return null; + } + + private void updateEnablement() { + if (toggleCommitSetAction != null) { + ISynchronizePageConfiguration configuration = getConfiguration(); + ChangeSetCapability changeSetCapability = getChangeSetCapability(configuration); + boolean enabled = changeSetCapability != null && (changeSetCapability.enableActiveChangeSetsFor(configuration) + || changeSetCapability.enableCheckedInChangeSetsFor(configuration)); + toggleCommitSetAction.setEnabled(enabled); + } + + } @Override public void dispose() { @@ -112,61 +112,61 @@ public class ChangeSetModelManager extends HierarchicalModelManager implements I @Override protected ISynchronizeModelProvider createModelProvider(String id) { - if (enabled) { - return new ChangeSetModelProvider(getConfiguration(), getSyncInfoSet(), id); - } else { - return super.createModelProvider(id); - } + if (enabled) { + return new ChangeSetModelProvider(getConfiguration(), getSyncInfoSet(), id); + } else { + return super.createModelProvider(id); + } } - @Override + @Override protected String getSelectedProviderId() { - String id = super.getSelectedProviderId(); - if (id.equals(ChangeSetModelProvider.ChangeSetModelProviderDescriptor.ID)) { - return ((ChangeSetModelProvider)getActiveModelProvider()).getSubproviderId(); - } else { - return id; - } - } + String id = super.getSelectedProviderId(); + if (id.equals(ChangeSetModelProvider.ChangeSetModelProviderDescriptor.ID)) { + return ((ChangeSetModelProvider)getActiveModelProvider()).getSubproviderId(); + } else { + return id; + } + } @Override public void propertyChange(PropertyChangeEvent event) { } - @Override + @Override protected void saveProviderSettings(String id) { - super.saveProviderSettings(id); - IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); + super.saveProviderSettings(id); + IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); if(pageSettings != null) { pageSettings.put(P_COMMIT_SET_ENABLED, enabled); } - } + } - @Override + @Override public void initialize(ISynchronizePageConfiguration configuration) { - // Load our setting before invoking super since the inherited - // initialize will create the provider - IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); - ChangeSetCapability changeSetCapability = getChangeSetCapability(getConfiguration()); - enabled = changeSetCapability != null && changeSetCapability.enableChangeSetsByDefault(); + // Load our setting before invoking super since the inherited + // initialize will create the provider + IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); + ChangeSetCapability changeSetCapability = getChangeSetCapability(getConfiguration()); + enabled = changeSetCapability != null && changeSetCapability.enableChangeSetsByDefault(); if(pageSettings != null && pageSettings.get(P_COMMIT_SET_ENABLED) != null) { - enabled = pageSettings.getBoolean(P_COMMIT_SET_ENABLED); + enabled = pageSettings.getBoolean(P_COMMIT_SET_ENABLED); } - super.initialize(configuration); - } - - /* - * This method is public so it can be invoked from test cases - */ - public void setCommitSetsEnabled(boolean enable) { - if (this.enabled != enable) { - this.enabled = enable; - setInput(getSelectedProviderId(), null); - } - } - - @Override + super.initialize(configuration); + } + + /* + * This method is public so it can be invoked from test cases + */ + public void setCommitSetsEnabled(boolean enable) { + if (this.enabled != enable) { + this.enabled = enable; + setInput(getSelectedProviderId(), null); + } + } + + @Override public ISynchronizeModelProvider getActiveModelProvider() { - return super.getActiveModelProvider(); - } + return super.getActiveModelProvider(); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelProvider.java index 003407375..09084d186 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelProvider.java @@ -42,10 +42,10 @@ import org.eclipse.team.ui.synchronize.SynchronizePageActionGroup; */ public class ChangeSetModelProvider extends CompositeModelProvider { - private ViewerSorter viewerSorter; + private ViewerSorter viewerSorter; // The id of the sub-provider - private final String subProvierId; + private final String subProvierId; private Map<ISynchronizeModelElement, ISynchronizeModelProvider> rootToProvider = new HashMap<>(); @@ -55,43 +55,43 @@ public class ChangeSetModelProvider extends CompositeModelProvider { private IChangeSetChangeListener changeSetListener = new IChangeSetChangeListener() { - @Override + @Override public void setAdded(final ChangeSet set) { - final SyncInfoTree syncInfoSet; - // TODO: May need to be modified to work with two-way - if (set instanceof CheckedInChangeSet) { - syncInfoSet = checkedInCollector.getSyncInfoSet(set); - } else { - syncInfoSet = activeCollector.getSyncInfoSet(set); - } - if (syncInfoSet != null) - createChangeSetModelElement(set, syncInfoSet); - } - - @Override + final SyncInfoTree syncInfoSet; + // TODO: May need to be modified to work with two-way + if (set instanceof CheckedInChangeSet) { + syncInfoSet = checkedInCollector.getSyncInfoSet(set); + } else { + syncInfoSet = activeCollector.getSyncInfoSet(set); + } + if (syncInfoSet != null) + createChangeSetModelElement(set, syncInfoSet); + } + + @Override public void defaultSetChanged(final ChangeSet previousDefault, final ChangeSet set) { - refreshLabel(previousDefault); - refreshLabel(set); - } + refreshLabel(previousDefault); + refreshLabel(set); + } - @Override + @Override public void setRemoved(final ChangeSet set) { - removeModelElementForSet(set); - } + removeModelElementForSet(set); + } - @Override + @Override public void nameChanged(final ChangeSet set) { - refreshLabel(set); - } + refreshLabel(set); + } - @Override + @Override public void resourcesChanged(ChangeSet set, IPath[] paths) { - // The sub-providers listen directly to the sets for changes - // There is no global action to be taken for such changes - } - }; + // The sub-providers listen directly to the sets for changes + // There is no global action to be taken for such changes + } + }; - private ActiveChangeSetCollector activeCollector; + private ActiveChangeSetCollector activeCollector; /* ***************************************************************************** * Descriptor for this model provider @@ -113,288 +113,288 @@ public class ChangeSetModelProvider extends CompositeModelProvider { }; private static final ChangeSetModelProviderDescriptor descriptor = new ChangeSetModelProviderDescriptor(); - protected ChangeSetModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set, String subProvierId) { - super(configuration, set); - this.subProvierId = subProvierId; - ChangeSetCapability changeSetCapability = getChangeSetCapability(); - if (changeSetCapability.supportsCheckedInChangeSets()) { - checkedInCollector = changeSetCapability.createSyncInfoSetChangeSetCollector(configuration); - checkedInCollector.setProvider(this); - checkedInCollector.addListener(changeSetListener); - } - if (changeSetCapability.supportsActiveChangeSets()) { - activeCollector = new ActiveChangeSetCollector(configuration, this); - activeCollector.setChangeSetChangeListener(changeSetListener); - configuration.addMenuGroup(ISynchronizePageConfiguration.P_CONTEXT_MENU, ChangeSetActionGroup.CHANGE_SET_GROUP); - } - } - - @Override + protected ChangeSetModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set, String subProvierId) { + super(configuration, set); + this.subProvierId = subProvierId; + ChangeSetCapability changeSetCapability = getChangeSetCapability(); + if (changeSetCapability.supportsCheckedInChangeSets()) { + checkedInCollector = changeSetCapability.createSyncInfoSetChangeSetCollector(configuration); + checkedInCollector.setProvider(this); + checkedInCollector.addListener(changeSetListener); + } + if (changeSetCapability.supportsActiveChangeSets()) { + activeCollector = new ActiveChangeSetCollector(configuration, this); + activeCollector.setChangeSetChangeListener(changeSetListener); + configuration.addMenuGroup(ISynchronizePageConfiguration.P_CONTEXT_MENU, ChangeSetActionGroup.CHANGE_SET_GROUP); + } + } + + @Override protected void handleChanges(ISyncInfoTreeChangeEvent event, IProgressMonitor monitor) { - boolean handled = false; - if (checkedInCollector != null && getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { - checkedInCollector.handleChange(event); - handled = true; - } - if (activeCollector != null && getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { - activeCollector.handleChange(event); - handled = true; - } - if (!handled) { - // Forward the event to the root provider - ISynchronizeModelProvider provider = getProviderRootedAt(getModelRoot()); - if (provider != null) { - SyncInfoSet set = provider.getSyncInfoSet(); - try { - set.beginInput(); - set.removeAll(event.getRemovedResources()); - SyncInfo[] added = event.getAddedResources(); - for (int i = 0; i < added.length; i++) { - SyncInfo info = added[i]; - set.add(info); - } - SyncInfo[] changed = event.getChangedResources(); - for (int i = 0; i < changed.length; i++) { - SyncInfo info = changed[i]; - set.add(info); - } - } finally { - set.endInput(monitor); - } - } - } - } - - @Override + boolean handled = false; + if (checkedInCollector != null && getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { + checkedInCollector.handleChange(event); + handled = true; + } + if (activeCollector != null && getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { + activeCollector.handleChange(event); + handled = true; + } + if (!handled) { + // Forward the event to the root provider + ISynchronizeModelProvider provider = getProviderRootedAt(getModelRoot()); + if (provider != null) { + SyncInfoSet set = provider.getSyncInfoSet(); + try { + set.beginInput(); + set.removeAll(event.getRemovedResources()); + SyncInfo[] added = event.getAddedResources(); + for (int i = 0; i < added.length; i++) { + SyncInfo info = added[i]; + set.add(info); + } + SyncInfo[] changed = event.getChangedResources(); + for (int i = 0; i < changed.length; i++) { + SyncInfo info = changed[i]; + set.add(info); + } + } finally { + set.endInput(monitor); + } + } + } + } + + @Override protected void handleAddition(SyncInfo info) { - // Nothing to do since change handling was bypassed - } + // Nothing to do since change handling was bypassed + } - @Override + @Override protected IDiffElement[] buildModelObjects(ISynchronizeModelElement node) { - // This method is invoked on a reset after the provider state has been cleared. - // Resetting the collector will rebuild the model + // This method is invoked on a reset after the provider state has been cleared. + // Resetting the collector will rebuild the model if (node == getModelRoot()) { - // First, disable the collectors - if (checkedInCollector != null) { - checkedInCollector.reset(null); - checkedInCollector.removeListener(changeSetListener); - } - if (activeCollector != null) { - activeCollector.setChangeSetChangeListener(null); - activeCollector.reset(null); - } - - // Then, re-enable the proper collection method - boolean handled = false; - if (checkedInCollector != null && getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { - checkedInCollector.addListener(changeSetListener); - checkedInCollector.reset(getSyncInfoSet()); - handled = true; - } - if (activeCollector != null && getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { - activeCollector.setChangeSetChangeListener(changeSetListener); - activeCollector.reset(getSyncInfoSet()); - handled = true; - } - if (!handled) { - // Forward the sync info to the root provider and trigger a build - ISynchronizeModelProvider provider = getProviderRootedAt(getModelRoot()); - if (provider != null) { - ((SynchronizeModelProvider)provider).getSyncInfoSet().addAll(getSyncInfoSet()); - } - } + // First, disable the collectors + if (checkedInCollector != null) { + checkedInCollector.reset(null); + checkedInCollector.removeListener(changeSetListener); + } + if (activeCollector != null) { + activeCollector.setChangeSetChangeListener(null); + activeCollector.reset(null); + } + + // Then, re-enable the proper collection method + boolean handled = false; + if (checkedInCollector != null && getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { + checkedInCollector.addListener(changeSetListener); + checkedInCollector.reset(getSyncInfoSet()); + handled = true; + } + if (activeCollector != null && getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { + activeCollector.setChangeSetChangeListener(changeSetListener); + activeCollector.reset(getSyncInfoSet()); + handled = true; + } + if (!handled) { + // Forward the sync info to the root provider and trigger a build + ISynchronizeModelProvider provider = getProviderRootedAt(getModelRoot()); + if (provider != null) { + ((SynchronizeModelProvider)provider).getSyncInfoSet().addAll(getSyncInfoSet()); + } + } } return new IDiffElement[0]; - } + } - @Override + @Override public ISynchronizeModelProviderDescriptor getDescriptor() { - return descriptor; - } + return descriptor; + } - @Override + @Override public ViewerSorter getViewerSorter() { - if (viewerSorter == null) { - viewerSorter = new ChangeSetModelSorter(this, ChangeSetActionGroup.getSortCriteria(getConfiguration())); - } - return viewerSorter; - } - - /* - * Method to allow ChangeSetActionGroup to set the viewer sorter of this provider. - */ - public void setViewerSorter(ViewerSorter viewerSorter) { - this.viewerSorter = viewerSorter; - firePropertyChange(ISynchronizeModelProvider.P_VIEWER_SORTER, null, null); - } - - @Override + if (viewerSorter == null) { + viewerSorter = new ChangeSetModelSorter(this, ChangeSetActionGroup.getSortCriteria(getConfiguration())); + } + return viewerSorter; + } + + /* + * Method to allow ChangeSetActionGroup to set the viewer sorter of this provider. + */ + public void setViewerSorter(ViewerSorter viewerSorter) { + this.viewerSorter = viewerSorter; + firePropertyChange(ISynchronizeModelProvider.P_VIEWER_SORTER, null, null); + } + + @Override protected SynchronizePageActionGroup createActionGroup() { - return new ChangeSetActionGroup(this); - } + return new ChangeSetActionGroup(this); + } - private ISynchronizeModelProvider createProviderRootedAt(ISynchronizeModelElement parent, SyncInfoTree set) { - ISynchronizeModelProvider provider = createModelProvider(parent, getSubproviderId(), set); - addProvider(provider); - rootToProvider.put(parent, provider); - return provider; - } + private ISynchronizeModelProvider createProviderRootedAt(ISynchronizeModelElement parent, SyncInfoTree set) { + ISynchronizeModelProvider provider = createModelProvider(parent, getSubproviderId(), set); + addProvider(provider); + rootToProvider.put(parent, provider); + return provider; + } - private ISynchronizeModelProvider getProviderRootedAt(ISynchronizeModelElement parent) { - return rootToProvider.get(parent); - } + private ISynchronizeModelProvider getProviderRootedAt(ISynchronizeModelElement parent) { + return rootToProvider.get(parent); + } - @Override + @Override protected void removeProvider(ISynchronizeModelProvider provider) { - rootToProvider.remove(provider.getModelRoot()); - super.removeProvider(provider); - } - - /** - * Return the id of the sub-provider used by the commit set provider. - * @return the id of the sub-provider used by the commit set provider - */ - public String getSubproviderId() { - return subProvierId; - } - - /** - * Return the sorter associated with the sub-provider being used. - * @return the sorter associated with the sub-provider being used - */ - public ViewerSorter getEmbeddedSorter() { - return embeddedSorter; - } - - @Override + rootToProvider.remove(provider.getModelRoot()); + super.removeProvider(provider); + } + + /** + * Return the id of the sub-provider used by the commit set provider. + * @return the id of the sub-provider used by the commit set provider + */ + public String getSubproviderId() { + return subProvierId; + } + + /** + * Return the sorter associated with the sub-provider being used. + * @return the sorter associated with the sub-provider being used + */ + public ViewerSorter getEmbeddedSorter() { + return embeddedSorter; + } + + @Override protected void recursiveClearModelObjects(ISynchronizeModelElement node) { - super.recursiveClearModelObjects(node); - if (node == getModelRoot()) { - rootToProvider.clear(); - // Throw away the embedded sorter - embeddedSorter = null; - createRootProvider(); - } - } - - /* - * Create the root subprovider which is used to display resources - * that are not in a commit set. This provider is created even if - * it is empty so we can have access to the appropriate sorter - * and action group - */ - private void createRootProvider() { - // Recreate the sub-provider at the root and use it's viewer sorter and action group - SyncInfoTree tree; - if (activeCollector != null && getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { - // When in outgoing mode, use the root set of the active change set collector at the root - tree = activeCollector.getRootSet(); - } else { - tree = new SyncInfoTree(); - } - final ISynchronizeModelProvider provider = createProviderRootedAt(getModelRoot(), tree); - embeddedSorter = provider.getViewerSorter(); - if (provider instanceof AbstractSynchronizeModelProvider) { - SynchronizePageActionGroup actionGroup = ((AbstractSynchronizeModelProvider)provider).getActionGroup(); - if (actionGroup != null) { - // This action group will be disposed when the provider is disposed - getConfiguration().addActionContribution(actionGroup); - provider.addPropertyChangeListener(event -> { - if (event.getProperty().equals(P_VIEWER_SORTER)) { - embeddedSorter = provider.getViewerSorter(); - ChangeSetModelProvider.this.firePropertyChange(P_VIEWER_SORTER, null, null); - } + super.recursiveClearModelObjects(node); + if (node == getModelRoot()) { + rootToProvider.clear(); + // Throw away the embedded sorter + embeddedSorter = null; + createRootProvider(); + } + } + + /* + * Create the root subprovider which is used to display resources + * that are not in a commit set. This provider is created even if + * it is empty so we can have access to the appropriate sorter + * and action group + */ + private void createRootProvider() { + // Recreate the sub-provider at the root and use it's viewer sorter and action group + SyncInfoTree tree; + if (activeCollector != null && getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { + // When in outgoing mode, use the root set of the active change set collector at the root + tree = activeCollector.getRootSet(); + } else { + tree = new SyncInfoTree(); + } + final ISynchronizeModelProvider provider = createProviderRootedAt(getModelRoot(), tree); + embeddedSorter = provider.getViewerSorter(); + if (provider instanceof AbstractSynchronizeModelProvider) { + SynchronizePageActionGroup actionGroup = ((AbstractSynchronizeModelProvider)provider).getActionGroup(); + if (actionGroup != null) { + // This action group will be disposed when the provider is disposed + getConfiguration().addActionContribution(actionGroup); + provider.addPropertyChangeListener(event -> { + if (event.getProperty().equals(P_VIEWER_SORTER)) { + embeddedSorter = provider.getViewerSorter(); + ChangeSetModelProvider.this.firePropertyChange(P_VIEWER_SORTER, null, null); + } }); - } - } - } - - /* - * Find the root element for the given change set. - * A linear search is used. - */ - protected ISynchronizeModelElement getModelElement(ChangeSet set) { - IDiffElement[] children = getModelRoot().getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - if (element instanceof ChangeSetDiffNode && ((ChangeSetDiffNode)element).getSet() == set) { - return (ISynchronizeModelElement)element; - } - } - return null; - } - - /* - * Return the change set capability - */ - public ChangeSetCapability getChangeSetCapability() { - ISynchronizeParticipant participant = getConfiguration().getParticipant(); - if (participant instanceof IChangeSetProvider) { - IChangeSetProvider provider = (IChangeSetProvider) participant; - return provider.getChangeSetCapability(); - } - return null; - } - - @Override + } + } + } + + /* + * Find the root element for the given change set. + * A linear search is used. + */ + protected ISynchronizeModelElement getModelElement(ChangeSet set) { + IDiffElement[] children = getModelRoot().getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + if (element instanceof ChangeSetDiffNode && ((ChangeSetDiffNode)element).getSet() == set) { + return (ISynchronizeModelElement)element; + } + } + return null; + } + + /* + * Return the change set capability + */ + public ChangeSetCapability getChangeSetCapability() { + ISynchronizeParticipant participant = getConfiguration().getParticipant(); + if (participant instanceof IChangeSetProvider) { + IChangeSetProvider provider = (IChangeSetProvider) participant; + return provider.getChangeSetCapability(); + } + return null; + } + + @Override public void dispose() { - if (checkedInCollector != null) { - checkedInCollector.removeListener(changeSetListener); - checkedInCollector.dispose(); - } - if (activeCollector != null) { - activeCollector.setChangeSetChangeListener(null); - activeCollector.dispose(); - } - super.dispose(); - } - - - @Override + if (checkedInCollector != null) { + checkedInCollector.removeListener(changeSetListener); + checkedInCollector.dispose(); + } + if (activeCollector != null) { + activeCollector.setChangeSetChangeListener(null); + activeCollector.dispose(); + } + super.dispose(); + } + + + @Override public void waitUntilDone(IProgressMonitor monitor) { - super.waitUntilDone(monitor); - if (checkedInCollector != null) { - checkedInCollector.waitUntilDone(monitor); - // Wait for the provider again since the change set handler may have queued UI updates - super.waitUntilDone(monitor); - } - } - - void removeModelElementForSet(final ChangeSet set) { - ISynchronizeModelElement node = getModelElement(set); - if (node != null) { - ISynchronizeModelProvider provider = getProviderRootedAt(node); - removeFromViewer(new ISynchronizeModelElement[] { node }); - removeProvider(provider); - } - } - - public void createChangeSetModelElement(ChangeSet set, SyncInfoTree tree) { - // Add the model element and provider for the set - ISynchronizeModelElement node = getModelElement(set); - ISynchronizeModelProvider provider = null; - if (node != null) { - provider = getProviderRootedAt(node); - } - if (provider == null) { - provider = createProvider(set, tree); - provider.prepareInput(null); - } - } - - private ISynchronizeModelProvider createProvider(ChangeSet set, SyncInfoTree tree) { - ChangeSetDiffNode node = new ChangeSetDiffNode(getModelRoot(), set); - addToViewer(node); - return createProviderRootedAt(node, tree); - } - - public void refreshLabel(ChangeSet set) { - ISynchronizeModelElement node = getModelElement(set); - if (node != null) { - getViewer().refresh(node); - } - } + super.waitUntilDone(monitor); + if (checkedInCollector != null) { + checkedInCollector.waitUntilDone(monitor); + // Wait for the provider again since the change set handler may have queued UI updates + super.waitUntilDone(monitor); + } + } + + void removeModelElementForSet(final ChangeSet set) { + ISynchronizeModelElement node = getModelElement(set); + if (node != null) { + ISynchronizeModelProvider provider = getProviderRootedAt(node); + removeFromViewer(new ISynchronizeModelElement[] { node }); + removeProvider(provider); + } + } + + public void createChangeSetModelElement(ChangeSet set, SyncInfoTree tree) { + // Add the model element and provider for the set + ISynchronizeModelElement node = getModelElement(set); + ISynchronizeModelProvider provider = null; + if (node != null) { + provider = getProviderRootedAt(node); + } + if (provider == null) { + provider = createProvider(set, tree); + provider.prepareInput(null); + } + } + + private ISynchronizeModelProvider createProvider(ChangeSet set, SyncInfoTree tree) { + ChangeSetDiffNode node = new ChangeSetDiffNode(getModelRoot(), set); + addToViewer(node); + return createProviderRootedAt(node, tree); + } + + public void refreshLabel(ChangeSet set) { + ISynchronizeModelElement node = getModelElement(set); + if (node != null) { + getViewer().refresh(node); + } + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelSorter.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelSorter.java index 63c91f990..1914bed1e 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelSorter.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ChangeSetModelSorter.java @@ -44,11 +44,11 @@ public class ChangeSetModelSorter extends ViewerSorter { protected int classComparison(Object element) { if (element instanceof ChangeSetDiffNode) { - ChangeSet set = ((ChangeSetDiffNode)element).getSet(); - if (set instanceof ActiveChangeSet) { - return 0; - } - return 1; + ChangeSet set = ((ChangeSetDiffNode)element).getSet(); + if (set instanceof ActiveChangeSet) { + return 0; + } + return 1; } return 2; } @@ -75,14 +75,14 @@ public class ChangeSetModelSorter extends ViewerSorter { //if one or both objects are not resources, returned a comparison //based on class. if (o1 instanceof ChangeSetDiffNode && o2 instanceof ChangeSetDiffNode) { - ChangeSet s1 = ((ChangeSetDiffNode) o1).getSet(); - ChangeSet s2 = ((ChangeSetDiffNode) o2).getSet(); - if (s1 instanceof ActiveChangeSet && s2 instanceof ActiveChangeSet) { - return compareNames(((ActiveChangeSet)s1).getTitle(), ((ActiveChangeSet)s2).getTitle()); - } - if (s1 instanceof CheckedInChangeSet && s2 instanceof CheckedInChangeSet) { - CheckedInChangeSet r1 = (CheckedInChangeSet)s1; - CheckedInChangeSet r2 = (CheckedInChangeSet)s2; + ChangeSet s1 = ((ChangeSetDiffNode) o1).getSet(); + ChangeSet s2 = ((ChangeSetDiffNode) o2).getSet(); + if (s1 instanceof ActiveChangeSet && s2 instanceof ActiveChangeSet) { + return compareNames(((ActiveChangeSet)s1).getTitle(), ((ActiveChangeSet)s2).getTitle()); + } + if (s1 instanceof CheckedInChangeSet && s2 instanceof CheckedInChangeSet) { + CheckedInChangeSet r1 = (CheckedInChangeSet)s1; + CheckedInChangeSet r2 = (CheckedInChangeSet)s2; if (commentCriteria == DATE) return compareDates(r1.getDate(), r2.getDate()); else if (commentCriteria == COMMENT) @@ -91,25 +91,25 @@ public class ChangeSetModelSorter extends ViewerSorter { return compareNames(r1.getAuthor(), r2.getAuthor()); else return 0; - } - if (s1 instanceof ActiveChangeSet) { - return -1; - } else if (s2 instanceof ActiveChangeSet) { - return 1; - } - if (s1 instanceof CheckedInChangeSet) { - return -1; - } else if (s2 instanceof CheckedInChangeSet) { - return 1; - } + } + if (s1 instanceof ActiveChangeSet) { + return -1; + } else if (s2 instanceof ActiveChangeSet) { + return 1; + } + if (s1 instanceof CheckedInChangeSet) { + return -1; + } else if (s2 instanceof CheckedInChangeSet) { + return 1; + } } if (o1 instanceof ISynchronizeModelElement && o2 instanceof ISynchronizeModelElement) { ViewerSorter embeddedSorter = provider.getEmbeddedSorter(); if (embeddedSorter != null) { - return embeddedSorter.compare(viewer, o1, o2); + return embeddedSorter.compare(viewer, o1, o2); } else { - return compareNames(((ISynchronizeModelElement)o1).getName(), ((ISynchronizeModelElement)o2).getName()); + return compareNames(((ISynchronizeModelElement)o1).getName(), ((ISynchronizeModelElement)o2).getName()); } } else if (o1 instanceof ISynchronizeModelElement) return 1; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompositeModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompositeModelProvider.java index e6d15e509..e3a55a7f2 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompositeModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompositeModelProvider.java @@ -36,160 +36,160 @@ import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; */ public abstract class CompositeModelProvider extends AbstractSynchronizeModelProvider { - private final List<ISynchronizeModelProvider> providers = new ArrayList<>(); - private final Map<IResource, List <ISynchronizeModelElement>> resourceToElements = new HashMap<>(); - private final Map<ISynchronizeModelElement, AbstractSynchronizeModelProvider> elementToProvider = new HashMap<>(); + private final List<ISynchronizeModelProvider> providers = new ArrayList<>(); + private final Map<IResource, List <ISynchronizeModelElement>> resourceToElements = new HashMap<>(); + private final Map<ISynchronizeModelElement, AbstractSynchronizeModelProvider> elementToProvider = new HashMap<>(); - protected CompositeModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set) { - super(configuration, set); - } + protected CompositeModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set) { + super(configuration, set); + } - /** - * Add the provider to the list of providers. - * @param provider the provider to be added - */ - protected void addProvider(ISynchronizeModelProvider provider) { - providers.add(provider); - } + /** + * Add the provider to the list of providers. + * @param provider the provider to be added + */ + protected void addProvider(ISynchronizeModelProvider provider) { + providers.add(provider); + } - /** - * Remove the provider from the list of providers. - * @param provider the provider to be removed - */ - protected void removeProvider(ISynchronizeModelProvider provider) { - providers.remove(provider); - provider.dispose(); - } + /** + * Remove the provider from the list of providers. + * @param provider the provider to be removed + */ + protected void removeProvider(ISynchronizeModelProvider provider) { + providers.remove(provider); + provider.dispose(); + } - @Override + @Override protected ISynchronizeModelProvider getProvider(ISynchronizeModelElement element) { - return elementToProvider.get(element); - } + return elementToProvider.get(element); + } - @Override + @Override public ISynchronizeModelElement[] getClosestExistingParents(IResource resource) { - ISynchronizeModelProvider[] providers = getProviders(); - if (providers.length == 0) { - return new ISynchronizeModelElement[0]; - } - if (providers.length == 1 && providers[0] instanceof AbstractSynchronizeModelProvider) { - return ((AbstractSynchronizeModelProvider)providers[0]).getClosestExistingParents(resource); - } - List<ISynchronizeModelElement> result = new ArrayList<>(); - for (int i = 0; i < providers.length; i++) { - ISynchronizeModelProvider provider = providers[i]; - if (provider instanceof AbstractSynchronizeModelProvider) { - ISynchronizeModelElement[] elements = ((AbstractSynchronizeModelProvider)provider).getClosestExistingParents(resource); - for (int j = 0; j < elements.length; j++) { - ISynchronizeModelElement element = elements[j]; - result.add(element); - } - } - } - return result.toArray(new ISynchronizeModelElement[result.size()]); - } + ISynchronizeModelProvider[] providers = getProviders(); + if (providers.length == 0) { + return new ISynchronizeModelElement[0]; + } + if (providers.length == 1 && providers[0] instanceof AbstractSynchronizeModelProvider) { + return ((AbstractSynchronizeModelProvider)providers[0]).getClosestExistingParents(resource); + } + List<ISynchronizeModelElement> result = new ArrayList<>(); + for (int i = 0; i < providers.length; i++) { + ISynchronizeModelProvider provider = providers[i]; + if (provider instanceof AbstractSynchronizeModelProvider) { + ISynchronizeModelElement[] elements = ((AbstractSynchronizeModelProvider)provider).getClosestExistingParents(resource); + for (int j = 0; j < elements.length; j++) { + ISynchronizeModelElement element = elements[j]; + result.add(element); + } + } + } + return result.toArray(new ISynchronizeModelElement[result.size()]); + } - /** - * Return all the sub-providers of this composite. - * @return the sub-providers of this composite - */ - protected ISynchronizeModelProvider[] getProviders() { - return providers.toArray(new ISynchronizeModelProvider[providers.size()]); - } + /** + * Return all the sub-providers of this composite. + * @return the sub-providers of this composite + */ + protected ISynchronizeModelProvider[] getProviders() { + return providers.toArray(new ISynchronizeModelProvider[providers.size()]); + } - /** - * Return the providers that are displaying the given resource. - * @param resource the resource - * @return the providers displaying the resource - */ - protected ISynchronizeModelProvider[] getProvidersContaining(IResource resource) { - List<ISynchronizeModelElement> elements = resourceToElements.get(resource); - if (elements == null || elements.isEmpty()) { - return new ISynchronizeModelProvider[0]; - } - List<ISynchronizeModelProvider> result = new ArrayList<>(); - for (Iterator<ISynchronizeModelElement> iter = elements.iterator(); iter.hasNext();) { - ISynchronizeModelElement element = iter.next(); - result.add(getProvider(element)); - } - return result.toArray(new ISynchronizeModelProvider[result.size()]); - } + /** + * Return the providers that are displaying the given resource. + * @param resource the resource + * @return the providers displaying the resource + */ + protected ISynchronizeModelProvider[] getProvidersContaining(IResource resource) { + List<ISynchronizeModelElement> elements = resourceToElements.get(resource); + if (elements == null || elements.isEmpty()) { + return new ISynchronizeModelProvider[0]; + } + List<ISynchronizeModelProvider> result = new ArrayList<>(); + for (Iterator<ISynchronizeModelElement> iter = elements.iterator(); iter.hasNext();) { + ISynchronizeModelElement element = iter.next(); + result.add(getProvider(element)); + } + return result.toArray(new ISynchronizeModelProvider[result.size()]); + } - @Override + @Override protected final void handleResourceAdditions(ISyncInfoTreeChangeEvent event) { - handleAdditions(event.getAddedResources()); - } + handleAdditions(event.getAddedResources()); + } - /** - * Handle the resource additions by adding them to any existing - * sub-providers or by creating addition sub-providers as needed. - * @param resources - */ - protected void handleAdditions(SyncInfo[] resources) { - for (int i = 0; i < resources.length; i++) { - SyncInfo info = resources[i]; - handleAddition(info); - } - } + /** + * Handle the resource additions by adding them to any existing + * sub-providers or by creating addition sub-providers as needed. + * @param resources + */ + protected void handleAdditions(SyncInfo[] resources) { + for (int i = 0; i < resources.length; i++) { + SyncInfo info = resources[i]; + handleAddition(info); + } + } - /** - * Handle the addition of the given sync info to this provider - * @param info the added sync info - */ - protected abstract void handleAddition(SyncInfo info); + /** + * Handle the addition of the given sync info to this provider + * @param info the added sync info + */ + protected abstract void handleAddition(SyncInfo info); - @Override + @Override protected final void handleResourceChanges(ISyncInfoTreeChangeEvent event) { - SyncInfo[] infos = event.getChangedResources(); - for (int i = 0; i < infos.length; i++) { - SyncInfo info = infos[i]; - handleChange(info); - } - } + SyncInfo[] infos = event.getChangedResources(); + for (int i = 0; i < infos.length; i++) { + SyncInfo info = infos[i]; + handleChange(info); + } + } - /** - * The state of the sync info for a resource has changed. Propagate the - * change to any sub-providers that contain the resource. - * @param info the sync info for the resource whose sync state has changed - */ - protected void handleChange(SyncInfo info) { - handleRemoval(info.getLocal()); - handleAddition(info); - } + /** + * The state of the sync info for a resource has changed. Propagate the + * change to any sub-providers that contain the resource. + * @param info the sync info for the resource whose sync state has changed + */ + protected void handleChange(SyncInfo info) { + handleRemoval(info.getLocal()); + handleAddition(info); + } - @Override + @Override protected final void handleResourceRemovals(ISyncInfoTreeChangeEvent event) { - IResource[] resources = event.getRemovedResources(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - handleRemoval(resource); - } - } + IResource[] resources = event.getRemovedResources(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + handleRemoval(resource); + } + } - /** - * Remove the resource from all providers that are displaying it - * @param resource the resource to be removed - */ - protected void handleRemoval(IResource resource) { - ISynchronizeModelProvider[] providers = getProvidersContaining(resource); - for (int i = 0; i < providers.length; i++) { - ISynchronizeModelProvider provider = providers[i]; - removeFromProvider(resource, provider); - } - } + /** + * Remove the resource from all providers that are displaying it + * @param resource the resource to be removed + */ + protected void handleRemoval(IResource resource) { + ISynchronizeModelProvider[] providers = getProvidersContaining(resource); + for (int i = 0; i < providers.length; i++) { + ISynchronizeModelProvider provider = providers[i]; + removeFromProvider(resource, provider); + } + } - /** - * Remove the resource from the sync set of the given provider - * unless the provider is this composite. Subclasses can - * override if they show resources directly. - * @param resource the resource to be removed - * @param provider the provider from which to remove the resource - */ - protected void removeFromProvider(IResource resource, ISynchronizeModelProvider provider) { - if (provider != this) { - provider.getSyncInfoSet().remove(resource); - } - } + /** + * Remove the resource from the sync set of the given provider + * unless the provider is this composite. Subclasses can + * override if they show resources directly. + * @param resource the resource to be removed + * @param provider the provider from which to remove the resource + */ + protected void removeFromProvider(IResource resource, ISynchronizeModelProvider provider) { + if (provider != this) { + provider.getSyncInfoSet().remove(resource); + } + } @Override protected void nodeAdded(ISynchronizeModelElement node, AbstractSynchronizeModelProvider provider) { @@ -207,49 +207,49 @@ public abstract class CompositeModelProvider extends AbstractSynchronizeModelPro super.nodeAdded(node, provider); } - @Override + @Override public void modelObjectCleared(ISynchronizeModelElement node) { - super.modelObjectCleared(node); - IResource r = node.getResource(); + super.modelObjectCleared(node); + IResource r = node.getResource(); if(r != null) { List elements = resourceToElements.get(r); if(elements != null) { elements.remove(node); if (elements.isEmpty()) { - resourceToElements.remove(r); + resourceToElements.remove(r); } } } elementToProvider.remove(node); - } + } - @Override + @Override protected void recursiveClearModelObjects(ISynchronizeModelElement node) { - super.recursiveClearModelObjects(node); - if (node == getModelRoot()) { - clearProviders(); - } - } + super.recursiveClearModelObjects(node); + if (node == getModelRoot()) { + clearProviders(); + } + } - private void clearProviders() { - for (Iterator iter = providers.iterator(); iter.hasNext();) { - ISynchronizeModelProvider provider = (ISynchronizeModelProvider) iter.next(); - provider.dispose(); - } - providers.clear(); - resourceToElements.clear(); - elementToProvider.clear(); - } + private void clearProviders() { + for (Iterator iter = providers.iterator(); iter.hasNext();) { + ISynchronizeModelProvider provider = (ISynchronizeModelProvider) iter.next(); + provider.dispose(); + } + providers.clear(); + resourceToElements.clear(); + elementToProvider.clear(); + } - /** - * Helper method for creating a provider for the given id. - * @param parent the root node for the new provider - * @param id the id of the providers descriptor - * @return the new provider - */ + /** + * Helper method for creating a provider for the given id. + * @param parent the root node for the new provider + * @param id the id of the providers descriptor + * @return the new provider + */ protected ISynchronizeModelProvider createModelProvider(ISynchronizeModelElement parent, String id, SyncInfoTree syncInfoTree) { - if (id != null && id.endsWith(FlatModelProvider.FlatModelProviderDescriptor.ID)) { - return new FlatModelProvider(this, parent, getConfiguration(), syncInfoTree); + if (id != null && id.endsWith(FlatModelProvider.FlatModelProviderDescriptor.ID)) { + return new FlatModelProvider(this, parent, getConfiguration(), syncInfoTree); } else if (id != null && id.endsWith(CompressedFoldersModelProvider.CompressedFolderModelProviderDescriptor.ID)) { return new CompressedFoldersModelProvider(this, parent, getConfiguration(), syncInfoTree); } else { @@ -257,23 +257,23 @@ public abstract class CompositeModelProvider extends AbstractSynchronizeModelPro } } - @Override + @Override public void dispose() { - clearProviders(); - super.dispose(); - } + clearProviders(); + super.dispose(); + } - @Override + @Override protected boolean hasViewerState() { - return resourceToElements != null && !resourceToElements.isEmpty(); - } + return resourceToElements != null && !resourceToElements.isEmpty(); + } - @Override + @Override protected ISynchronizeModelElement[] getModelObjects(IResource resource) { - List<ISynchronizeModelElement> elements = resourceToElements.get(resource); - if (elements == null) { - return new ISynchronizeModelElement[0]; - } - return elements.toArray(new ISynchronizeModelElement[elements.size()]); - } + List<ISynchronizeModelElement> elements = resourceToElements.get(resource); + if (elements == null) { + return new ISynchronizeModelElement[0]; + } + return elements.toArray(new ISynchronizeModelElement[elements.size()]); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java index cc72e1456..e2f967c15 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/CompressedFoldersModelProvider.java @@ -99,12 +99,12 @@ public class CompressedFoldersModelProvider extends HierarchicalModelProvider { super(configuration, set); } - public CompressedFoldersModelProvider( - AbstractSynchronizeModelProvider parentProvider, - ISynchronizeModelElement modelRoot, - ISynchronizePageConfiguration configuration, SyncInfoSet set) { - super(parentProvider, modelRoot, configuration, set); - } + public CompressedFoldersModelProvider( + AbstractSynchronizeModelProvider parentProvider, + ISynchronizeModelElement modelRoot, + ISynchronizePageConfiguration configuration, SyncInfoSet set) { + super(parentProvider, modelRoot, configuration, set); + } @Override public ISynchronizeModelProviderDescriptor getDescriptor() { @@ -272,27 +272,27 @@ public class CompressedFoldersModelProvider extends HierarchicalModelProvider { if (resource.getType() == IResource.FILE) { if (isCompressedParentEmpty(resource) && !isOutOfSync(resource.getParent())) { // The parent compressed folder is also empty so remove it - resourcesToRemove.add(resource.getParent()); + resourcesToRemove.add(resource.getParent()); } else { - resourcesToRemove.add(resource); + resourcesToRemove.add(resource); } } else { // A folder has been removed (i.e. is in-sync) // but may still contain children - resourcesToRemove.add(resource); - resourcesToAdd.addAll(Arrays.asList(getSyncInfosForFileMembers((IContainer)resource))); + resourcesToRemove.add(resource); + resourcesToAdd.addAll(Arrays.asList(getSyncInfosForFileMembers((IContainer)resource))); } } } if (!resourcesToRemove.isEmpty()) { - removeFromViewer(resourcesToRemove.toArray(new IResource[resourcesToRemove.size()])); + removeFromViewer(resourcesToRemove.toArray(new IResource[resourcesToRemove.size()])); } if (!resourcesToAdd.isEmpty()) { - addResources(resourcesToAdd.toArray(new SyncInfo[resourcesToAdd.size()])); + addResources(resourcesToAdd.toArray(new SyncInfo[resourcesToAdd.size()])); } } - @Override + @Override protected int getLogicalModelDepth(IResource resource) { if(resource.getType() == IResource.PROJECT) { return IResource.DEPTH_INFINITE; @@ -326,16 +326,16 @@ public class CompressedFoldersModelProvider extends HierarchicalModelProvider { private SyncInfo[] getSyncInfosForFileMembers(IContainer parent) { // Check if the sync set has any file children of the parent - List<SyncInfo> result = new ArrayList<>(); + List<SyncInfo> result = new ArrayList<>(); IResource[] members = getSyncInfoTree().members(parent); for (int i = 0; i < members.length; i++) { SyncInfo info = getSyncInfoTree().getSyncInfo(members[i]); if (info != null) { - result.add(info); + result.add(info); + } + if (members[i] instanceof IContainer) { + result.addAll(Arrays.asList(this.getSyncInfosForFileMembers((IContainer)members[i]))); } - if (members[i] instanceof IContainer) { - result.addAll(Arrays.asList(this.getSyncInfosForFileMembers((IContainer)members[i]))); - } } return result.toArray(new SyncInfo[result.size()]); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureRefreshScheduleDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureRefreshScheduleDialog.java index 5c345e5c1..99381f2d3 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureRefreshScheduleDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureRefreshScheduleDialog.java @@ -70,8 +70,8 @@ public class ConfigureRefreshScheduleDialog extends DetailsDialog { protected void updateEnablements() { } - @Override + @Override protected String getHelpContextId() { - return IHelpContextIds.CONFIGURE_REFRESH_SCHEDULE_DIALOG; - } + return IHelpContextIds.CONFIGURE_REFRESH_SCHEDULE_DIALOG; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/FlatModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/FlatModelProvider.java index 0ac8ef88f..1323b9662 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/FlatModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/FlatModelProvider.java @@ -150,7 +150,7 @@ public class FlatModelProvider extends SynchronizeModelProvider { @Override public void run() { if (isChecked() && sortCriteria != criteria) { - sortCriteria = criteria; + sortCriteria = criteria; String key = getSettingsKey(); IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); if(pageSettings != null) { @@ -166,7 +166,7 @@ public class FlatModelProvider extends SynchronizeModelProvider { } protected String getSettingsKey() { - return P_LAST_RESOURCESORT; + return P_LAST_RESOURCESORT; } } @@ -201,17 +201,17 @@ public class FlatModelProvider extends SynchronizeModelProvider { } } - public FlatModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set) { - super(configuration, set); - initialize(configuration); - } + public FlatModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set) { + super(configuration, set); + initialize(configuration); + } - public FlatModelProvider(AbstractSynchronizeModelProvider parentProvider, ISynchronizeModelElement modelRoot, ISynchronizePageConfiguration configuration, SyncInfoSet set) { - super(parentProvider, modelRoot, configuration, set); - initialize(configuration); - } + public FlatModelProvider(AbstractSynchronizeModelProvider parentProvider, ISynchronizeModelElement modelRoot, ISynchronizePageConfiguration configuration, SyncInfoSet set) { + super(parentProvider, modelRoot, configuration, set); + initialize(configuration); + } - private void initialize(ISynchronizePageConfiguration configuration) { + private void initialize(ISynchronizePageConfiguration configuration) { try { IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); if(pageSettings != null) { @@ -221,69 +221,69 @@ public class FlatModelProvider extends SynchronizeModelProvider { // ignore and use the defaults. } switch (sortCriteria) { - case FlatSorter.PATH: - case FlatSorter.NAME: - case FlatSorter.PARENT_NAME: - break; - default: - sortCriteria = FlatSorter.PATH; - break; - } - } - - @Override + case FlatSorter.PATH: + case FlatSorter.NAME: + case FlatSorter.PARENT_NAME: + break; + default: + sortCriteria = FlatSorter.PATH; + break; + } + } + + @Override protected SynchronizePageActionGroup createActionGroup() { - return new FlatActionGroup(); - } + return new FlatActionGroup(); + } - @Override + @Override public ViewerSorter getViewerSorter() { return new FlatSorter(sortCriteria); - } + } - @Override + @Override protected IDiffElement[] buildModelObjects(ISynchronizeModelElement node) { - if (node == getModelRoot()); - SyncInfo[] infos = getSyncInfoSet().getSyncInfos(); - List result = new ArrayList(); - for (int i = 0; i < infos.length; i++) { - SyncInfo info = infos[i]; - result.add(createModelObject(node, info)); - } - return (IDiffElement[]) result.toArray(new IDiffElement[result.size()]); - } - - @Override + if (node == getModelRoot()); + SyncInfo[] infos = getSyncInfoSet().getSyncInfos(); + List result = new ArrayList(); + for (int i = 0; i < infos.length; i++) { + SyncInfo info = infos[i]; + result.add(createModelObject(node, info)); + } + return (IDiffElement[]) result.toArray(new IDiffElement[result.size()]); + } + + @Override protected void handleResourceAdditions(ISyncInfoTreeChangeEvent event) { - addResources(event.getAddedResources()); - } + addResources(event.getAddedResources()); + } - @Override + @Override protected void handleResourceRemovals(ISyncInfoTreeChangeEvent event) { - IResource[] resources = event.getRemovedResources(); - removeFromViewer(resources); - } + IResource[] resources = event.getRemovedResources(); + removeFromViewer(resources); + } - @Override + @Override public ISynchronizeModelProviderDescriptor getDescriptor() { - return flatDescriptor; - } + return flatDescriptor; + } @Override protected void addResource(SyncInfo info) { // Add the node to the root - ISynchronizeModelElement node = getModelObject(info.getLocal()); - if (node != null) { - // Somehow the node exists. Remove it and read it to ensure - // what is shown matches the contents of the sync set - removeFromViewer(info.getLocal()); - } + ISynchronizeModelElement node = getModelObject(info.getLocal()); + if (node != null) { + // Somehow the node exists. Remove it and read it to ensure + // what is shown matches the contents of the sync set + removeFromViewer(info.getLocal()); + } createModelObject(getModelRoot(), info); } @Override protected ISynchronizeModelElement createModelObject(ISynchronizeModelElement parent, SyncInfo info) { - SynchronizeModelElement newNode = new FullPathSyncInfoElement(parent, info); + SynchronizeModelElement newNode = new FullPathSyncInfoElement(parent, info); addToViewer(newNode); return newNode; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ForwardingChangesSection.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ForwardingChangesSection.java index d1712d3e2..0a21c362d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ForwardingChangesSection.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ForwardingChangesSection.java @@ -106,9 +106,9 @@ public abstract class ForwardingChangesSection extends ChangesSection { if (numChanges > 0) { String message; if(numChanges > 1) { - message = NLS.bind(TeamUIMessages.ChangesSection_filterHidesPlural, new String[] { Long.toString(numChanges), Utils.modeToString(candidateMode) }); + message = NLS.bind(TeamUIMessages.ChangesSection_filterHidesPlural, new String[] { Long.toString(numChanges), Utils.modeToString(candidateMode) }); } else { - message = NLS.bind(TeamUIMessages.ChangesSection_filterHidesSingular, new String[] { Long.toString(numChanges), Utils.modeToString(candidateMode) }); + message = NLS.bind(TeamUIMessages.ChangesSection_filterHidesSingular, new String[] { Long.toString(numChanges), Utils.modeToString(candidateMode) }); } message = NLS.bind(TeamUIMessages.ChangesSection_filterHides, new String[] { Utils.modeToString(getConfiguration().getMode()), message }); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/GlobalRefreshElementSelectionPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/GlobalRefreshElementSelectionPage.java index e42932b00..64cca1c54 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/GlobalRefreshElementSelectionPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/GlobalRefreshElementSelectionPage.java @@ -87,7 +87,7 @@ public abstract class GlobalRefreshElementSelectionPage extends WizardPage { top.setLayoutData(data); setControl(top); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.SYNC_RESOURCE_SELECTION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.SYNC_RESOURCE_SELECTION_PAGE); Label l = new Label(top, SWT.NULL); l.setText(TeamUIMessages.GlobalRefreshResourceSelectionPage_5); @@ -379,9 +379,9 @@ public abstract class GlobalRefreshElementSelectionPage extends WizardPage { } protected void setWorkspaceSelected(boolean selected) { - workingSetScope.setSelection(!selected); - selectedResourcesScope.setSelection(!selected); - participantScope.setSelection(selected); + workingSetScope.setSelection(!selected); + selectedResourcesScope.setSelection(!selected); + participantScope.setSelection(selected); } protected boolean isWorkingSetSelected() { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelManager.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelManager.java index 61278d117..d9b34c55a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelManager.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelManager.java @@ -27,7 +27,7 @@ public class HierarchicalModelManager extends SynchronizeModelManager { @Override protected ISynchronizeModelProviderDescriptor[] getSupportedModelProviders() { return new ISynchronizeModelProviderDescriptor[] { - new FlatModelProvider.FlatModelProviderDescriptor(), + new FlatModelProvider.FlatModelProviderDescriptor(), new HierarchicalModelProvider.HierarchicalModelProviderDescriptor(), new CompressedFoldersModelProvider.CompressedFolderModelProviderDescriptor() }; } @@ -38,7 +38,7 @@ public class HierarchicalModelManager extends SynchronizeModelManager { id = getDefaultProviderId(); } if (id.endsWith(FlatModelProvider.FlatModelProviderDescriptor.ID)) { - return new FlatModelProvider(getConfiguration(), getSyncInfoSet()); + return new FlatModelProvider(getConfiguration(), getSyncInfoSet()); } else if(id.endsWith(CompressedFoldersModelProvider.CompressedFolderModelProviderDescriptor.ID)) { return new CompressedFoldersModelProvider(getConfiguration(), getSyncInfoSet()); } else { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelProvider.java index 8247b2452..bd5d3971f 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/HierarchicalModelProvider.java @@ -83,12 +83,12 @@ public class HierarchicalModelProvider extends SynchronizeModelProvider { super(configuration, set); } - public HierarchicalModelProvider( - AbstractSynchronizeModelProvider parentProvider, - ISynchronizeModelElement modelRoot, - ISynchronizePageConfiguration configuration, SyncInfoSet set) { - super(parentProvider, modelRoot, configuration, set); - } + public HierarchicalModelProvider( + AbstractSynchronizeModelProvider parentProvider, + ISynchronizeModelElement modelRoot, + ISynchronizePageConfiguration configuration, SyncInfoSet set) { + super(parentProvider, modelRoot, configuration, set); + } @Override public ISynchronizeModelProviderDescriptor getDescriptor() { @@ -159,24 +159,24 @@ public class HierarchicalModelProvider extends SynchronizeModelProvider { protected void addResources(IResource[] added) { for (int i = 0; i < added.length; i++) { IResource resource = added[i]; - addResource(resource); + addResource(resource); } } - private void addResource(IResource resource) { - ISynchronizeModelElement node = getModelObject(resource); - if (node != null) { - // Somehow the node exists. Remove it and read it to ensure - // what is shown matches the contents of the sync set - removeFromViewer(resource); - } - // Build the sub-tree rooted at this node - ISynchronizeModelElement parent = getModelObject(resource.getParent()); - if (parent != null) { - node = createModelObject(parent, resource); - buildModelObjects(node); - } - } + private void addResource(IResource resource) { + ISynchronizeModelElement node = getModelObject(resource); + if (node != null) { + // Somehow the node exists. Remove it and read it to ensure + // what is shown matches the contents of the sync set + removeFromViewer(resource); + } + // Build the sub-tree rooted at this node + ISynchronizeModelElement parent = getModelObject(resource.getParent()); + if (parent != null) { + node = createModelObject(parent, resource); + buildModelObjects(node); + } + } @Override protected IDiffElement[] buildModelObjects(ISynchronizeModelElement node) { @@ -222,13 +222,13 @@ public class HierarchicalModelProvider extends SynchronizeModelProvider { } } - @Override + @Override protected ISynchronizeModelElement createModelObject(ISynchronizeModelElement parent, SyncInfo info) { - return createModelObject(parent, info.getLocal()); - } + return createModelObject(parent, info.getLocal()); + } - @Override + @Override protected void addResource(SyncInfo info) { - addResource(info.getLocal()); - } + addResource(info.getLocal()); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IChangeSetProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IChangeSetProvider.java index 2ab987df3..d3fabe5f1 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IChangeSetProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IChangeSetProvider.java @@ -20,11 +20,11 @@ package org.eclipse.team.internal.ui.synchronize; */ public interface IChangeSetProvider { - /** - * Return the change set capability for this participant or <code>null</code> - * if change sets are not supported. - * @return the change set capability for this participant - * @since 3.1 - */ - public ChangeSetCapability getChangeSetCapability(); + /** + * Return the change set capability for this participant or <code>null</code> + * if change sets are not supported. + * @return the change set capability for this participant + * @since 3.1 + */ + public ChangeSetCapability getChangeSetCapability(); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IPageValidator.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IPageValidator.java index ac66d0a92..bbcc47756 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IPageValidator.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/IPageValidator.java @@ -18,8 +18,8 @@ package org.eclipse.team.internal.ui.synchronize; * @since 3.0 */ public interface IPageValidator { - /** - * If errorMessage in <code>null</code> then the page is complete otherwise + /** + * If errorMessage in <code>null</code> then the page is complete otherwise * the error message indicates that the reason why the page is not complete. */ public void setComplete(String errorMessage); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ISynchronizeModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ISynchronizeModelProvider.java index c4d91ec90..30ecf3f6e 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ISynchronizeModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ISynchronizeModelProvider.java @@ -29,13 +29,13 @@ import org.eclipse.team.ui.synchronize.ISynchronizeModelElement; */ public interface ISynchronizeModelProvider { - /** - * Property constant used to indicate that the viewer sorter has changed. - * Property change notifications for the viewer sorter change do not include - * the old and new viewer sorter. Instead, clients should re-obtain the sorter - * from the provider. - */ - public static final String P_VIEWER_SORTER = TeamUIPlugin.ID + ".P_VIEWER_SORTER"; //$NON-NLS-1$ + /** + * Property constant used to indicate that the viewer sorter has changed. + * Property change notifications for the viewer sorter change do not include + * the old and new viewer sorter. Instead, clients should re-obtain the sorter + * from the provider. + */ + public static final String P_VIEWER_SORTER = TeamUIPlugin.ID + ".P_VIEWER_SORTER"; //$NON-NLS-1$ /** * Returns the sync set this model provider is showing. diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/LocalResourceSaveableComparison.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/LocalResourceSaveableComparison.java index 25d37b81d..01e63bfb6 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/LocalResourceSaveableComparison.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/LocalResourceSaveableComparison.java @@ -58,7 +58,7 @@ public abstract class LocalResourceSaveableComparison extends SaveableComparison private final CompareEditorInput editorInput; private boolean isSaving; private IContentChangeListener contentChangeListener; - private ITypedElement fileElement; + private ITypedElement fileElement; private IDocument document; /** @@ -123,7 +123,7 @@ public abstract class LocalResourceSaveableComparison extends SaveableComparison // Discard of the buffer ITypedElement left = getFileElement(); if (left instanceof LocalResourceTypedElement) - ((LocalResourceTypedElement) left).discardBuffer(); + ((LocalResourceTypedElement) left).discardBuffer(); document = null; } @@ -245,7 +245,7 @@ public abstract class LocalResourceSaveableComparison extends SaveableComparison // Only the left is ever editable ITypedElement left = getFileElement(); if (left instanceof LocalResourceTypedElement) - ((LocalResourceTypedElement) left).discardBuffer(); + ((LocalResourceTypedElement) left).discardBuffer(); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshModelParticipantJob.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshModelParticipantJob.java index 1be2a0b6d..f5a42ae35 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshModelParticipantJob.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshModelParticipantJob.java @@ -97,17 +97,17 @@ public class RefreshModelParticipantJob extends RefreshParticipantJob { return ((ModelSynchronizeParticipant)getParticipant()).getContext().getDiffTree().size(); } - @Override + @Override protected int getIncomingChangeCount() { - IResourceDiffTree diffTree = ((ModelSynchronizeParticipant)getParticipant()).getContext().getDiffTree(); - return (int) diffTree.countFor(IThreeWayDiff.INCOMING, IThreeWayDiff.DIRECTION_MASK); - } + IResourceDiffTree diffTree = ((ModelSynchronizeParticipant)getParticipant()).getContext().getDiffTree(); + return (int) diffTree.countFor(IThreeWayDiff.INCOMING, IThreeWayDiff.DIRECTION_MASK); + } - @Override + @Override protected int getOutgoingChangeCount() { - IResourceDiffTree diffTree = ((ModelSynchronizeParticipant)getParticipant()).getContext().getDiffTree(); - return (int) diffTree.countFor(IThreeWayDiff.OUTGOING, IThreeWayDiff.DIRECTION_MASK); - } + IResourceDiffTree diffTree = ((ModelSynchronizeParticipant)getParticipant()).getContext().getDiffTree(); + return (int) diffTree.countFor(IThreeWayDiff.OUTGOING, IThreeWayDiff.DIRECTION_MASK); + } @Override protected void handleProgressGroupSet(IProgressMonitor group, int ticks) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshParticipantJob.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshParticipantJob.java index 8ed33cc10..23402f815 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshParticipantJob.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshParticipantJob.java @@ -116,49 +116,49 @@ public abstract class RefreshParticipantJob extends Job { * that have occurred during the refresh */ private final class GotoActionWrapper extends WorkbenchAction { - private ActionFactory.IWorkbenchAction gotoAction; - private IStatus status; - @Override + private ActionFactory.IWorkbenchAction gotoAction; + private IStatus status; + @Override public void run() { - if (status != null && !status.isOK()) { - ErrorDialog.openError(Utils.getShell(null), null, TeamUIMessages.RefreshSubscriberJob_3, status); - } else if(gotoAction != null) { - gotoAction.run(); - } - } - @Override + if (status != null && !status.isOK()) { + ErrorDialog.openError(Utils.getShell(null), null, TeamUIMessages.RefreshSubscriberJob_3, status); + } else if(gotoAction != null) { + gotoAction.run(); + } + } + @Override public boolean isEnabled() { - if(gotoAction != null) { - return gotoAction.isEnabled(); - } - return true; - } - @Override + if(gotoAction != null) { + return gotoAction.isEnabled(); + } + return true; + } + @Override public String getText() { - if(gotoAction != null) { - return gotoAction.getText(); - } - return null; - } - @Override + if(gotoAction != null) { + return gotoAction.getText(); + } + return null; + } + @Override public String getToolTipText() { - if (status != null && !status.isOK()) { - return status.getMessage(); - } - if(gotoAction != null) { - return gotoAction.getToolTipText(); - } - return Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, RefreshParticipantJob.this.getName()); - } - @Override + if (status != null && !status.isOK()) { + return status.getMessage(); + } + if(gotoAction != null) { + return gotoAction.getToolTipText(); + } + return Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, RefreshParticipantJob.this.getName()); + } + @Override public void dispose() { - super.dispose(); - if(gotoAction != null) { - gotoAction.dispose(); - } - } - public void setGotoAction(ActionFactory.IWorkbenchAction gotoAction) { - this.gotoAction = gotoAction; + super.dispose(); + if(gotoAction != null) { + gotoAction.dispose(); + } + } + public void setGotoAction(ActionFactory.IWorkbenchAction gotoAction) { + this.gotoAction = gotoAction; setEnabled(isEnabled()); setToolTipText(getToolTipText()); gotoAction.addPropertyChangeListener(event -> { @@ -167,13 +167,13 @@ public abstract class RefreshParticipantJob extends Job { GotoActionWrapper.this.setEnabled(bool.booleanValue()); } }); - } - public void setStatus(IStatus status) { - this.status = status; - } - } + } + public void setStatus(IStatus status) { + this.status = status; + } + } - /** + /** * Notification for safely notifying listeners of refresh lifecycle. */ private abstract class Notification implements ISafeRunnable { @@ -349,21 +349,21 @@ public abstract class RefreshParticipantJob extends Job { } } } catch(CoreException e) { - // Determine the status to be returned and the GOTO action - status = e.getStatus(); - if (!isUser()) { - // Use the GOTO action to show the error and return OK - Object prop = getProperty(IProgressConstants.ACTION_PROPERTY); - if (prop instanceof GotoActionWrapper) { - GotoActionWrapper wrapper = (GotoActionWrapper)prop; - wrapper.setStatus(e.getStatus()); - status = new Status(IStatus.OK, TeamUIPlugin.ID, IStatus.OK, e.getStatus().getMessage(), e); - } - } - if (!isUser() && status.getSeverity() == IStatus.ERROR) { - // Never prompt for errors on non-user jobs - setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); - } + // Determine the status to be returned and the GOTO action + status = e.getStatus(); + if (!isUser()) { + // Use the GOTO action to show the error and return OK + Object prop = getProperty(IProgressConstants.ACTION_PROPERTY); + if (prop instanceof GotoActionWrapper) { + GotoActionWrapper wrapper = (GotoActionWrapper)prop; + wrapper.setStatus(e.getStatus()); + status = new Status(IStatus.OK, TeamUIPlugin.ID, IStatus.OK, e.getStatus().getMessage(), e); + } + } + if (!isUser() && status.getSeverity() == IStatus.ERROR) { + // Never prompt for errors on non-user jobs + setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); + } } finally { event.setStopTime(System.currentTimeMillis()); } @@ -383,7 +383,7 @@ public abstract class RefreshParticipantJob extends Job { return event.getStatus(); } finally { if (acquired) lock.release(); - monitor.done(); + monitor.done(); } } @@ -422,12 +422,12 @@ public abstract class RefreshParticipantJob extends Job { code = IRefreshEvent.STATUS_CHANGES; int incomingChanges = getIncomingChangeCount(); - String numIncomingChanges = incomingChanges==0 ? "" //$NON-NLS-1$ - : NLS.bind(TeamUIMessages.RefreshCompleteDialog_incomingChanges, Integer.toString(incomingChanges)); + String numIncomingChanges = incomingChanges==0 ? "" //$NON-NLS-1$ + : NLS.bind(TeamUIMessages.RefreshCompleteDialog_incomingChanges, Integer.toString(incomingChanges)); int outgoingChanges = getOutgoingChangeCount(); String numOutgoingChanges = outgoingChanges==0 ? "" //$NON-NLS-1$ - : NLS.bind(TeamUIMessages.RefreshCompleteDialog_outgoingChanges, Integer.toString(outgoingChanges)); + : NLS.bind(TeamUIMessages.RefreshCompleteDialog_outgoingChanges, Integer.toString(outgoingChanges)); String sep = incomingChanges>0 && outgoingChanges>0 ? "; " : ""; //$NON-NLS-1$ //$NON-NLS-2$ @@ -436,9 +436,9 @@ public abstract class RefreshParticipantJob extends Job { code = IRefreshEvent.STATUS_NEW_CHANGES; String numNewChanges = Integer.toString(changeCount); if (changeCount == 1) { - text.append(NLS.bind(TeamUIMessages.RefreshCompleteDialog_newChangesSingular, (new Object[]{getName(), numNewChanges, numIncomingChanges, sep, numOutgoingChanges}))); + text.append(NLS.bind(TeamUIMessages.RefreshCompleteDialog_newChangesSingular, (new Object[]{getName(), numNewChanges, numIncomingChanges, sep, numOutgoingChanges}))); } else { - text.append(NLS.bind(TeamUIMessages.RefreshCompleteDialog_newChangesPlural, (new Object[]{getName(), numNewChanges, numIncomingChanges, sep, numOutgoingChanges}))); + text.append(NLS.bind(TeamUIMessages.RefreshCompleteDialog_newChangesPlural, (new Object[]{getName(), numNewChanges, numIncomingChanges, sep, numOutgoingChanges}))); } } else { // Refreshed resources contain changes @@ -487,7 +487,7 @@ public abstract class RefreshParticipantJob extends Job { Job update = new UIJob("") { //$NON-NLS-1$ @Override public IStatus runInUIThread(IProgressMonitor monitor) { - runnable.run(); + runnable.run(); return Status.OK_STATUS; } }; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshSubscriberParticipantJob.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshSubscriberParticipantJob.java index 593ffa68e..99d6c6474 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshSubscriberParticipantJob.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/RefreshSubscriberParticipantJob.java @@ -57,35 +57,35 @@ public class RefreshSubscriberParticipantJob extends RefreshParticipantJob { return numChanges; } - @Override + @Override protected int getIncomingChangeCount() { - return getChangesInMode(SyncInfo.INCOMING); - } + return getChangesInMode(SyncInfo.INCOMING); + } - @Override + @Override protected int getOutgoingChangeCount() { - return getChangesInMode(SyncInfo.OUTGOING); - } + return getChangesInMode(SyncInfo.OUTGOING); + } - private int getChangesInMode(int kind) { - int numChanges = 0; - SubscriberSyncInfoCollector collector = getCollector(); - if (collector != null) { - SyncInfoTree set = collector.getSyncInfoSet(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; - SyncInfo[] infos = set.getSyncInfos(resource, IResource.DEPTH_INFINITE); - if(infos != null && infos.length > 0) { - for(int j = 0; j < infos.length; j++) { - if((infos[j].getKind() & kind)>0) { - numChanges++; - } - } - } - } - } - return numChanges; - } + private int getChangesInMode(int kind) { + int numChanges = 0; + SubscriberSyncInfoCollector collector = getCollector(); + if (collector != null) { + SyncInfoTree set = collector.getSyncInfoSet(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + SyncInfo[] infos = set.getSyncInfos(resource, IResource.DEPTH_INFINITE); + if(infos != null && infos.length > 0) { + for(int j = 0; j < infos.length; j++) { + if((infos[j].getKind() & kind)>0) { + numChanges++; + } + } + } + } + } + return numChanges; + } @Override protected RefreshParticipantJob.IChangeDescription createChangeDescription() { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StartupPreferencePage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StartupPreferencePage.java index 467f888a6..b901a59f7 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StartupPreferencePage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StartupPreferencePage.java @@ -49,20 +49,20 @@ public class StartupPreferencePage extends FieldEditorPreferencePage implements @Override public void createControl(Composite parent) { super.createControl(parent); - // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.SYNC_STARTUP_PREFERENCE_PAGE); + // set F1 help + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.SYNC_STARTUP_PREFERENCE_PAGE); } @Override protected void createFieldEditors() { - addField(new RadioGroupFieldEditor(PROP_STARTUP_ACTION, - TeamUIMessages.StartupPreferencePage_2, 1, - new String[][] { - {TeamUIMessages.StartupPreferencePage_3, STARTUP_ACTION_POPULATE}, - {TeamUIMessages.StartupPreferencePage_4, STARTUP_ACTION_SYNCHRONIZE}, - {TeamUIMessages.StartupPreferencePage_5, STARTUP_ACTION_NONE} - }, - getFieldEditorParent(), true /* use a group */)); + addField(new RadioGroupFieldEditor(PROP_STARTUP_ACTION, + TeamUIMessages.StartupPreferencePage_2, 1, + new String[][] { + {TeamUIMessages.StartupPreferencePage_3, STARTUP_ACTION_POPULATE}, + {TeamUIMessages.StartupPreferencePage_4, STARTUP_ACTION_SYNCHRONIZE}, + {TeamUIMessages.StartupPreferencePage_5, STARTUP_ACTION_NONE} + }, + getFieldEditorParent(), true /* use a group */)); } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StructuredViewerAdvisor.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StructuredViewerAdvisor.java index 14f808abe..aaf139b8d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StructuredViewerAdvisor.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/StructuredViewerAdvisor.java @@ -185,7 +185,7 @@ public abstract class StructuredViewerAdvisor extends AbstractViewerAdvisor { IResource resource = syncNode.getResource(); if (syncNode != null && resource != null && resource.getType() == IResource.FILE) { // The open is handled by the open strategy but say we handled - // it so that overriding methods will not do anything + // it so that overriding methods will not do anything return true; } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SyncInfoSetChangeSetCollector.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SyncInfoSetChangeSetCollector.java index 361c227bd..327151fe5 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SyncInfoSetChangeSetCollector.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SyncInfoSetChangeSetCollector.java @@ -44,237 +44,237 @@ import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; */ public abstract class SyncInfoSetChangeSetCollector extends ChangeSetManager { - private final ISynchronizePageConfiguration configuration; - private ChangeSetModelProvider provider; + private final ISynchronizePageConfiguration configuration; + private ChangeSetModelProvider provider; - /* - * Listener that will remove sets when they become empty. - * The sets in this collector are only modified from either the - * UI thread or the provider's event handler thread so updates - * done by this listener will update the view properly. - */ - ISyncInfoSetChangeListener changeSetListener = new ISyncInfoSetChangeListener() { + /* + * Listener that will remove sets when they become empty. + * The sets in this collector are only modified from either the + * UI thread or the provider's event handler thread so updates + * done by this listener will update the view properly. + */ + ISyncInfoSetChangeListener changeSetListener = new ISyncInfoSetChangeListener() { - @Override + @Override public void syncInfoSetReset(SyncInfoSet set, IProgressMonitor monitor) { - handleChangeEvent(set); - } + handleChangeEvent(set); + } - @Override + @Override public void syncInfoChanged(ISyncInfoSetChangeEvent event, IProgressMonitor monitor) { - handleChangeEvent(event.getSet()); - } + handleChangeEvent(event.getSet()); + } - @Override + @Override public void syncInfoSetErrors(SyncInfoSet set, ITeamStatus[] errors, IProgressMonitor monitor) { - // TODO Auto-generated method stub - } + // TODO Auto-generated method stub + } - /* - * The collector removes change sets once they are empty - */ - private void handleChangeEvent(SyncInfoSet set) { - if (set.isEmpty()) { - ChangeSet changeSet = getChangeSet(set); - if (changeSet != null) { - remove(changeSet); - } - } - } - }; + /* + * The collector removes change sets once they are empty + */ + private void handleChangeEvent(SyncInfoSet set) { + if (set.isEmpty()) { + ChangeSet changeSet = getChangeSet(set); + if (changeSet != null) { + remove(changeSet); + } + } + } + }; - /** - * Create a collector that contains the sync info from the given seed set - * @param configuration the set used to determine which sync info - * should be included in the change sets. - */ - public SyncInfoSetChangeSetCollector(ISynchronizePageConfiguration configuration) { - this.configuration = configuration; - } + /** + * Create a collector that contains the sync info from the given seed set + * @param configuration the set used to determine which sync info + * should be included in the change sets. + */ + public SyncInfoSetChangeSetCollector(ISynchronizePageConfiguration configuration) { + this.configuration = configuration; + } - /** - * Add the given resource sync info nodes to the appropriate - * change sets, adding them if necessary. - * This method is invoked by the <code>handleChanges</code> - * and <code>reset</code> methods - * when the model provider changes state. Updates done to the collector - * from within this thread will be thread-safe and update the view - * properly. Updates done from other threads should perform adds - * within a runnable passed to the - * <code>performUpdate</code> method to ensure the view is - * updated properly. - * <p> - * Subclasses must override this method. - * @param infos the sync infos to add - */ - protected abstract void add(SyncInfo[] infos); + /** + * Add the given resource sync info nodes to the appropriate + * change sets, adding them if necessary. + * This method is invoked by the <code>handleChanges</code> + * and <code>reset</code> methods + * when the model provider changes state. Updates done to the collector + * from within this thread will be thread-safe and update the view + * properly. Updates done from other threads should perform adds + * within a runnable passed to the + * <code>performUpdate</code> method to ensure the view is + * updated properly. + * <p> + * Subclasses must override this method. + * @param infos the sync infos to add + */ + protected abstract void add(SyncInfo[] infos); - /** - * Remove the given resources from all sets of this collector. - * This method is invoked by the <code>handleChanges</code> method - * when the model provider changes state. It should not - * be invoked by other clients. The model provider - * will invoke this method from a particular thread (which may - * or may not be the UI thread). - * Updates done from other threads should perform removes - * within a runnable passed to the - * <code>performUpdate</code> method to ensure the view is - * updated properly. - * <p> - * Subclasses may override this method. - * @param resources the resources to be removed - */ - protected void remove(IResource[] resources) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set = sets[i]; - set.remove(resources); - } - } + /** + * Remove the given resources from all sets of this collector. + * This method is invoked by the <code>handleChanges</code> method + * when the model provider changes state. It should not + * be invoked by other clients. The model provider + * will invoke this method from a particular thread (which may + * or may not be the UI thread). + * Updates done from other threads should perform removes + * within a runnable passed to the + * <code>performUpdate</code> method to ensure the view is + * updated properly. + * <p> + * Subclasses may override this method. + * @param resources the resources to be removed + */ + protected void remove(IResource[] resources) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set = sets[i]; + set.remove(resources); + } + } - protected ISyncInfoSetChangeListener getChangeSetChangeListener() { - return changeSetListener; - } + protected ISyncInfoSetChangeListener getChangeSetChangeListener() { + return changeSetListener; + } - /** - * Re-populate the change sets from the seed set. - * If <code>null</code> is passed, clear any state - * but do not re-populate. - * <p> - * This method is invoked by the model provider when the - * model provider changes state. It should not - * be invoked by other clients. The model provider - * will invoke this method from a particular thread (which may - * or may not be the UI thread). Updates done to the collector - * from within this thread will be thread-safe and update the view - * properly. Updates done from other threads should use the - * <code>performUpdate</code> method to ensure the view is - * updated properly. - * <p> - * Subclasses may override this method. - * @param seedSet - */ - public void reset(SyncInfoSet seedSet) { - // First, remove all the sets - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet set2 = sets[i]; - remove(set2); - } - if (seedSet != null) { - add(seedSet.getSyncInfos()); - } - } + /** + * Re-populate the change sets from the seed set. + * If <code>null</code> is passed, clear any state + * but do not re-populate. + * <p> + * This method is invoked by the model provider when the + * model provider changes state. It should not + * be invoked by other clients. The model provider + * will invoke this method from a particular thread (which may + * or may not be the UI thread). Updates done to the collector + * from within this thread will be thread-safe and update the view + * properly. Updates done from other threads should use the + * <code>performUpdate</code> method to ensure the view is + * updated properly. + * <p> + * Subclasses may override this method. + * @param seedSet + */ + public void reset(SyncInfoSet seedSet) { + // First, remove all the sets + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet set2 = sets[i]; + remove(set2); + } + if (seedSet != null) { + add(seedSet.getSyncInfos()); + } + } - /** - * This method is invoked by the model provider when the - * seed <code>SyncInfoSet</code> changes. It should not - * be invoked by other clients. The model provider - * will invoke this method from a particular thread (which may - * or may not be the UI thread). Updates done to the collector - * from within this thread will be thread-safe and update the view - * properly. Updates done from other threads should use the - * <code>performUpdate</code> method to ensure the view is - * updated properly. - * <p> - * Subclasses may override this method. - * @param event the set change event. - */ - public void handleChange(ISyncInfoSetChangeEvent event) { - List<IResource> removals = new ArrayList<>(); - List<SyncInfo> additions = new ArrayList<>(); - removals.addAll(Arrays.asList(event.getRemovedResources())); - additions.addAll(Arrays.asList(event.getAddedResources())); - SyncInfo[] changed = event.getChangedResources(); - for (int i = 0; i < changed.length; i++) { - SyncInfo info = changed[i]; - additions.add(info); - removals.add(info.getLocal()); - } - if (!removals.isEmpty()) { - remove(removals.toArray(new IResource[removals.size()])); - } - if (!additions.isEmpty()) { - add(additions.toArray(new SyncInfo[additions.size()])); - } - } + /** + * This method is invoked by the model provider when the + * seed <code>SyncInfoSet</code> changes. It should not + * be invoked by other clients. The model provider + * will invoke this method from a particular thread (which may + * or may not be the UI thread). Updates done to the collector + * from within this thread will be thread-safe and update the view + * properly. Updates done from other threads should use the + * <code>performUpdate</code> method to ensure the view is + * updated properly. + * <p> + * Subclasses may override this method. + * @param event the set change event. + */ + public void handleChange(ISyncInfoSetChangeEvent event) { + List<IResource> removals = new ArrayList<>(); + List<SyncInfo> additions = new ArrayList<>(); + removals.addAll(Arrays.asList(event.getRemovedResources())); + additions.addAll(Arrays.asList(event.getAddedResources())); + SyncInfo[] changed = event.getChangedResources(); + for (int i = 0; i < changed.length; i++) { + SyncInfo info = changed[i]; + additions.add(info); + removals.add(info.getLocal()); + } + if (!removals.isEmpty()) { + remove(removals.toArray(new IResource[removals.size()])); + } + if (!additions.isEmpty()) { + add(additions.toArray(new SyncInfo[additions.size()])); + } + } - /** - * Return the configuration for the page that is displaying the model created - * using this collector. - * @return the configuration for the page that is displaying the model created - * using this collector - */ - public final ISynchronizePageConfiguration getConfiguration() { - return configuration; - } + /** + * Return the configuration for the page that is displaying the model created + * using this collector. + * @return the configuration for the page that is displaying the model created + * using this collector + */ + public final ISynchronizePageConfiguration getConfiguration() { + return configuration; + } - /** - * Execute the given runnable which updates the sync sets contained - * in this collector. This method should be used by subclasses when they - * are populating or modifying sets from another thread. In other words, - * if the sets of this collector are updated directly in the <code>add</code> - * method then this method is not required. However, if sets are created - * or modified by another thread, that thread must use this method to ensure - * the updates occur in the proper thread in order to ensure thread safety. - * <p> - * The update may be run in a different thread then the caller. - * However, regardless of which thread the update is run in, the view - * will be updated once the update is completed. - * @param runnable the workspace runnable that updates the sync sets. - * @param preserveExpansion whether the expansed items in the view should - * remain expanded after the update is performed. - * @param monitor a progress monitor - */ - protected final void performUpdate(IWorkspaceRunnable runnable, boolean preserveExpansion, IProgressMonitor monitor) { - provider.performUpdate(runnable, preserveExpansion, false /* run in the handler thread and refresh at the end */); - } + /** + * Execute the given runnable which updates the sync sets contained + * in this collector. This method should be used by subclasses when they + * are populating or modifying sets from another thread. In other words, + * if the sets of this collector are updated directly in the <code>add</code> + * method then this method is not required. However, if sets are created + * or modified by another thread, that thread must use this method to ensure + * the updates occur in the proper thread in order to ensure thread safety. + * <p> + * The update may be run in a different thread then the caller. + * However, regardless of which thread the update is run in, the view + * will be updated once the update is completed. + * @param runnable the workspace runnable that updates the sync sets. + * @param preserveExpansion whether the expansed items in the view should + * remain expanded after the update is performed. + * @param monitor a progress monitor + */ + protected final void performUpdate(IWorkspaceRunnable runnable, boolean preserveExpansion, IProgressMonitor monitor) { + provider.performUpdate(runnable, preserveExpansion, false /* run in the handler thread and refresh at the end */); + } - /* - * Sets the provider for this collector. This method is for internal use only. - */ - public final void setProvider(ChangeSetModelProvider provider) { - this.provider = provider; - } + /* + * Sets the provider for this collector. This method is for internal use only. + */ + public final void setProvider(ChangeSetModelProvider provider) { + this.provider = provider; + } - /** - * This method should wait until any background processing is - * completed. It is for testing purposes. By default, it does not wait at all. - * Subclasses that perform work in the background should override. - * @param monitor a progress monitor - */ - public void waitUntilDone(IProgressMonitor monitor) { - // Do nothing, by default - } + /** + * This method should wait until any background processing is + * completed. It is for testing purposes. By default, it does not wait at all. + * Subclasses that perform work in the background should override. + * @param monitor a progress monitor + */ + public void waitUntilDone(IProgressMonitor monitor) { + // Do nothing, by default + } - @Override + @Override protected void handleSetAdded(ChangeSet set) { - ((CheckedInChangeSet)set).getSyncInfoSet().addSyncSetChangedListener(getChangeSetChangeListener()); - super.handleSetAdded(set); - } + ((CheckedInChangeSet)set).getSyncInfoSet().addSyncSetChangedListener(getChangeSetChangeListener()); + super.handleSetAdded(set); + } - @Override + @Override protected void handleSetRemoved(ChangeSet set) { - ((CheckedInChangeSet)set).getSyncInfoSet().removeSyncSetChangedListener(getChangeSetChangeListener()); - super.handleSetRemoved(set); - } + ((CheckedInChangeSet)set).getSyncInfoSet().removeSyncSetChangedListener(getChangeSetChangeListener()); + super.handleSetRemoved(set); + } - /** - * Return the Change Set whose sync info set is the - * one given. - * @param set a sync info set - * @return the change set for the given sync info set - */ - protected ChangeSet getChangeSet(SyncInfoSet set) { - ChangeSet[] sets = getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet changeSet = sets[i]; - if (((CheckedInChangeSet)changeSet).getSyncInfoSet() == set) { - return changeSet; - } - } - return null; - } + /** + * Return the Change Set whose sync info set is the + * one given. + * @param set a sync info set + * @return the change set for the given sync info set + */ + protected ChangeSet getChangeSet(SyncInfoSet set) { + ChangeSet[] sets = getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet changeSet = sets[i]; + if (((CheckedInChangeSet)changeSet).getSyncInfoSet() == set) { + return changeSet; + } + } + return null; + } public SyncInfoTree getSyncInfoSet(ChangeSet set) { return ((CheckedInChangeSet)set).getSyncInfoSet(); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelElementLabelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelElementLabelProvider.java index 594a7a9eb..4fa15f001 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelElementLabelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelElementLabelProvider.java @@ -210,7 +210,7 @@ public class SynchronizeModelElementLabelProvider extends LabelProvider implemen @Override public void dispose() { - workbenchLabelProvider.dispose(); + workbenchLabelProvider.dispose(); if(busyFont != null) { busyFont.dispose(); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelManager.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelManager.java index 0e01553fd..dc68ea5a1 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelManager.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelManager.java @@ -123,10 +123,10 @@ public abstract class SynchronizeModelManager extends SynchronizePageActionGroup protected String getDefaultProviderId() { String defaultLayout = TeamUIPlugin.getPlugin().getPreferenceStore().getString(IPreferenceIds.SYNCVIEW_DEFAULT_LAYOUT); if (defaultLayout.equals(IPreferenceIds.TREE_LAYOUT)) { - return HierarchicalModelProvider.HierarchicalModelProviderDescriptor.ID; + return HierarchicalModelProvider.HierarchicalModelProviderDescriptor.ID; } if (defaultLayout.equals(IPreferenceIds.FLAT_LAYOUT)) { - return FlatModelProvider.FlatModelProviderDescriptor.ID; + return FlatModelProvider.FlatModelProviderDescriptor.ID; } // Return compressed folder is the others were not a match return CompressedFoldersModelProvider.CompressedFolderModelProviderDescriptor.ID; @@ -156,7 +156,7 @@ public abstract class SynchronizeModelManager extends SynchronizePageActionGroup */ protected void setInput(String id, IProgressMonitor monitor) { if(modelProvider != null) { - modelProvider.saveState(); + modelProvider.saveState(); modelProvider.dispose(); } modelProvider = createModelProvider(id); @@ -248,7 +248,7 @@ public abstract class SynchronizeModelManager extends SynchronizePageActionGroup } setInput(defaultProviderId, null); } else { - setInput(); + setInput(); } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelProvider.java index 575cb6f9a..2520c08e3 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelProvider.java @@ -48,7 +48,7 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP protected final Map<IResource, ISynchronizeModelElement> resourceMap = Collections.synchronizedMap(new HashMap<>()); - protected static final boolean DEBUG = false; + protected static final boolean DEBUG = false; public SynchronizeModelProvider(ISynchronizePageConfiguration configuration, SyncInfoSet set) { super(configuration, set); @@ -59,10 +59,10 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP associateRoot(modelRoot); } - private void associateRoot(ISynchronizeModelElement modelRoot) { - // associate the root resource with the provider's root element + private void associateRoot(ISynchronizeModelElement modelRoot) { + // associate the root resource with the provider's root element resourceMap.put(ResourcesPlugin.getWorkspace().getRoot(), modelRoot); - } + } /** * Dispose of the builder @@ -92,14 +92,14 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP return resourceMap.get(resource); } - @Override + @Override protected ISynchronizeModelElement[] getModelObjects(IResource resource) { - ISynchronizeModelElement element = getModelObject(resource); - if (element == null) { - return new ISynchronizeModelElement[0]; - } - return new ISynchronizeModelElement[] { element }; - } + ISynchronizeModelElement element = getModelObject(resource); + if (element == null) { + return new ISynchronizeModelElement[0]; + } + return new ISynchronizeModelElement[] { element }; + } protected void associateDiffNode(ISynchronizeModelElement node) { IResource resource = node.getResource(); @@ -130,16 +130,16 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP * @param resources the resources to remove */ protected void removeFromViewer(IResource[] resources) { - List<ISynchronizeModelElement> elements = new ArrayList<>(); - for (int i = 0; i < resources.length; i++) { - IResource resource = resources[i]; + List<ISynchronizeModelElement> elements = new ArrayList<>(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; ISynchronizeModelElement element = getModelObject(resource); if(element != null) { - elements.add(element); + elements.add(element); } - } + } if (!elements.isEmpty()) { - removeFromViewer(elements.toArray(new ISynchronizeModelElement[elements.size()])); + removeFromViewer(elements.toArray(new ISynchronizeModelElement[elements.size()])); } } @@ -147,11 +147,11 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP protected void recursiveClearModelObjects(ISynchronizeModelElement node) { super.recursiveClearModelObjects(node); if (node == getModelRoot()) { - // If we are clearing everything under the root - // than just purge the resource map - resourceMap.clear(); - // Reassociate the root node to allow the children to be readded - associateRoot(getModelRoot()); + // If we are clearing everything under the root + // than just purge the resource map + resourceMap.clear(); + // Reassociate the root node to allow the children to be readded + associateRoot(getModelRoot()); } else { IResource resource = node.getResource(); if (resource != null) { @@ -166,10 +166,10 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP super.addToViewer(node); } - @Override + @Override protected boolean hasViewerState() { - return ! resourceMap.isEmpty(); - } + return ! resourceMap.isEmpty(); + } @Override public ISynchronizeModelElement[] getClosestExistingParents(IResource resource) { @@ -181,15 +181,15 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP } while(element == null && resource != null); } if (element == null) { - return new ISynchronizeModelElement[0]; + return new ISynchronizeModelElement[0]; } return new ISynchronizeModelElement[] { element }; } - @Override + @Override protected final void handleChanges(ISyncInfoTreeChangeEvent event, IProgressMonitor monitor) { - super.handleChanges(event, monitor); - } + super.handleChanges(event, monitor); + } @Override protected void handleResourceChanges(ISyncInfoTreeChangeEvent event) { @@ -205,12 +205,12 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP } } - /** - * The sync state for the existing diff node has changed and the new state - * is provided by the given sync info. - * @param diffNode the changed diff node - * @param info the new sync state - */ + /** + * The sync state for the existing diff node has changed and the new state + * is provided by the given sync info. + * @param diffNode the changed diff node + * @param info the new sync state + */ protected void handleChange(ISynchronizeModelElement diffNode, SyncInfo info) { IResource local = info.getLocal(); @@ -227,30 +227,30 @@ public abstract class SynchronizeModelProvider extends AbstractSynchronizeModelP } } - /** - * Add the give sync infos to the provider, creating - * any intermediate nodes a required. - * @param added the added infos - */ + /** + * Add the give sync infos to the provider, creating + * any intermediate nodes a required. + * @param added the added infos + */ protected void addResources(SyncInfo[] added) { for (int i = 0; i < added.length; i++) { SyncInfo info = added[i]; - addResource(info); + addResource(info); } } /** - * Add the give sync info to the provider, creating - * any intermediate nodes a required and adding any children as well - * @param info the added infos - */ - protected abstract void addResource(SyncInfo info); + * Add the give sync info to the provider, creating + * any intermediate nodes a required and adding any children as well + * @param info the added infos + */ + protected abstract void addResource(SyncInfo info); - /** + /** * Create the model object for the given sync info as a child of the given parent node. * @param parent the parent * @param info the info to be used for the new node * @return the created node */ - protected abstract ISynchronizeModelElement createModelObject(ISynchronizeModelElement parent, SyncInfo info); + protected abstract ISynchronizeModelElement createModelObject(ISynchronizeModelElement parent, SyncInfo info); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelUpdateHandler.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelUpdateHandler.java index 14aacad9c..e027dffc3 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelUpdateHandler.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeModelUpdateHandler.java @@ -59,9 +59,9 @@ import com.ibm.icu.text.SimpleDateFormat; * handler's thread. */ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implements IResourceChangeListener, ISyncInfoSetChangeListener { - private static final IWorkspaceRoot ROOT = ResourcesPlugin.getWorkspace().getRoot(); + private static final IWorkspaceRoot ROOT = ResourcesPlugin.getWorkspace().getRoot(); - // Event that indicates that the markers for a set of elements has changed + // Event that indicates that the markers for a set of elements has changed private static final int MARKERS_CHANGED = 1; private static final int BUSY_STATE_CHANGED = 2; private static final int RESET = 3; @@ -81,14 +81,14 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem * Custom event for posting marker changes */ class MarkerChangeEvent extends Event { - private final ISynchronizeModelElement[] elements; - public MarkerChangeEvent(ISynchronizeModelElement[] elements) { - super(MARKERS_CHANGED); - this.elements = elements; - } - public ISynchronizeModelElement[] getElements() { - return elements; - } + private final ISynchronizeModelElement[] elements; + public MarkerChangeEvent(ISynchronizeModelElement[] elements) { + super(MARKERS_CHANGED); + this.elements = elements; + } + public ISynchronizeModelElement[] getElements() { + return elements; + } } /** @@ -96,65 +96,65 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem */ class BusyStateChangeEvent extends Event { - private final ISynchronizeModelElement element; - private final boolean isBusy; - public BusyStateChangeEvent(ISynchronizeModelElement element, boolean isBusy) { - super(BUSY_STATE_CHANGED); - this.element = element; - this.isBusy = isBusy; - } - public ISynchronizeModelElement getElement() { - return element; - } - public boolean isBusy() { - return isBusy; - } + private final ISynchronizeModelElement element; + private final boolean isBusy; + public BusyStateChangeEvent(ISynchronizeModelElement element, boolean isBusy) { + super(BUSY_STATE_CHANGED); + this.element = element; + this.isBusy = isBusy; + } + public ISynchronizeModelElement getElement() { + return element; + } + public boolean isBusy() { + return isBusy; + } } /** * Custom event for posting sync info set changes */ class SyncInfoSetChangeEvent extends Event { - private final ISyncInfoSetChangeEvent event; - public SyncInfoSetChangeEvent(ISyncInfoSetChangeEvent event) { - super(SYNC_INFO_SET_CHANGED); - this.event = event; - } - public ISyncInfoSetChangeEvent getEvent() { - return event; - } + private final ISyncInfoSetChangeEvent event; + public SyncInfoSetChangeEvent(ISyncInfoSetChangeEvent event) { + super(SYNC_INFO_SET_CHANGED); + this.event = event; + } + public ISyncInfoSetChangeEvent getEvent() { + return event; + } } private IPropertyChangeListener listener = event -> { if (event.getProperty() == ISynchronizeModelElement.BUSY_PROPERTY) { Object source = event.getSource(); if (source instanceof ISynchronizeModelElement) - updateBusyState((ISynchronizeModelElement)source, ((Boolean)event.getNewValue()).booleanValue()); + updateBusyState((ISynchronizeModelElement)source, ((Boolean)event.getNewValue()).booleanValue()); } }; - private boolean performingBackgroundUpdate; + private boolean performingBackgroundUpdate; - /* - * Map used to keep track of additions so they can be added in batch at the end of the update - */ - private Map<ISynchronizeModelElement, Set<ISynchronizeModelElement>> additionsMap; + /* + * Map used to keep track of additions so they can be added in batch at the end of the update + */ + private Map<ISynchronizeModelElement, Set<ISynchronizeModelElement>> additionsMap; /** - * Create the marker update handler. - */ - public SynchronizeModelUpdateHandler(AbstractSynchronizeModelProvider provider) { - super(TeamUIMessages.SynchronizeModelProvider_0, TeamUIMessages.SynchronizeModelUpdateHandler_0); // - this.provider = provider; - ResourcesPlugin.getWorkspace().addResourceChangeListener(this); - provider.getSyncInfoSet().addSyncSetChangedListener(this); - } - - /** - * Return the marker types that are of interest to this handler. - * @return the marker types that are of interest to this handler - */ - protected String[] getMarkerTypes() { + * Create the marker update handler. + */ + public SynchronizeModelUpdateHandler(AbstractSynchronizeModelProvider provider) { + super(TeamUIMessages.SynchronizeModelProvider_0, TeamUIMessages.SynchronizeModelUpdateHandler_0); // + this.provider = provider; + ResourcesPlugin.getWorkspace().addResourceChangeListener(this); + provider.getSyncInfoSet().addSyncSetChangedListener(this); + } + + /** + * Return the marker types that are of interest to this handler. + * @return the marker types that are of interest to this handler + */ + protected String[] getMarkerTypes() { return new String[] {IMarker.PROBLEM}; } @@ -181,38 +181,38 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem IMarkerDelta delta = markerDeltas[i]; IResource resource = delta.getResource(); if (!handledResources.contains(resource)) { - handledResources.add(resource); - ISynchronizeModelElement[] elements = provider.getClosestExistingParents(delta.getResource()); + handledResources.add(resource); + ISynchronizeModelElement[] elements = provider.getClosestExistingParents(delta.getResource()); if(elements != null && elements.length > 0) { - for (int j = 0; j < elements.length; j++) { - ISynchronizeModelElement element = elements[j]; - changes.add(element); - } + for (int j = 0; j < elements.length; j++) { + ISynchronizeModelElement element = elements[j]; + changes.add(element); + } } } } } if (!changes.isEmpty()) { - updateMarkersFor(changes.toArray(new ISynchronizeModelElement[changes.size()])); + updateMarkersFor(changes.toArray(new ISynchronizeModelElement[changes.size()])); } } - private void updateMarkersFor(ISynchronizeModelElement[] elements) { - queueEvent(new MarkerChangeEvent(elements), false /* not on front of queue */); - } + private void updateMarkersFor(ISynchronizeModelElement[] elements) { + queueEvent(new MarkerChangeEvent(elements), false /* not on front of queue */); + } - protected void updateBusyState(ISynchronizeModelElement element, boolean isBusy) { - queueEvent(new BusyStateChangeEvent(element, isBusy), false /* not on front of queue */); - } + protected void updateBusyState(ISynchronizeModelElement element, boolean isBusy) { + queueEvent(new BusyStateChangeEvent(element, isBusy), false /* not on front of queue */); + } - @Override + @Override protected void processEvent(Event event, IProgressMonitor monitor) throws CoreException { - switch (event.getType()) { + switch (event.getType()) { case BackgroundEventHandler.RUNNABLE_EVENT : executeRunnable(event, monitor); break; - case MARKERS_CHANGED: + case MARKERS_CHANGED: // Changes contains all elements that need their labels updated long start = System.currentTimeMillis(); ISynchronizeModelElement[] elements = getChangedElements(event); @@ -227,46 +227,46 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem String took = TIME_FORMAT.format(new Date(time)); System.out.println(took + " for " + elements.length + " files"); //$NON-NLS-1$//$NON-NLS-2$ } - break; - case BUSY_STATE_CHANGED: - BusyStateChangeEvent e = (BusyStateChangeEvent)event; - queueForLabelUpdate(e.getElement()); - if (e.isBusy()) { - // indicate that we want an early dispatch to show busy elements - dispatchEarly = true; - } - break; - case RESET: - // Perform the reset immediately - pendingLabelUpdates.clear(); - provider.reset(); - break; - case SYNC_INFO_SET_CHANGED: - // Handle the sync change immediately - handleChanges(((SyncInfoSetChangeEvent)event).getEvent(), monitor); - default: - break; - } - } - - private ISynchronizeModelElement[] getChangedElements(Event event) { - if (event.getType() == MARKERS_CHANGED) { - return ((MarkerChangeEvent)event).getElements(); - } - return new ISynchronizeModelElement[0]; - } - - @Override + break; + case BUSY_STATE_CHANGED: + BusyStateChangeEvent e = (BusyStateChangeEvent)event; + queueForLabelUpdate(e.getElement()); + if (e.isBusy()) { + // indicate that we want an early dispatch to show busy elements + dispatchEarly = true; + } + break; + case RESET: + // Perform the reset immediately + pendingLabelUpdates.clear(); + provider.reset(); + break; + case SYNC_INFO_SET_CHANGED: + // Handle the sync change immediately + handleChanges(((SyncInfoSetChangeEvent)event).getEvent(), monitor); + default: + break; + } + } + + private ISynchronizeModelElement[] getChangedElements(Event event) { + if (event.getType() == MARKERS_CHANGED) { + return ((MarkerChangeEvent)event).getElements(); + } + return new ISynchronizeModelElement[0]; + } + + @Override protected boolean doDispatchEvents(IProgressMonitor monitor) throws TeamException { // Fire label changed - dispatchEarly = false; - if (pendingLabelUpdates.isEmpty()) { - return false; - } else { + dispatchEarly = false; + if (pendingLabelUpdates.isEmpty()) { + return false; + } else { Utils.asyncExec((Runnable) () -> firePendingLabelUpdates(), getViewer()); return true; - } - } + } + } /** * Forces the viewer to update the labels for queued elemens @@ -287,7 +287,7 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem * Forces the viewer to update the labels for the given elements */ private void updateLabels(Object[] elements) { - StructuredViewer tree = getViewer(); + StructuredViewer tree = getViewer(); if (Utils.canUpdateViewer(tree)) { tree.update(elements, null); } @@ -390,287 +390,287 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem /* * Queue an event that will reset the provider */ - private void reset() { - queueEvent(new ResourceEvent(ROOT, RESET, IResource.DEPTH_INFINITE), false); - } + private void reset() { + queueEvent(new ResourceEvent(ROOT, RESET, IResource.DEPTH_INFINITE), false); + } - public void dispose() { - shutdown(); - ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); - provider.getSyncInfoSet().removeSyncSetChangedListener(this); - } + public void dispose() { + shutdown(); + ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); + provider.getSyncInfoSet().removeSyncSetChangedListener(this); + } - @Override + @Override protected long getShortDispatchDelay() { - if (dispatchEarly) { - dispatchEarly = false; - return EARLY_DISPATCH_INCREMENT; - } - return super.getShortDispatchDelay(); - } - - /** - * This method is invoked whenever a node is added to the viewer - * by the provider or a sub-provider. The handler adds an update - * listener to the node and notifies the root provider that - * a node was added. - * @param element the added element - * @param provider the provider that added the element - */ - public void nodeAdded(ISynchronizeModelElement element, AbstractSynchronizeModelProvider provider) { - element.addPropertyChangeListener(listener); - this.provider.nodeAdded(element, provider); - if (Policy.DEBUG_SYNC_MODELS) { - System.out.println("Node added: " + getDebugDisplayLabel(element) + " -> " + getDebugDisplayLabel((ISynchronizeModelElement)element.getParent()) + " : " + getDebugDisplayLabel(provider)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - /** - * This method is invoked whenever a node is removed the viewer - * by the provider or a sub-provider. The handler removes any - * listener and notifies the root provider that - * a node was removed. The node removed may have children for which - * a nodeRemoved callback was not invoked (see modelObjectCleared). - * @param element the removed element - * @param provider the provider that added the element - */ - public void nodeRemoved(ISynchronizeModelElement element, AbstractSynchronizeModelProvider provider) { - element.removePropertyChangeListener(listener); - this.provider.nodeRemoved(element, provider); - if (Policy.DEBUG_SYNC_MODELS) { - System.out.println("Node removed: " + getDebugDisplayLabel(element) + " -> " + getDebugDisplayLabel((ISynchronizeModelElement)element.getParent()) + " : " + getDebugDisplayLabel(provider)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - /** - * This method is invoked whenever a model object (i.e. node) - * is cleared from the model. This is similar to node removal but - * is deep. - * @param node the node that was cleared - */ - public void modelObjectCleared(ISynchronizeModelElement node) { - node.removePropertyChangeListener(listener); - this.provider.modelObjectCleared(node); - if (Policy.DEBUG_SYNC_MODELS) { - System.out.println("Node cleared: " + getDebugDisplayLabel(node)); //$NON-NLS-1$ - } - } - - private String getDebugDisplayLabel(ISynchronizeModelElement node) { - if (node == null) { - return "ROOT"; //$NON-NLS-1$ - } - if (node.getResource() != null) { - return node.getResource().getFullPath().toString(); - } - return node.getName(); - } - - private String getDebugDisplayLabel(AbstractSynchronizeModelProvider provider2) { - return provider2.toString(); - } - - @Override + if (dispatchEarly) { + dispatchEarly = false; + return EARLY_DISPATCH_INCREMENT; + } + return super.getShortDispatchDelay(); + } + + /** + * This method is invoked whenever a node is added to the viewer + * by the provider or a sub-provider. The handler adds an update + * listener to the node and notifies the root provider that + * a node was added. + * @param element the added element + * @param provider the provider that added the element + */ + public void nodeAdded(ISynchronizeModelElement element, AbstractSynchronizeModelProvider provider) { + element.addPropertyChangeListener(listener); + this.provider.nodeAdded(element, provider); + if (Policy.DEBUG_SYNC_MODELS) { + System.out.println("Node added: " + getDebugDisplayLabel(element) + " -> " + getDebugDisplayLabel((ISynchronizeModelElement)element.getParent()) + " : " + getDebugDisplayLabel(provider)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + + /** + * This method is invoked whenever a node is removed the viewer + * by the provider or a sub-provider. The handler removes any + * listener and notifies the root provider that + * a node was removed. The node removed may have children for which + * a nodeRemoved callback was not invoked (see modelObjectCleared). + * @param element the removed element + * @param provider the provider that added the element + */ + public void nodeRemoved(ISynchronizeModelElement element, AbstractSynchronizeModelProvider provider) { + element.removePropertyChangeListener(listener); + this.provider.nodeRemoved(element, provider); + if (Policy.DEBUG_SYNC_MODELS) { + System.out.println("Node removed: " + getDebugDisplayLabel(element) + " -> " + getDebugDisplayLabel((ISynchronizeModelElement)element.getParent()) + " : " + getDebugDisplayLabel(provider)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + } + + /** + * This method is invoked whenever a model object (i.e. node) + * is cleared from the model. This is similar to node removal but + * is deep. + * @param node the node that was cleared + */ + public void modelObjectCleared(ISynchronizeModelElement node) { + node.removePropertyChangeListener(listener); + this.provider.modelObjectCleared(node); + if (Policy.DEBUG_SYNC_MODELS) { + System.out.println("Node cleared: " + getDebugDisplayLabel(node)); //$NON-NLS-1$ + } + } + + private String getDebugDisplayLabel(ISynchronizeModelElement node) { + if (node == null) { + return "ROOT"; //$NON-NLS-1$ + } + if (node.getResource() != null) { + return node.getResource().getFullPath().toString(); + } + return node.getName(); + } + + private String getDebugDisplayLabel(AbstractSynchronizeModelProvider provider2) { + return provider2.toString(); + } + + @Override public void syncInfoSetReset(SyncInfoSet set, IProgressMonitor monitor) { if(provider.isDisposed()) { set.removeSyncSetChangedListener(this); } else { - reset(); + reset(); } - } + } - @Override + @Override public void syncInfoChanged(final ISyncInfoSetChangeEvent event, IProgressMonitor monitor) { if (! (event instanceof ISyncInfoTreeChangeEvent)) { reset(); } else { queueEvent(new SyncInfoSetChangeEvent(event), false); } - } + } - /* - * Handle the sync info set change event in the UI thread. - */ - private void handleChanges(final ISyncInfoSetChangeEvent event, final IProgressMonitor monitor) { - runViewUpdate(() -> { + /* + * Handle the sync info set change event in the UI thread. + */ + private void handleChanges(final ISyncInfoSetChangeEvent event, final IProgressMonitor monitor) { + runViewUpdate(() -> { provider.handleChanges((ISyncInfoTreeChangeEvent)event, monitor); firePendingLabelUpdates(); }, true /* preserve expansion */); - } + } - @Override + @Override public void syncInfoSetErrors(SyncInfoSet set, ITeamStatus[] errors, IProgressMonitor monitor) { // When errors occur we currently don't process them. It may be possible to decorate // elements in the model with errors, but currently we prefer to let ignore and except // another listener to display them. - } - - public ISynchronizeModelProvider getProvider() { - return provider; - } - - public void connect(IProgressMonitor monitor) { - getProvider().getSyncInfoSet().connect(this, monitor); - } - - public void runViewUpdate(final Runnable runnable, final boolean preserveExpansion) { - if (Utils.canUpdateViewer(getViewer()) || isPerformingBackgroundUpdate()) { - internalRunViewUpdate(runnable, preserveExpansion); - } else { - if (Thread.currentThread() != getEventHandlerJob().getThread()) { - // Run view update should only be called from the UI thread or - // the update handler thread. - // We will log the problem for now and make it an assert later - TeamUIPlugin.log(IStatus.WARNING, "View update invoked from invalid thread", new TeamException("View update invoked from invalid thread")); //$NON-NLS-1$ //$NON-NLS-2$ - } - final Control ctrl = getViewer().getControl(); - if (ctrl != null && !ctrl.isDisposed()) { - ctrl.getDisplay().syncExec(() -> { + } + + public ISynchronizeModelProvider getProvider() { + return provider; + } + + public void connect(IProgressMonitor monitor) { + getProvider().getSyncInfoSet().connect(this, monitor); + } + + public void runViewUpdate(final Runnable runnable, final boolean preserveExpansion) { + if (Utils.canUpdateViewer(getViewer()) || isPerformingBackgroundUpdate()) { + internalRunViewUpdate(runnable, preserveExpansion); + } else { + if (Thread.currentThread() != getEventHandlerJob().getThread()) { + // Run view update should only be called from the UI thread or + // the update handler thread. + // We will log the problem for now and make it an assert later + TeamUIPlugin.log(IStatus.WARNING, "View update invoked from invalid thread", new TeamException("View update invoked from invalid thread")); //$NON-NLS-1$ //$NON-NLS-2$ + } + final Control ctrl = getViewer().getControl(); + if (ctrl != null && !ctrl.isDisposed()) { + ctrl.getDisplay().syncExec(() -> { if (!ctrl.isDisposed()) { BusyIndicator.showWhile(ctrl.getDisplay(), () -> internalRunViewUpdate(runnable, preserveExpansion)); } }); - } - } - } - - /* - * Return whether the event handler is performing a background view update. - * In other words, a client has invoked <code>performUpdate</code>. - */ - public boolean isPerformingBackgroundUpdate() { - return Thread.currentThread() == getEventHandlerJob().getThread() && performingBackgroundUpdate; - } - - /* - * Method that can be called from the UI thread to update the view model. - */ - private void internalRunViewUpdate(final Runnable runnable, boolean preserveExpansion) { - StructuredViewer viewer = getViewer(); - IResource[] expanded = null; - IResource[] selected = null; + } + } + } + + /* + * Return whether the event handler is performing a background view update. + * In other words, a client has invoked <code>performUpdate</code>. + */ + public boolean isPerformingBackgroundUpdate() { + return Thread.currentThread() == getEventHandlerJob().getThread() && performingBackgroundUpdate; + } + + /* + * Method that can be called from the UI thread to update the view model. + */ + private void internalRunViewUpdate(final Runnable runnable, boolean preserveExpansion) { + StructuredViewer viewer = getViewer(); + IResource[] expanded = null; + IResource[] selected = null; try { - if (Utils.canUpdateViewer(viewer)) { - viewer.getControl().setRedraw(false); - if (preserveExpansion) { - expanded = provider.getExpandedResources(); - selected = provider.getSelectedResources(); - } - if (viewer instanceof AbstractTreeViewer && additionsMap == null) - additionsMap = new HashMap<>(); - } + if (Utils.canUpdateViewer(viewer)) { + viewer.getControl().setRedraw(false); + if (preserveExpansion) { + expanded = provider.getExpandedResources(); + selected = provider.getSelectedResources(); + } + if (viewer instanceof AbstractTreeViewer && additionsMap == null) + additionsMap = new HashMap<>(); + } runnable.run(); } finally { - if (Utils.canUpdateViewer(viewer)) { - try { - if (additionsMap != null && !additionsMap.isEmpty() && Utils.canUpdateViewer(viewer)) { - for (Iterator iter = additionsMap.keySet().iterator(); iter.hasNext();) { - ISynchronizeModelElement parent = (ISynchronizeModelElement) iter.next(); - if (Policy.DEBUG_SYNC_MODELS) { - System.out.println("Adding child view items of " + parent.getName()); //$NON-NLS-1$ - } - Set<ISynchronizeModelElement> toAdd = additionsMap.get(parent); - ((AbstractTreeViewer)viewer).add(parent, toAdd.toArray(new Object[toAdd.size()])); - } - additionsMap = null; - } - if (expanded != null) { - provider.expandResources(expanded); - } - if (selected != null) { - provider.selectResources(selected); - } - } finally { - viewer.getControl().setRedraw(true); - } - } + if (Utils.canUpdateViewer(viewer)) { + try { + if (additionsMap != null && !additionsMap.isEmpty() && Utils.canUpdateViewer(viewer)) { + for (Iterator iter = additionsMap.keySet().iterator(); iter.hasNext();) { + ISynchronizeModelElement parent = (ISynchronizeModelElement) iter.next(); + if (Policy.DEBUG_SYNC_MODELS) { + System.out.println("Adding child view items of " + parent.getName()); //$NON-NLS-1$ + } + Set<ISynchronizeModelElement> toAdd = additionsMap.get(parent); + ((AbstractTreeViewer)viewer).add(parent, toAdd.toArray(new Object[toAdd.size()])); + } + additionsMap = null; + } + if (expanded != null) { + provider.expandResources(expanded); + } + if (selected != null) { + provider.selectResources(selected); + } + } finally { + viewer.getControl().setRedraw(true); + } + } } ISynchronizeModelElement root = provider.getModelRoot(); if(root instanceof SynchronizeModelElement) ((SynchronizeModelElement)root).fireChanges(); - } - - /** - * Execute a runnable which performs an update of the model being displayed - * by the handler's provider. The runnable should be executed in a thread-safe manner - * which esults in the view being updated. - * @param runnable the runnable which updates the model. - * @param preserveExpansion whether the expansion of the view should be preserver - * @param updateInUIThread if <code>true</code>, the model will be updated in the - * UI thread. Otherwise, the model will be updated in the handler thread and the view - * updated in the UI thread at the end. - */ - public void performUpdate(final IWorkspaceRunnable runnable, boolean preserveExpansion, boolean updateInUIThread) { - if (updateInUIThread) { - queueEvent(new BackgroundEventHandler.RunnableEvent(getUIUpdateRunnable(runnable, preserveExpansion), true), true); - } else { - queueEvent(new BackgroundEventHandler.RunnableEvent(getBackgroundUpdateRunnable(runnable, preserveExpansion), true), true); - } - } - - /** - * Wrap the runnable in an outer runnable that preserves expansion. - */ - private IWorkspaceRunnable getUIUpdateRunnable(final IWorkspaceRunnable runnable, final boolean preserveExpansion) { - return monitor -> { - final CoreException[] exception = new CoreException[] { null }; - runViewUpdate(() -> { - try { - runnable.run(monitor); - } catch (CoreException e) { - exception[0] = e; - } + } + + /** + * Execute a runnable which performs an update of the model being displayed + * by the handler's provider. The runnable should be executed in a thread-safe manner + * which esults in the view being updated. + * @param runnable the runnable which updates the model. + * @param preserveExpansion whether the expansion of the view should be preserver + * @param updateInUIThread if <code>true</code>, the model will be updated in the + * UI thread. Otherwise, the model will be updated in the handler thread and the view + * updated in the UI thread at the end. + */ + public void performUpdate(final IWorkspaceRunnable runnable, boolean preserveExpansion, boolean updateInUIThread) { + if (updateInUIThread) { + queueEvent(new BackgroundEventHandler.RunnableEvent(getUIUpdateRunnable(runnable, preserveExpansion), true), true); + } else { + queueEvent(new BackgroundEventHandler.RunnableEvent(getBackgroundUpdateRunnable(runnable, preserveExpansion), true), true); + } + } + + /** + * Wrap the runnable in an outer runnable that preserves expansion. + */ + private IWorkspaceRunnable getUIUpdateRunnable(final IWorkspaceRunnable runnable, final boolean preserveExpansion) { + return monitor -> { + final CoreException[] exception = new CoreException[] { null }; + runViewUpdate(() -> { + try { + runnable.run(monitor); + } catch (CoreException e) { + exception[0] = e; + } }, true /* preserve expansion */); - if (exception[0] != null) - throw exception[0]; + if (exception[0] != null) + throw exception[0]; }; - } - - /* - * Wrap the runnable in an outer runnable that preserves expansion if requested - * and refreshes the view when the update is completed. - */ - private IWorkspaceRunnable getBackgroundUpdateRunnable(final IWorkspaceRunnable runnable, final boolean preserveExpansion) { - return new IWorkspaceRunnable() { - IResource[] expanded; - IResource[] selected; - @Override + } + + /* + * Wrap the runnable in an outer runnable that preserves expansion if requested + * and refreshes the view when the update is completed. + */ + private IWorkspaceRunnable getBackgroundUpdateRunnable(final IWorkspaceRunnable runnable, final boolean preserveExpansion) { + return new IWorkspaceRunnable() { + IResource[] expanded; + IResource[] selected; + @Override public void run(IProgressMonitor monitor) throws CoreException { - if (preserveExpansion) - recordExpandedResources(); - try { - performingBackgroundUpdate = true; - runnable.run(monitor); - } finally { - performingBackgroundUpdate = false; - } - updateView(); - - } - private void recordExpandedResources() { - final StructuredViewer viewer = getViewer(); - if (viewer != null && !viewer.getControl().isDisposed() && viewer instanceof AbstractTreeViewer) { - viewer.getControl().getDisplay().syncExec(() -> { + if (preserveExpansion) + recordExpandedResources(); + try { + performingBackgroundUpdate = true; + runnable.run(monitor); + } finally { + performingBackgroundUpdate = false; + } + updateView(); + + } + private void recordExpandedResources() { + final StructuredViewer viewer = getViewer(); + if (viewer != null && !viewer.getControl().isDisposed() && viewer instanceof AbstractTreeViewer) { + viewer.getControl().getDisplay().syncExec(() -> { if (viewer != null && !viewer.getControl().isDisposed()) { - expanded = provider.getExpandedResources(); - selected = provider.getSelectedResources(); + expanded = provider.getExpandedResources(); + selected = provider.getSelectedResources(); } }); - } - } - private void updateView() { - // Refresh the view and then set the expansion - runViewUpdate(() -> { - provider.getViewer().refresh(); - if (expanded != null) - provider.expandResources(expanded); - if (selected != null) - provider.selectResources(selected); + } + } + private void updateView() { + // Refresh the view and then set the expansion + runViewUpdate(() -> { + provider.getViewer().refresh(); + if (expanded != null) + provider.expandResources(expanded); + if (selected != null) + provider.selectResources(selected); }, false /* do not preserve expansion (since it is done above) */); - } - }; - } + } + }; + } /* * Execute the RunnableEvent @@ -689,29 +689,29 @@ public class SynchronizeModelUpdateHandler extends BackgroundEventHandler implem } } - /** - * Add the element to the viewer. - * @param parent the parent of the element which is already added to the viewer - * @param element the element to be added to the viewer - */ - protected void doAdd(ISynchronizeModelElement parent, ISynchronizeModelElement element) { - if (additionsMap == null) { - if (Policy.DEBUG_SYNC_MODELS) { - System.out.println("Added view item " + element.getName()); //$NON-NLS-1$ - } - AbstractTreeViewer viewer = (AbstractTreeViewer)getViewer(); - viewer.add(parent, element); - } else { - // Accumulate the additions - if (Policy.DEBUG_SYNC_MODELS) { - System.out.println("Queueing view item for addition " + element.getName()); //$NON-NLS-1$ - } - Set<ISynchronizeModelElement> toAdd = additionsMap.get(parent); - if (toAdd == null) { - toAdd = new HashSet<>(); - additionsMap.put(parent, toAdd); - } - toAdd.add(element); - } - } + /** + * Add the element to the viewer. + * @param parent the parent of the element which is already added to the viewer + * @param element the element to be added to the viewer + */ + protected void doAdd(ISynchronizeModelElement parent, ISynchronizeModelElement element) { + if (additionsMap == null) { + if (Policy.DEBUG_SYNC_MODELS) { + System.out.println("Added view item " + element.getName()); //$NON-NLS-1$ + } + AbstractTreeViewer viewer = (AbstractTreeViewer)getViewer(); + viewer.add(parent, element); + } else { + // Accumulate the additions + if (Policy.DEBUG_SYNC_MODELS) { + System.out.println("Queueing view item for addition " + element.getName()); //$NON-NLS-1$ + } + Set<ISynchronizeModelElement> toAdd = additionsMap.get(parent); + if (toAdd == null) { + toAdd = new HashSet<>(); + additionsMap.put(parent, toAdd); + } + toAdd.add(element); + } + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizePageConfiguration.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizePageConfiguration.java index 6e98c6ee4..3380973b9 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizePageConfiguration.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizePageConfiguration.java @@ -116,10 +116,10 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp public static final int CHECKBOX = TreeViewerAdvisor.CHECKBOX; - // State flags - private static final int UNINITIALIZED = 0; - private static final int INITIALIZED = 1; - private static final int DISPOSED = 2; + // State flags + private static final int UNINITIALIZED = 0; + private static final int INITIALIZED = 1; + private static final int DISPOSED = 2; private ISynchronizeParticipant participant; private ISynchronizePageSite site; @@ -192,25 +192,25 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp @Override public void addActionContribution(SynchronizePageActionGroup contribution) { - int currentActionState; + int currentActionState; synchronized(actionContributions) { - // Determine the action state while locked so we handle the addition properly below - currentActionState = actionState; - if (currentActionState != DISPOSED) - actionContributions.add(contribution); + // Determine the action state while locked so we handle the addition properly below + currentActionState = actionState; + if (currentActionState != DISPOSED) + actionContributions.add(contribution); } if (currentActionState == INITIALIZED) { - // This is tricky because we are doing the initialize while not locked. - // It is possible that another thread is concurrently disposing the contributions - // but we can't lock while calling client code. We'll change for DISPOSE after - // we initialize and, if we are disposed, we dispose this one, just in case. + // This is tricky because we are doing the initialize while not locked. + // It is possible that another thread is concurrently disposing the contributions + // but we can't lock while calling client code. We'll change for DISPOSE after + // we initialize and, if we are disposed, we dispose this one, just in case. contribution.initialize(this); - if (actionState == DISPOSED) { - contribution .dispose(); - } + if (actionState == DISPOSED) { + contribution .dispose(); + } } else if (currentActionState == DISPOSED) { - contribution.dispose(); - } + contribution.dispose(); + } } @Override @@ -244,16 +244,16 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp @Override public void initialize(final ISynchronizePageConfiguration configuration) { super.initialize(configuration); - // need to synchronize here to ensure that actions that are added concurrently also get initialized - final Object[] listeners; - synchronized(actionContributions) { - if (actionState != UNINITIALIZED) { - // Initialization has already taken place so just return. - return; - } - actionState = INITIALIZED; - listeners = actionContributions.getListeners(); - } + // need to synchronize here to ensure that actions that are added concurrently also get initialized + final Object[] listeners; + synchronized(actionContributions) { + if (actionState != UNINITIALIZED) { + // Initialization has already taken place so just return. + return; + } + actionState = INITIALIZED; + listeners = actionContributions.getListeners(); + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { @@ -272,10 +272,10 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp @Override public void setContext(final ActionContext context) { super.setContext(context); - final Object[] listeners; - synchronized(actionContributions) { - listeners = actionContributions.getListeners(); - } + final Object[] listeners; + synchronized(actionContributions) { + listeners = actionContributions.getListeners(); + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { @@ -298,10 +298,10 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp */ @Override public void fillContextMenu(final IMenuManager manager) { - final Object[] listeners; - synchronized(actionContributions) { - listeners = actionContributions.getListeners(); - } + final Object[] listeners; + synchronized(actionContributions) { + listeners = actionContributions.getListeners(); + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { @@ -326,10 +326,10 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp if (actionState == UNINITIALIZED) { initialize(this); } - final Object[] listeners; - synchronized(actionContributions) { - listeners = actionContributions.getListeners(); - } + final Object[] listeners; + synchronized(actionContributions) { + listeners = actionContributions.getListeners(); + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { @@ -347,10 +347,10 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp @Override public void updateActionBars() { - final Object[] listeners; - synchronized(actionContributions) { - listeners = actionContributions.getListeners(); - } + final Object[] listeners; + synchronized(actionContributions) { + listeners = actionContributions.getListeners(); + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { @@ -368,10 +368,10 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp @Override public void modelChanged(final ISynchronizeModelElement root) { - final Object[] listeners; - synchronized(actionContributions) { - listeners = actionContributions.getListeners(); - } + final Object[] listeners; + synchronized(actionContributions) { + listeners = actionContributions.getListeners(); + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { @@ -390,11 +390,11 @@ public class SynchronizePageConfiguration extends SynchronizePageActionGroup imp @Override public void dispose() { super.dispose(); - final Object[] listeners; - synchronized(actionContributions) { - listeners = actionContributions.getListeners(); - actionState = DISPOSED; - } + final Object[] listeners; + synchronized(actionContributions) { + listeners = actionContributions.getListeners(); + actionState = DISPOSED; + } for (int i= 0; i < listeners.length; i++) { final SynchronizePageActionGroup contribution = (SynchronizePageActionGroup)listeners[i]; SafeRunner.run(new ISafeRunnable() { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeView.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeView.java index f38e5bc85..bb2bffbd6 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeView.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeView.java @@ -179,8 +179,8 @@ public class SynchronizeView extends PageBookView implements ISynchronizeView, I * Preference key to save */ private static final String KEY_LAST_ACTIVE_PARTICIPANT_ID = "lastactiveparticipant_id"; //$NON-NLS-1$ - private static final String KEY_LAST_ACTIVE_PARTICIPANT_SECONDARY_ID = "lastactiveparticipant_sec_id"; //$NON-NLS-1$ - private static final String KEY_LINK_WITH_EDITOR = "linkWithEditor"; //$NON-NLS-1$ + private static final String KEY_LAST_ACTIVE_PARTICIPANT_SECONDARY_ID = "lastactiveparticipant_sec_id"; //$NON-NLS-1$ + private static final String KEY_LINK_WITH_EDITOR = "linkWithEditor"; //$NON-NLS-1$ private static final String KEY_SETTINGS_SECTION= "SynchronizeViewSettings"; //$NON-NLS-1$ @@ -338,14 +338,14 @@ public class SynchronizeView extends PageBookView implements ISynchronizeView, I getSite().getPage().removePartListener(fLinkWithEditorListener); } - /** - * - */ - private void rememberCurrentParticipant() { - IDialogSettings section = getDialogSettings(); - section.put(KEY_LAST_ACTIVE_PARTICIPANT_ID, activeParticipantRef.getId()); - section.put(KEY_LAST_ACTIVE_PARTICIPANT_SECONDARY_ID, activeParticipantRef.getSecondaryId()); - } + /** + * + */ + private void rememberCurrentParticipant() { + IDialogSettings section = getDialogSettings(); + section.put(KEY_LAST_ACTIVE_PARTICIPANT_ID, activeParticipantRef.getId()); + section.put(KEY_LAST_ACTIVE_PARTICIPANT_SECONDARY_ID, activeParticipantRef.getSecondaryId()); + } @Override protected IPage createDefaultPage(PageBook book) { @@ -659,7 +659,7 @@ public class SynchronizeView extends PageBookView implements ISynchronizeView, I private String getSettingsKey(ISynchronizeParticipant participant) { String id = participant.getId(); String secondaryId = participant.getSecondaryId(); - return secondaryId == null ? id : id + '.' + secondaryId; + return secondaryId == null ? id : id + '.' + secondaryId; } private IDialogSettings getDialogSettings(ISynchronizeParticipant participant) { @@ -1104,7 +1104,7 @@ public class SynchronizeView extends PageBookView implements ISynchronizeView, I if (input instanceof IEditorInput) { return showInput(getInputFromEditor((IEditorInput) input)); } - return showInput(input); + return showInput(input); } return false; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeViewWorkbenchPart.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeViewWorkbenchPart.java index 479e016fe..425806ddb 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeViewWorkbenchPart.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/SynchronizeViewWorkbenchPart.java @@ -33,7 +33,7 @@ public class SynchronizeViewWorkbenchPart implements IWorkbenchPart { @Override public boolean equals(Object obj) { return (obj instanceof SynchronizeViewWorkbenchPart) && - participant.equals(((SynchronizeViewWorkbenchPart)obj).getParticipant()); + participant.equals(((SynchronizeViewWorkbenchPart)obj).getParticipant()); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/TreeViewerAdvisor.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/TreeViewerAdvisor.java index a4fc927c9..1223f1640 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/TreeViewerAdvisor.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/TreeViewerAdvisor.java @@ -166,16 +166,16 @@ public class TreeViewerAdvisor extends AbstractTreeViewerAdvisor { * @param configuration */ protected SynchronizeModelManager createModelManager(ISynchronizePageConfiguration configuration) { - ISynchronizeParticipant participant = configuration.getParticipant(); - if (participant instanceof IChangeSetProvider) { - IChangeSetProvider provider = (IChangeSetProvider) participant; - ChangeSetCapability changeSetCapability = provider.getChangeSetCapability(); - if (changeSetCapability != null) { - if (changeSetCapability.supportsActiveChangeSets() || changeSetCapability.supportsCheckedInChangeSets()) { - return new ChangeSetModelManager(configuration); - } - } - } + ISynchronizeParticipant participant = configuration.getParticipant(); + if (participant instanceof IChangeSetProvider) { + IChangeSetProvider provider = (IChangeSetProvider) participant; + ChangeSetCapability changeSetCapability = provider.getChangeSetCapability(); + if (changeSetCapability != null) { + if (changeSetCapability.supportsActiveChangeSets() || changeSetCapability.supportsCheckedInChangeSets()) { + return new ChangeSetModelManager(configuration); + } + } + } return new HierarchicalModelManager(configuration); } @@ -240,21 +240,21 @@ public class TreeViewerAdvisor extends AbstractTreeViewerAdvisor { viewer.setSorter(modelProvider.getViewerSorter()); viewer.setInput(modelRoot); modelProvider.addPropertyChangeListener(event -> { - if (event.getProperty() == ISynchronizeModelProvider.P_VIEWER_SORTER) { - if (viewer != null && !viewer.getControl().isDisposed()) { - viewer.getControl().getDisplay().syncExec(() -> { - if (viewer != null && !viewer.getControl().isDisposed()) { - ViewerSorter newSorter = modelProvider.getViewerSorter(); - ViewerSorter oldSorter = viewer.getSorter(); - if (newSorter == oldSorter) { - viewer.refresh(); - } else { - viewer.setSorter(newSorter); - } - } + if (event.getProperty() == ISynchronizeModelProvider.P_VIEWER_SORTER) { + if (viewer != null && !viewer.getControl().isDisposed()) { + viewer.getControl().getDisplay().syncExec(() -> { + if (viewer != null && !viewer.getControl().isDisposed()) { + ViewerSorter newSorter = modelProvider.getViewerSorter(); + ViewerSorter oldSorter = viewer.getSorter(); + if (newSorter == oldSorter) { + viewer.refresh(); + } else { + viewer.setSorter(newSorter); + } + } }); - } - } + } + } }); } } @@ -271,24 +271,24 @@ public class TreeViewerAdvisor extends AbstractTreeViewerAdvisor { final DragSourceListener listener = new DragSourceListener() { - @Override + @Override public void dragStart(DragSourceEvent event) { final IStructuredSelection selection = viewer.getStructuredSelection(); - final Object [] array= selection.toArray(); - event.doit= Utils.getResources(array).length > 0; + final Object [] array= selection.toArray(); + event.doit= Utils.getResources(array).length > 0; } - @Override + @Override public void dragSetData(DragSourceEvent event) { - if (ResourceTransfer.getInstance().isSupportedType(event.dataType)) { - final IStructuredSelection selection= viewer.getStructuredSelection(); - final Object [] array= selection.toArray(); - event.data= Utils.getResources(array); - } - } + if (ResourceTransfer.getInstance().isSupportedType(event.dataType)) { + final IStructuredSelection selection= viewer.getStructuredSelection(); + final Object [] array= selection.toArray(); + event.data= Utils.getResources(array); + } + } - @Override + @Override public void dragFinished(DragSourceEvent event) {} }; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ChangeSetActionGroup.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ChangeSetActionGroup.java index a9b59a959..65839d020 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ChangeSetActionGroup.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ChangeSetActionGroup.java @@ -66,103 +66,103 @@ import org.eclipse.ui.actions.BaseSelectionListenerAction; */ public class ChangeSetActionGroup extends SynchronizePageActionGroup { - /** - * Menu group that can be added to the context menu - */ - public final static String CHANGE_SET_GROUP = "change_set_group"; //$NON-NLS-1$ + /** + * Menu group that can be added to the context menu + */ + public final static String CHANGE_SET_GROUP = "change_set_group"; //$NON-NLS-1$ // Constants for persisting sorting options private static final String P_LAST_COMMENTSORT = TeamUIPlugin.ID + ".P_LAST_COMMENT_SORT"; //$NON-NLS-1$ - public static final FastSyncInfoFilter OUTGOING_RESOURCE_FILTER = new SyncInfoDirectionFilter( - new int[] { SyncInfo.OUTGOING, SyncInfo.CONFLICTING }); + public static final FastSyncInfoFilter OUTGOING_RESOURCE_FILTER = new SyncInfoDirectionFilter( + new int[] { SyncInfo.OUTGOING, SyncInfo.CONFLICTING }); private class CreateChangeSetAction extends SynchronizeModelAction { - public CreateChangeSetAction(ISynchronizePageConfiguration configuration) { - super(TeamUIMessages.ChangeLogModelProvider_0, configuration); - } + public CreateChangeSetAction(ISynchronizePageConfiguration configuration) { + super(TeamUIMessages.ChangeLogModelProvider_0, configuration); + } @Override protected boolean needsToSaveDirtyEditors() { return false; } - @Override + @Override protected FastSyncInfoFilter getSyncInfoFilter() { - return OUTGOING_RESOURCE_FILTER; - } + return OUTGOING_RESOURCE_FILTER; + } - @Override + @Override protected SynchronizeModelOperation getSubscriberOperation(ISynchronizePageConfiguration configuration, IDiffElement[] elements) { - return new SynchronizeModelOperation(configuration, elements) { - @Override + return new SynchronizeModelOperation(configuration, elements) { + @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - syncExec(() -> { - ActiveChangeSet set = createChangeSet(getDiffs(getSyncInfoSet().getResources())); - if (set != null) { - getActiveChangeSetManager().add(set); - } + syncExec(() -> { + ActiveChangeSet set = createChangeSet(getDiffs(getSyncInfoSet().getResources())); + if (set != null) { + getActiveChangeSetManager().add(set); + } }); - } - }; - } + } + }; + } } private abstract class ChangeSetAction extends BaseSelectionListenerAction { - public ChangeSetAction(String title, ISynchronizePageConfiguration configuration) { - super(title); - } + public ChangeSetAction(String title, ISynchronizePageConfiguration configuration) { + super(title); + } - @Override + @Override protected boolean updateSelection(IStructuredSelection selection) { - return getSelectedSet() != null; - } - - protected ActiveChangeSet getSelectedSet() { - IStructuredSelection selection = getStructuredSelection(); - if (selection.size() == 1) { - Object first = selection.getFirstElement(); - if (first instanceof IAdaptable) { - Object adapter = ((IAdaptable)first).getAdapter(ChangeSet.class); - if (adapter instanceof ActiveChangeSet) { - return (ActiveChangeSet)adapter; - } - } - } - return null; - } + return getSelectedSet() != null; + } + + protected ActiveChangeSet getSelectedSet() { + IStructuredSelection selection = getStructuredSelection(); + if (selection.size() == 1) { + Object first = selection.getFirstElement(); + if (first instanceof IAdaptable) { + Object adapter = ((IAdaptable)first).getAdapter(ChangeSet.class); + if (adapter instanceof ActiveChangeSet) { + return (ActiveChangeSet)adapter; + } + } + } + return null; + } } private class EditChangeSetAction extends ChangeSetAction { - public EditChangeSetAction(ISynchronizePageConfiguration configuration) { - super(TeamUIMessages.ChangeLogModelProvider_6, configuration); - } + public EditChangeSetAction(ISynchronizePageConfiguration configuration) { + super(TeamUIMessages.ChangeLogModelProvider_6, configuration); + } - @Override + @Override public void run() { - ActiveChangeSet set = getSelectedSet(); - if (set == null) return; - editChangeSet(set); - } + ActiveChangeSet set = getSelectedSet(); + if (set == null) return; + editChangeSet(set); + } } private class RemoveChangeSetAction extends ChangeSetAction { - public RemoveChangeSetAction(ISynchronizePageConfiguration configuration) { - super(TeamUIMessages.ChangeLogModelProvider_7, configuration); - } + public RemoveChangeSetAction(ISynchronizePageConfiguration configuration) { + super(TeamUIMessages.ChangeLogModelProvider_7, configuration); + } - @Override + @Override public void run() { - ActiveChangeSet set = getSelectedSet(); - if (set == null) return; - if (MessageDialog.openConfirm(getConfiguration().getSite().getShell(), TeamUIMessages.ChangeSetActionGroup_0, NLS.bind(TeamUIMessages.ChangeSetActionGroup_1, new String[] { LegacyActionTools.escapeMnemonics(set.getTitle()) }))) { // - getActiveChangeSetManager().remove(set); - } - } + ActiveChangeSet set = getSelectedSet(); + if (set == null) return; + if (MessageDialog.openConfirm(getConfiguration().getSite().getShell(), TeamUIMessages.ChangeSetActionGroup_0, NLS.bind(TeamUIMessages.ChangeSetActionGroup_1, new String[] { LegacyActionTools.escapeMnemonics(set.getTitle()) }))) { // + getActiveChangeSetManager().remove(set); + } + } } private class MakeDefaultChangeSetAction extends ChangeSetAction { @@ -198,44 +198,44 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { private class AddToChangeSetAction extends SynchronizeModelAction { - private final ActiveChangeSet set; + private final ActiveChangeSet set; - public AddToChangeSetAction(ISynchronizePageConfiguration configuration, ActiveChangeSet set, ISelection selection) { - super(set == null ? TeamUIMessages.ChangeSetActionGroup_2 : LegacyActionTools.escapeMnemonics(set.getTitle()), configuration); - this.set = set; - selectionChanged(selection); - } + public AddToChangeSetAction(ISynchronizePageConfiguration configuration, ActiveChangeSet set, ISelection selection) { + super(set == null ? TeamUIMessages.ChangeSetActionGroup_2 : LegacyActionTools.escapeMnemonics(set.getTitle()), configuration); + this.set = set; + selectionChanged(selection); + } - @Override + @Override protected FastSyncInfoFilter getSyncInfoFilter() { - return OUTGOING_RESOURCE_FILTER; - } + return OUTGOING_RESOURCE_FILTER; + } @Override protected boolean needsToSaveDirtyEditors() { return false; } - @Override + @Override protected SynchronizeModelOperation getSubscriberOperation(ISynchronizePageConfiguration configuration, IDiffElement[] elements) { - return new SynchronizeModelOperation(configuration, elements) { - @Override + return new SynchronizeModelOperation(configuration, elements) { + @Override public void run(IProgressMonitor monitor) - throws InvocationTargetException, InterruptedException { - IResource[] resources = getSyncInfoSet().getResources(); - if (set != null) { - IDiff[] diffArray = getDiffs(resources); + throws InvocationTargetException, InterruptedException { + IResource[] resources = getSyncInfoSet().getResources(); + if (set != null) { + IDiff[] diffArray = getDiffs(resources); set.add(diffArray); - } else { - ChangeSet[] sets = getActiveChangeSetManager().getSets(); - for (int i = 0; i < sets.length; i++) { - ActiveChangeSet activeSet = (ActiveChangeSet)sets[i]; + } else { + ChangeSet[] sets = getActiveChangeSetManager().getSets(); + for (int i = 0; i < sets.length; i++) { + ActiveChangeSet activeSet = (ActiveChangeSet)sets[i]; activeSet.remove(resources); - } - } - } - }; - } + } + } + } + }; + } } /* ***************************************************************************** @@ -252,7 +252,7 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { @Override public void run() { if (isChecked() && sortCriteria != criteria) { - sortCriteria = criteria; + sortCriteria = criteria; String key = getSettingsKey(); IDialogSettings pageSettings = getConfiguration().getSite().getPageSettings(); if(pageSettings != null) { @@ -264,11 +264,11 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { } public void update() { - setChecked(criteria == sortCriteria); + setChecked(criteria == sortCriteria); } protected String getSettingsKey() { - return P_LAST_COMMENTSORT; + return P_LAST_COMMENTSORT; } } @@ -283,19 +283,19 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { private MenuManager sortByComment; private CreateChangeSetAction createChangeSet; private MenuManager addToChangeSet; - private EditChangeSetAction editChangeSet; - private RemoveChangeSetAction removeChangeSet; - private MakeDefaultChangeSetAction makeDefault; + private EditChangeSetAction editChangeSet; + private RemoveChangeSetAction removeChangeSet; + private MakeDefaultChangeSetAction makeDefault; - private SynchronizePageActionGroup subActions; + private SynchronizePageActionGroup subActions; - /* - * The currently chosen sort criteria - */ - private int sortCriteria = ChangeSetModelSorter.DATE; + /* + * The currently chosen sort criteria + */ + private int sortCriteria = ChangeSetModelSorter.DATE; - public static int getSortCriteria(ISynchronizePageConfiguration configuration) { - int sortCriteria = ChangeSetModelSorter.DATE; + public static int getSortCriteria(ISynchronizePageConfiguration configuration) { + int sortCriteria = ChangeSetModelSorter.DATE; try { IDialogSettings pageSettings = configuration.getSite().getPageSettings(); if(pageSettings != null) { @@ -305,27 +305,27 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { // ignore and use the defaults. } switch (sortCriteria) { - case ChangeSetModelSorter.COMMENT: - case ChangeSetModelSorter.DATE: - case ChangeSetModelSorter.USER: - break; - default: - sortCriteria = ChangeSetModelSorter.DATE; - break; - } + case ChangeSetModelSorter.COMMENT: + case ChangeSetModelSorter.DATE: + case ChangeSetModelSorter.USER: + break; + default: + sortCriteria = ChangeSetModelSorter.DATE; + break; + } return sortCriteria; - } + } - public ChangeSetActionGroup(ChangeSetModelProvider provider) { - this.provider = provider; - } + public ChangeSetActionGroup(ChangeSetModelProvider provider) { + this.provider = provider; + } @Override public void initialize(ISynchronizePageConfiguration configuration) { super.initialize(configuration); if (getChangeSetCapability().supportsCheckedInChangeSets()) { - sortCriteria = getSortCriteria(configuration); + sortCriteria = getSortCriteria(configuration); sortByComment = new MenuManager(TeamUIMessages.ChangeLogModelProvider_0a); sortByComment.add(new ToggleSortOrderAction(TeamUIMessages.ChangeLogModelProvider_1a, ChangeSetModelSorter.COMMENT)); sortByComment.add(new ToggleSortOrderAction(TeamUIMessages.ChangeLogModelProvider_2a, ChangeSetModelSorter.DATE)); @@ -346,16 +346,16 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { subActions = getChangeSetCapability().getActionGroup(); if (subActions != null) { - subActions.initialize(configuration); + subActions.initialize(configuration); } } - @Override + @Override public void fillContextMenu(IMenuManager menu) { - if (getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { - appendToGroup(menu, ISynchronizePageConfiguration.SORT_GROUP, sortByComment); - } - if (getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { + if (getChangeSetCapability().enableCheckedInChangeSetsFor(getConfiguration())) { + appendToGroup(menu, ISynchronizePageConfiguration.SORT_GROUP, sortByComment); + } + if (getChangeSetCapability().enableActiveChangeSetsFor(getConfiguration())) { appendToGroup( menu, CHANGE_SET_GROUP, @@ -372,102 +372,102 @@ public class ChangeSetActionGroup extends SynchronizePageActionGroup { menu, CHANGE_SET_GROUP, makeDefault); - } + } if (subActions != null) { - subActions.fillContextMenu(menu); + subActions.fillContextMenu(menu); } - } + } - protected void addChangeSets(IMenuManager manager) { - ChangeSet[] sets = getActiveChangeSetManager().getSets(); - Arrays.sort(sets, new Comparator<ChangeSet>() { - private Collator collator = Collator.getInstance(); - @Override + protected void addChangeSets(IMenuManager manager) { + ChangeSet[] sets = getActiveChangeSetManager().getSets(); + Arrays.sort(sets, new Comparator<ChangeSet>() { + private Collator collator = Collator.getInstance(); + @Override public int compare(ChangeSet o1, ChangeSet o2) { - return collator.compare(o1.getName(), o2.getName()); - } - }); - ISelection selection = getContext().getSelection(); - createChangeSet.selectionChanged(selection); + return collator.compare(o1.getName(), o2.getName()); + } + }); + ISelection selection = getContext().getSelection(); + createChangeSet.selectionChanged(selection); addToChangeSet.add(createChangeSet); addToChangeSet.add(new Separator()); - for (int i = 0; i < sets.length; i++) { - ActiveChangeSet set = (ActiveChangeSet)sets[i]; - AddToChangeSetAction action = new AddToChangeSetAction(getConfiguration(), set, selection); - manager.add(action); - } - addToChangeSet.add(new Separator()); - // Action that removes change set resources - addToChangeSet.add(new AddToChangeSetAction(getConfiguration(), null, selection)); - } - - /** - * Return the change set manager for the current page. - * @return the change set manager for the current page - */ - protected ActiveChangeSetManager getActiveChangeSetManager() { - return getChangeSetCapability().getActiveChangeSetManager(); - } + for (int i = 0; i < sets.length; i++) { + ActiveChangeSet set = (ActiveChangeSet)sets[i]; + AddToChangeSetAction action = new AddToChangeSetAction(getConfiguration(), set, selection); + manager.add(action); + } + addToChangeSet.add(new Separator()); + // Action that removes change set resources + addToChangeSet.add(new AddToChangeSetAction(getConfiguration(), null, selection)); + } + + /** + * Return the change set manager for the current page. + * @return the change set manager for the current page + */ + protected ActiveChangeSetManager getActiveChangeSetManager() { + return getChangeSetCapability().getActiveChangeSetManager(); + } @Override public void dispose() { - if (addToChangeSet != null) { + if (addToChangeSet != null) { addToChangeSet.dispose(); addToChangeSet.removeAll(); - } - if (sortByComment != null) { + } + if (sortByComment != null) { sortByComment.dispose(); sortByComment.removeAll(); - } - if (subActions != null) { - subActions.dispose(); - } + } + if (subActions != null) { + subActions.dispose(); + } super.dispose(); } - @Override + @Override public void updateActionBars() { - if (editChangeSet != null) - editChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); - if (removeChangeSet != null) - removeChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); - if (makeDefault != null) - makeDefault.selectionChanged((IStructuredSelection)getContext().getSelection()); - super.updateActionBars(); - } - - private void syncExec(final Runnable runnable) { + if (editChangeSet != null) + editChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); + if (removeChangeSet != null) + removeChangeSet.selectionChanged((IStructuredSelection)getContext().getSelection()); + if (makeDefault != null) + makeDefault.selectionChanged((IStructuredSelection)getContext().getSelection()); + super.updateActionBars(); + } + + private void syncExec(final Runnable runnable) { final Control ctrl = getConfiguration().getPage().getViewer().getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().syncExec(() -> { if (!ctrl.isDisposed()) { - runnable.run(); + runnable.run(); } }); } - } + } - /** - * Return a viewer sorter that utilizes the sort criteria - * selected by the user. - * @return a sorter - */ + /** + * Return a viewer sorter that utilizes the sort criteria + * selected by the user. + * @return a sorter + */ public ViewerSorter getViewerSorter() { return new ChangeSetModelSorter(provider, sortCriteria); } - private ActiveChangeSet createChangeSet(IDiff[] diffs) { - return getChangeSetCapability().createChangeSet(getConfiguration(), diffs); - } + private ActiveChangeSet createChangeSet(IDiff[] diffs) { + return getChangeSetCapability().createChangeSet(getConfiguration(), diffs); + } - private void editChangeSet(ActiveChangeSet set) { - getChangeSetCapability().editChangeSet(getConfiguration(), set); - } + private void editChangeSet(ActiveChangeSet set) { + getChangeSetCapability().editChangeSet(getConfiguration(), set); + } - private ChangeSetCapability getChangeSetCapability() { - return provider.getChangeSetCapability(); - } + private ChangeSetCapability getChangeSetCapability() { + return provider.getChangeSetCapability(); + } private IDiff[] getDiffs(IResource[] resources) { List<IDiff> diffs = new ArrayList<>(); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/CopyToClipboardAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/CopyToClipboardAction.java index 89d673e6e..6b9513c55 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/CopyToClipboardAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/CopyToClipboardAction.java @@ -53,36 +53,36 @@ import org.eclipse.ui.part.ResourceTransfer; */ class CopyToClipboardAction extends SelectionListenerAction { - private static final String EOL = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + private static final String EOL = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - private final static String ID= TeamUIPlugin.PLUGIN_ID + ".synchronize.action.copy"; //$NON-NLS-1$ + private final static String ID= TeamUIPlugin.PLUGIN_ID + ".synchronize.action.copy"; //$NON-NLS-1$ - private final Shell fShell; - private final Clipboard fClipboard; + private final Shell fShell; + private final Clipboard fClipboard; private final INavigatorContentService navigatorContentService; - protected CopyToClipboardAction(Shell shell, INavigatorContentService navigatorContentService) { - super(TeamUIMessages.CopyToClipboardAction_1); + protected CopyToClipboardAction(Shell shell, INavigatorContentService navigatorContentService) { + super(TeamUIMessages.CopyToClipboardAction_1); this.navigatorContentService = navigatorContentService; - Assert.isNotNull(shell); - fShell= shell; - fClipboard= new Clipboard(shell.getDisplay()); - setToolTipText(TeamUIMessages.CopyToClipboardAction_2); - setId(ID); - } + Assert.isNotNull(shell); + fShell= shell; + fClipboard= new Clipboard(shell.getDisplay()); + setToolTipText(TeamUIMessages.CopyToClipboardAction_2); + setId(ID); + } - @Override + @Override public void run() { copyResources(getSelectedResources(), getTextualClipboardContents()); } - /* - * Return a text representation of all selected elements. - * Use the name from the tree node so what is copied - * matches what appears in the tree. - */ - private String getTextualClipboardContents() { + /* + * Return a text representation of all selected elements. + * Use the name from the tree node so what is copied + * matches what appears in the tree. + */ + private String getTextualClipboardContents() { StringBuilder buf = new StringBuilder(); int i = 0; IStructuredSelection structuredSelection = getStructuredSelection(); @@ -177,36 +177,36 @@ class CopyToClipboardAction extends SelectionListenerAction { * @param fileNames file names of the resources to copy to the clipboard * @param names string representation of all names */ - private void setClipboard(IResource[] resources, String[] fileNames, String names) { - try { - // set the clipboard contents - List data = new ArrayList(); - List<Transfer> dataTypes = new ArrayList<>(); - if (resources.length > 0) { - data.add(resources); - dataTypes.add(ResourceTransfer.getInstance()); - } - if (fileNames.length > 0) { - data.add(fileNames); - dataTypes.add(FileTransfer.getInstance()); - } - if (names != null && names.length() > 0) { - data.add(names); - dataTypes.add(TextTransfer.getInstance()); - } - if (!data.isEmpty()) - fClipboard.setContents( - data.toArray(), - dataTypes.toArray(new Transfer[dataTypes.size()])); - } catch (SWTError e) { - if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) - throw e; - if (MessageDialog.openQuestion(fShell, TeamUIMessages.CopyToClipboardAction_3, TeamUIMessages.CopyToClipboardAction_4)) - setClipboard(resources, fileNames, names); - } - } + private void setClipboard(IResource[] resources, String[] fileNames, String names) { + try { + // set the clipboard contents + List data = new ArrayList(); + List<Transfer> dataTypes = new ArrayList<>(); + if (resources.length > 0) { + data.add(resources); + dataTypes.add(ResourceTransfer.getInstance()); + } + if (fileNames.length > 0) { + data.add(fileNames); + dataTypes.add(FileTransfer.getInstance()); + } + if (names != null && names.length() > 0) { + data.add(names); + dataTypes.add(TextTransfer.getInstance()); + } + if (!data.isEmpty()) + fClipboard.setContents( + data.toArray(), + dataTypes.toArray(new Transfer[dataTypes.size()])); + } catch (SWTError e) { + if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) + throw e; + if (MessageDialog.openQuestion(fShell, TeamUIMessages.CopyToClipboardAction_3, TeamUIMessages.CopyToClipboardAction_4)) + setClipboard(resources, fileNames, names); + } + } - @Override + @Override protected boolean updateSelection(IStructuredSelection selection) { if (!super.updateSelection(selection)) return false; @@ -250,7 +250,7 @@ class CopyToClipboardAction extends SelectionListenerAction { @Override protected List<? extends IResource> getSelectedResources() { - // Calling our own selection utility because the elements in the + // Calling our own selection utility because the elements in the // synchronize view can't adapt to IResource because we don't want the usual object // contribution/ on them. return Arrays.asList(Utils.getResources(getStructuredSelection().toArray())); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/DefaultSynchronizePageActions.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/DefaultSynchronizePageActions.java index 3afe5d6e2..9e49dd9fe 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/DefaultSynchronizePageActions.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/DefaultSynchronizePageActions.java @@ -55,26 +55,26 @@ public class DefaultSynchronizePageActions extends SynchronizePageActionGroup { } } - @Override + @Override public void fillActionBars(IActionBars actionBars) { - if (openWithActions != null) openWithActions.fillActionBars(actionBars); - if (refactorActions != null) refactorActions.fillActionBars(actionBars); - if (actionBars != null && showPreferences != null) { - IMenuManager menu = actionBars.getMenuManager(); - appendToGroup(menu, ISynchronizePageConfiguration.PREFERENCES_GROUP, showPreferences); - } - } + if (openWithActions != null) openWithActions.fillActionBars(actionBars); + if (refactorActions != null) refactorActions.fillActionBars(actionBars); + if (actionBars != null && showPreferences != null) { + IMenuManager menu = actionBars.getMenuManager(); + appendToGroup(menu, ISynchronizePageConfiguration.PREFERENCES_GROUP, showPreferences); + } + } - @Override + @Override public void updateActionBars() { - if (openWithActions != null) openWithActions.updateActionBars(); - if (refactorActions != null) refactorActions.updateActionBars(); - } + if (openWithActions != null) openWithActions.updateActionBars(); + if (refactorActions != null) refactorActions.updateActionBars(); + } @Override public void fillContextMenu(IMenuManager manager) { - final IContributionItem fileGroup = findGroup(manager, ISynchronizePageConfiguration.FILE_GROUP); + final IContributionItem fileGroup = findGroup(manager, ISynchronizePageConfiguration.FILE_GROUP); if (openWithActions != null && fileGroup != null) { openWithActions.fillContextMenu(manager, fileGroup.getId()); } @@ -92,9 +92,9 @@ public class DefaultSynchronizePageActions extends SynchronizePageActionGroup { if (openWithActions != null) openWithActions.dispose(); } - @Override + @Override public void setContext(ActionContext context) { - if (openWithActions != null) openWithActions.setContext(context); - if (refactorActions != null) refactorActions.setContext(context); - } + if (openWithActions != null) openWithActions.setContext(context); + if (refactorActions != null) refactorActions.setContext(context); + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/GlobalRefreshAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/GlobalRefreshAction.java index bf37bf446..761eadfed 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/GlobalRefreshAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/GlobalRefreshAction.java @@ -173,7 +173,7 @@ public class GlobalRefreshAction extends Action implements IMenuCreator, IWorkbe return null; } }; - syncLatest = hs.activateHandler("org.eclipse.team.ui.synchronizeLast", handler); //$NON-NLS-1$ + syncLatest = hs.activateHandler("org.eclipse.team.ui.synchronizeLast", handler); //$NON-NLS-1$ } setMenuCreator(this); TeamUI.getSynchronizeManager().addSynchronizeParticipantListener(this); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/NavigateAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/NavigateAction.java index 735508da8..37aa9eba9 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/NavigateAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/NavigateAction.java @@ -52,7 +52,7 @@ public class NavigateAction extends Action { /** * Two types of navigation is supported: navigation that is specific to coordinating between a view * and a compare editor and navigation simply using the configured navigator. - */ + */ @Override public void run() { ICompareNavigator nav = (ICompareNavigator)configuration.getProperty(SynchronizePageConfiguration.P_NAVIGATOR); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenInCompareAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenInCompareAction.java index 9d139ae12..4ac48f61d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenInCompareAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenInCompareAction.java @@ -104,11 +104,11 @@ public class OpenInCompareAction extends Action { // all files IResource resources[] = Utils.getResources(elements); for (int i = 0; i < resources.length; i++) { - if (resources[i].getType() != IResource.FILE) { - // Only supported if all the items are files. - return false; - } - } + if (resources[i].getType() != IResource.FILE) { + // Only supported if all the items are files. + return false; + } + } } return true; } @@ -210,32 +210,32 @@ public class OpenInCompareAction extends Action { return page; } - public static void openCompareEditor(CompareEditorInput input, IWorkbenchPage page) { - // try to reuse editors, if possible + public static void openCompareEditor(CompareEditorInput input, IWorkbenchPage page) { + // try to reuse editors, if possible openCompareEditor(input, page, true); } - public static void openCompareEditor(CompareEditorInput input, IWorkbenchPage page, boolean reuseEditorIfPossible) { - if (page == null || input == null) - return; + public static void openCompareEditor(CompareEditorInput input, IWorkbenchPage page, boolean reuseEditorIfPossible) { + if (page == null || input == null) + return; IEditorPart editor = Utils.findReusableCompareEditor(input, page, new Class[] { SyncInfoCompareInput.class, ModelCompareEditorInput.class }); - // reuse editor only for single selection - if(editor != null && reuseEditorIfPossible) { - IEditorInput otherInput = editor.getEditorInput(); - if(otherInput.equals(input)) { - // simply provide focus to editor - page.activate(editor); - } else { - // if editor is currently not open on that input either re-use existing - CompareUI.reuseCompareEditor(input, (IReusableEditor)editor); - page.activate(editor); - } - } else { - CompareUI.openCompareEditorOnPage(input, page); - } - } + // reuse editor only for single selection + if(editor != null && reuseEditorIfPossible) { + IEditorInput otherInput = editor.getEditorInput(); + if(otherInput.equals(input)) { + // simply provide focus to editor + page.activate(editor); + } else { + // if editor is currently not open on that input either re-use existing + CompareUI.reuseCompareEditor(input, (IReusableEditor)editor); + page.activate(editor); + } + } else { + CompareUI.openCompareEditorOnPage(input, page); + } + } /** * Returns an editor handle if a SyncInfoCompareInput compare editor is opened on diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenWithActionGroup.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenWithActionGroup.java index 9708c6d71..fba0cd937 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenWithActionGroup.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/OpenWithActionGroup.java @@ -89,11 +89,11 @@ public class OpenWithActionGroup extends ActionGroup { */ private void fillOpenWithMenu(IMenuManager menu, String groupId, IStructuredSelection selection) { - // Only supported if at least one file is selected. - if (selection == null || selection.size() < 1) - return; - Object[] elements = selection.toArray(); - IResource resources[] = Utils.getResources(elements); + // Only supported if at least one file is selected. + if (selection == null || selection.size() < 1) + return; + Object[] elements = selection.toArray(); + IResource resources[] = Utils.getResources(elements); if (resources.length == 0) { if (openInCompareAction != null) { // We can still show the compare editor open if the element has @@ -118,12 +118,12 @@ public class OpenWithActionGroup extends ActionGroup { return; } - if (elements.length != resources.length){ - // Only supported if all the items are resources. - return; - } + if (elements.length != resources.length){ + // Only supported if all the items are resources. + return; + } - boolean allFiles = true; + boolean allFiles = true; for (int i = 0; i < resources.length; i++) { if (resources[i].getType() != IResource.FILE) { // Open actions are only supported if all the items are files. @@ -173,7 +173,7 @@ public class OpenWithActionGroup extends ActionGroup { showInSubmenu.add(showInMenu); menu.appendToGroup(groupId, showInSubmenu); } - } + } /** * {@link SaveablesCompareEditorInput#getShowInMenuLabel} diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RefactorActionGroup.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RefactorActionGroup.java index 7b2a919a5..9d1f9a086 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RefactorActionGroup.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RefactorActionGroup.java @@ -77,13 +77,13 @@ public class RefactorActionGroup extends ActionGroup { parentMenu.appendToGroup(groupId, renameAction); } - @Override + @Override public void fillActionBars(IActionBars actionBars) { - actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction); - actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), deleteAction); - actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), renameAction); - actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), moveAction); - } + actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction); + actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), deleteAction); + actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), renameAction); + actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), moveAction); + } @Override public void updateActionBars() { @@ -150,22 +150,22 @@ public class RefactorActionGroup extends ActionGroup { .setActionDefinitionId(IWorkbenchCommandConstants.FILE_RENAME); } - private IStructuredSelection getSelection() { - final ISelection selection= getContext().getSelection(); + private IStructuredSelection getSelection() { + final ISelection selection= getContext().getSelection(); - if (!(selection instanceof IStructuredSelection)) - return new StructuredSelection(); + if (!(selection instanceof IStructuredSelection)) + return new StructuredSelection(); - return new StructuredSelection(Utils.getResources(((IStructuredSelection)selection).toArray())); + return new StructuredSelection(Utils.getResources(((IStructuredSelection)selection).toArray())); } - private IStructuredSelection getObjectSelection() { - final ISelection selection= getContext().getSelection(); + private IStructuredSelection getObjectSelection() { + final ISelection selection= getContext().getSelection(); - if (!(selection instanceof IStructuredSelection)) - return new StructuredSelection(); + if (!(selection instanceof IStructuredSelection)) + return new StructuredSelection(); - return (IStructuredSelection)selection; + return (IStructuredSelection)selection; } private boolean allResourcesAreOfType(IStructuredSelection selection, int resourceMask) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RemoveSynchronizeParticipantAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RemoveSynchronizeParticipantAction.java index 8b384042f..cd7c571b0 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RemoveSynchronizeParticipantAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/RemoveSynchronizeParticipantAction.java @@ -136,8 +136,8 @@ public class RemoveSynchronizeParticipantAction extends Action { } private boolean promptToSave(List dirtyModels) { - if (dirtyModels.size() == 1) { - Saveable model = (Saveable) dirtyModels.get(0); + if (dirtyModels.size() == 1) { + Saveable model = (Saveable) dirtyModels.get(0); String message = NLS.bind(TeamUIMessages.RemoveSynchronizeParticipantAction_2, model.getName()); // Show a dialog. String[] buttons = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }; @@ -159,28 +159,28 @@ public class RemoveSynchronizeParticipantAction extends Action { case 2: // cancel return false; } - } else { - ListSelectionDialog dlg = new ListSelectionDialog( - view.getSite().getShell(), dirtyModels, - new ArrayContentProvider(), - new WorkbenchPartLabelProvider(), TeamUIMessages.RemoveSynchronizeParticipantAction_4); - dlg.setInitialSelections(dirtyModels.toArray()); - dlg.setTitle(TeamUIMessages.RemoveSynchronizeParticipantAction_5); - - int result = dlg.open(); - //Just return false to prevent the operation continuing - if (result == IDialogConstants.CANCEL_ID) - return false; - - dirtyModels = Arrays.asList(dlg.getResult()); - } - - // If the editor list is empty return. - if (dirtyModels.isEmpty()) - return true; + } else { + ListSelectionDialog dlg = new ListSelectionDialog( + view.getSite().getShell(), dirtyModels, + new ArrayContentProvider(), + new WorkbenchPartLabelProvider(), TeamUIMessages.RemoveSynchronizeParticipantAction_4); + dlg.setInitialSelections(dirtyModels.toArray()); + dlg.setTitle(TeamUIMessages.RemoveSynchronizeParticipantAction_5); + + int result = dlg.open(); + //Just return false to prevent the operation continuing + if (result == IDialogConstants.CANCEL_ID) + return false; + + dirtyModels = Arrays.asList(dlg.getResult()); + } + + // If the editor list is empty return. + if (dirtyModels.isEmpty()) + return true; // Create save block. - final List finalModels = dirtyModels; + final List finalModels = dirtyModels; IRunnableWithProgress progressOp = monitor -> { monitor.beginTask(null, finalModels.size()); for (Iterator i = finalModels.iterator(); i.hasNext();) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ShowSynchronizeParticipantAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ShowSynchronizeParticipantAction.java index eeb6cb7cd..93fb4a03d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ShowSynchronizeParticipantAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/ShowSynchronizeParticipantAction.java @@ -34,7 +34,7 @@ import org.eclipse.team.ui.synchronize.SubscriberParticipant; public class ShowSynchronizeParticipantAction extends Action implements IPropertyChangeListener { - private ISynchronizeParticipantReference fPage; + private ISynchronizeParticipantReference fPage; private ISynchronizeView fView; @Override @@ -59,22 +59,22 @@ public class ShowSynchronizeParticipantAction extends Action implements IPropert super(Utils.shortenText(SynchronizeView.MAX_NAME_LENGTH, ref.getDisplayName()), IAction.AS_RADIO_BUTTON); fPage = ref; fView = view; - setImageDescriptor( new ParticipantOverlay( ref)); + setImageDescriptor( new ParticipantOverlay( ref)); - try { - fPage.getParticipant().addPropertyChangeListener( this); - } catch( TeamException e) { - Utils.handle(e); - } + try { + fPage.getParticipant().addPropertyChangeListener( this); + } catch( TeamException e) { + Utils.handle(e); + } } @Override public void propertyChange( PropertyChangeEvent event) { - String property = event.getProperty(); - if( AbstractSynchronizeParticipant.P_PINNED.equals( property) || - AbstractSynchronizeParticipant.P_SCHEDULED.equals(property)) { - setImageDescriptor(new ParticipantOverlay( fPage)); - } + String property = event.getProperty(); + if( AbstractSynchronizeParticipant.P_PINNED.equals( property) || + AbstractSynchronizeParticipant.P_SCHEDULED.equals(property)) { + setImageDescriptor(new ParticipantOverlay( fPage)); + } } @@ -100,18 +100,18 @@ public class ShowSynchronizeParticipantAction extends Action implements IPropert if (this.participant.isPinned()) { drawImage(pinnedData, this.imageData.width - pinnedData.width, 0); } - if (this.participant instanceof SubscriberParticipant) { - SubscriberParticipant participant = ( SubscriberParticipant) this.participant; - SubscriberRefreshSchedule schedule = participant.getRefreshSchedule(); - if(schedule!=null && schedule.isEnabled()) { - drawImage(scheduledData, 0, 0); - } - } else { - SubscriberRefreshSchedule schedule = Adapters.adapt(participant, SubscriberRefreshSchedule.class); - if(schedule!=null && schedule.isEnabled()) { - drawImage(scheduledData, 0, 0); - } - } + if (this.participant instanceof SubscriberParticipant) { + SubscriberParticipant participant = ( SubscriberParticipant) this.participant; + SubscriberRefreshSchedule schedule = participant.getRefreshSchedule(); + if(schedule!=null && schedule.isEnabled()) { + drawImage(scheduledData, 0, 0); + } + } else { + SubscriberRefreshSchedule schedule = Adapters.adapt(participant, SubscriberRefreshSchedule.class); + if(schedule!=null && schedule.isEnabled()) { + drawImage(scheduledData, 0, 0); + } + } } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/SyncViewerShowPreferencesAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/SyncViewerShowPreferencesAction.java index 94066ef1a..20d393563 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/SyncViewerShowPreferencesAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/actions/SyncViewerShowPreferencesAction.java @@ -20,7 +20,7 @@ import org.eclipse.team.internal.ui.dialogs.PreferencePageContainerDialog; import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; public class SyncViewerShowPreferencesAction extends Action { - private final ISynchronizePageConfiguration configuration; + private final ISynchronizePageConfiguration configuration; public SyncViewerShowPreferencesAction(ISynchronizePageConfiguration configuration) { this.configuration = configuration; @@ -29,8 +29,8 @@ public class SyncViewerShowPreferencesAction extends Action { @Override public void run() { - PreferencePage[] pages = configuration.getParticipant().getPreferencePages(); - PreferencePageContainerDialog dialog = new PreferencePageContainerDialog(configuration.getSite().getShell(), pages); + PreferencePage[] pages = configuration.getParticipant().getPreferencePages(); + PreferencePageContainerDialog dialog = new PreferencePageContainerDialog(configuration.getSite().getShell(), pages); dialog.setBlockOnOpen(true); dialog.open(); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java index 6b56d2995..4cea0114b 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java @@ -162,9 +162,9 @@ public class ConfigureProjectWizard extends Wizard { private static boolean filterItem(IConfigurationElement element) { String extensionId = element.getAttribute(ATT_ID); String extensionPluginId = element.getNamespaceIdentifier(); - IActivityManager activityMgr = PlatformUI.getWorkbench().getActivitySupport().getActivityManager(); - IIdentifier id = activityMgr.getIdentifier(extensionPluginId + "/" + extensionId); //$NON-NLS-1$ - return (!id.isEnabled()); + IActivityManager activityMgr = PlatformUI.getWorkbench().getActivitySupport().getActivityManager(); + IIdentifier id = activityMgr.getIdentifier(extensionPluginId + "/" + extensionId); //$NON-NLS-1$ + return (!id.isEnabled()); } /** diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizardMainPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizardMainPage.java index 5440d76ac..e71ea8741 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizardMainPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizardMainPage.java @@ -121,7 +121,7 @@ public class ConfigureProjectWizardMainPage extends WizardPage { setControl(composite); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARE_PROJECT_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.SHARE_PROJECT_PAGE); Label label = new Label(composite, SWT.LEFT); label.setText(description); @@ -201,7 +201,7 @@ public class ConfigureProjectWizardMainPage extends WizardPage { viewer.setInput(wizards); } initializeWizardSelection(); - Dialog.applyDialogFont(parent); + Dialog.applyDialogFont(parent); } /* package */ IProject[] getUnsharedProjects() { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalRefreshWizardSelectionPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalRefreshWizardSelectionPage.java index 36f3aa6bf..93cc65318 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalRefreshWizardSelectionPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalRefreshWizardSelectionPage.java @@ -59,7 +59,7 @@ import org.eclipse.ui.views.navigator.ResourceComparator; */ public class GlobalRefreshWizardSelectionPage extends WizardPage implements IDoubleClickListener, ISelectionChangedListener { - private final static String DEFAULT_SELECTION= TeamUIPlugin.ID + "GlobalRefreshWizardSelectionPage.default_selection"; //$NON-NLS-1$ + private final static String DEFAULT_SELECTION= TeamUIPlugin.ID + "GlobalRefreshWizardSelectionPage.default_selection"; //$NON-NLS-1$ private TableViewer fViewer; private IWizard wizard; @@ -119,25 +119,25 @@ public class GlobalRefreshWizardSelectionPage extends WizardPage implements IDou } /** - * Save the page settings into the dialog settings - */ - public void savePageSettings() { - if (fViewer.getControl().isDisposed()) - return; - - final IStructuredSelection selection= fViewer.getStructuredSelection(); - final Object selected= selection.getFirstElement(); - if (!(selected instanceof SynchronizeWizardDescription)) - return; - getDialogSettings().put(DEFAULT_SELECTION, ((SynchronizeWizardDescription)selected).getId()); - } + * Save the page settings into the dialog settings + */ + public void savePageSettings() { + if (fViewer.getControl().isDisposed()) + return; + + final IStructuredSelection selection= fViewer.getStructuredSelection(); + final Object selected= selection.getFirstElement(); + if (!(selected instanceof SynchronizeWizardDescription)) + return; + getDialogSettings().put(DEFAULT_SELECTION, ((SynchronizeWizardDescription)selected).getId()); + } @Override public void createControl(Composite parent2) { Composite top = new Composite(parent2, SWT.NULL); top.setLayout(new GridLayout()); setControl(top); - PlatformUI.getWorkbench().getHelpSystem().setHelp(top, IHelpContextIds.REFRESH_WIZARD_SELECTION_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(top, IHelpContextIds.REFRESH_WIZARD_SELECTION_PAGE); Label l = new Label(top, SWT.NULL); l.setText(TeamUIMessages.GlobalRefreshParticipantSelectionPage_3); @@ -153,10 +153,10 @@ public class GlobalRefreshWizardSelectionPage extends WizardPage implements IDou Object toSelect= getDefaultSelection(); if (toSelect == null) { - toSelect= fViewer.getElementAt(0); + toSelect= fViewer.getElementAt(0); } if (toSelect != null) { - fViewer.setSelection(new StructuredSelection(toSelect), true); + fViewer.setSelection(new StructuredSelection(toSelect), true); } fViewer.getTable().setFocus(); Dialog.applyDialogFont(parent2); @@ -164,24 +164,24 @@ public class GlobalRefreshWizardSelectionPage extends WizardPage implements IDou private SynchronizeWizardDescription getDefaultSelection() { - if (!(TeamUI.getSynchronizeManager() instanceof SynchronizeManager)) - return null; + if (!(TeamUI.getSynchronizeManager() instanceof SynchronizeManager)) + return null; - final String defaultSelection= getDialogSettings().get(DEFAULT_SELECTION); - if (defaultSelection == null) - return null; + final String defaultSelection= getDialogSettings().get(DEFAULT_SELECTION); + if (defaultSelection == null) + return null; - final SynchronizeManager syncManager= (SynchronizeManager)TeamUI.getSynchronizeManager(); - final SynchronizeWizardDescription [] wizards= syncManager.getWizardDescriptors(); - for (int i = 0; i < wizards.length; i++) { - if (defaultSelection.equals(wizards[i].getId())) { - return wizards[i]; - } - } - return null; - } + final SynchronizeManager syncManager= (SynchronizeManager)TeamUI.getSynchronizeManager(); + final SynchronizeWizardDescription [] wizards= syncManager.getWizardDescriptors(); + for (int i = 0; i < wizards.length; i++) { + if (defaultSelection.equals(wizards[i].getId())) { + return wizards[i]; + } + } + return null; + } - @Override + @Override public void doubleClick(DoubleClickEvent event) { selectionChanged( new SelectionChangedEvent( diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalSynchronizeWizard.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalSynchronizeWizard.java index 7080985a3..0764a54ee 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalSynchronizeWizard.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/GlobalSynchronizeWizard.java @@ -30,7 +30,7 @@ import org.eclipse.ui.IWorkbench; */ public class GlobalSynchronizeWizard extends Wizard { - private final static String DIALOG_SETTINGS_SECTION= "SynchronizeWizard"; //$NON-NLS-1$ + private final static String DIALOG_SETTINGS_SECTION= "SynchronizeWizard"; //$NON-NLS-1$ protected IWorkbench workbench; protected GlobalRefreshWizardSelectionPage mainPage; @@ -45,8 +45,8 @@ public class GlobalSynchronizeWizard extends Wizard { final IDialogSettings pluginSettings= TeamUIPlugin.getPlugin().getDialogSettings(); IDialogSettings wizardSettings= pluginSettings.getSection(DIALOG_SETTINGS_SECTION); if (wizardSettings == null) { - pluginSettings.addNewSection(DIALOG_SETTINGS_SECTION); - wizardSettings= pluginSettings.getSection(DIALOG_SETTINGS_SECTION); + pluginSettings.addNewSection(DIALOG_SETTINGS_SECTION); + wizardSettings= pluginSettings.getSection(DIALOG_SETTINGS_SECTION); } setDialogSettings(wizardSettings); } @@ -77,7 +77,7 @@ public class GlobalSynchronizeWizard extends Wizard { IWizard noPageWizard = mainPage.getSelectedWizard(); if (noPageWizard != null) { if (noPageWizard.canFinish()) { - mainPage.savePageSettings(); + mainPage.savePageSettings(); return noPageWizard.performFinish(); } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ImportProjectSetMainPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ImportProjectSetMainPage.java index e60e615b3..48605b798 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ImportProjectSetMainPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ImportProjectSetMainPage.java @@ -102,7 +102,7 @@ public class ImportProjectSetMainPage extends TeamWizardPage { initializeDialogUnits(composite); // set F1 help - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.IMPORT_PROJECT_SET_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.IMPORT_PROJECT_SET_PAGE); Composite inner = new Composite(composite, SWT.NULL); inner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetExportWizard.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetExportWizard.java index 30ac041ac..e50143720 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetExportWizard.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetExportWizard.java @@ -209,16 +209,16 @@ public class ProjectSetExportWizard extends Wizard implements IExportWizard { private XMLMemento getXMLMementoRoot() { Document document; - try { - document = DocumentBuilderFactory.newInstance() - .newDocumentBuilder().newDocument(); - Element element = document.createElement("psf"); //$NON-NLS-1$ - element.setAttribute("version", "2.0"); //$NON-NLS-1$ //$NON-NLS-2$ - document.appendChild(element); - return new XMLMemento(document, element); - } catch (ParserConfigurationException e) { - throw new Error(e.getMessage()); - } + try { + document = DocumentBuilderFactory.newInstance() + .newDocumentBuilder().newDocument(); + Element element = document.createElement("psf"); //$NON-NLS-1$ + element.setAttribute("version", "2.0"); //$NON-NLS-1$ //$NON-NLS-2$ + document.appendChild(element); + return new XMLMemento(document, element); + } catch (ParserConfigurationException e) { + throw new Error(e.getMessage()); + } } }); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetImportWizard.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetImportWizard.java index 53c69df4d..b874d1216 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetImportWizard.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ProjectSetImportWizard.java @@ -78,8 +78,8 @@ public class ProjectSetImportWizard extends Wizard implements IImportWizard { throw (Error)target; } if (target instanceof SAXException) { - ErrorDialog.openError(getShell(), null, null, new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, NLS.bind(TeamUIMessages.ProjectSetImportWizard_2, new String[] { target.getMessage() }), target)); - return false; + ErrorDialog.openError(getShell(), null, null, new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, NLS.bind(TeamUIMessages.ProjectSetImportWizard_2, new String[] { target.getMessage() }), target)); + return false; } ErrorDialog.openError(getShell(), null, null, new Status(IStatus.ERROR, TeamUIPlugin.ID, 0, NLS.bind(TeamUIMessages.ProjectSetImportWizard_3, new String[] { target.getMessage() }), target)); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/WorkingSetsDialog.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/WorkingSetsDialog.java index 08a451d17..001fed4c1 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/WorkingSetsDialog.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/WorkingSetsDialog.java @@ -133,49 +133,49 @@ public class WorkingSetsDialog extends TitleAreaDialog { } class WorkingSetLabelProvider extends LabelProvider { - private Map<ImageDescriptor, Image> icons; - - public WorkingSetLabelProvider() { - icons = new Hashtable<>(); - } - - @Override - public void dispose() { - Iterator<Image> iterator = icons.values().iterator(); - - while (iterator.hasNext()) { - Image icon = iterator.next(); - icon.dispose(); - } - super.dispose(); - } - - @Override - public Image getImage(Object object) { - Assert.isTrue(object instanceof IWorkingSet); - IWorkingSet workingSet = (IWorkingSet) object; - ImageDescriptor imageDescriptor = workingSet.getImageDescriptor(); - - if (imageDescriptor == null) { - return null; - } - - Image icon = icons.get(imageDescriptor); - if (icon == null) { - icon = imageDescriptor.createImage(); - icons.put(imageDescriptor, icon); - } - return icon; - } - - @Override - public String getText(Object object) { - Assert.isTrue(object instanceof IWorkingSet); - IWorkingSet workingSet = (IWorkingSet) object; - return workingSet.getLabel(); - } + private Map<ImageDescriptor, Image> icons; + + public WorkingSetLabelProvider() { + icons = new Hashtable<>(); } + @Override + public void dispose() { + Iterator<Image> iterator = icons.values().iterator(); + + while (iterator.hasNext()) { + Image icon = iterator.next(); + icon.dispose(); + } + super.dispose(); + } + + @Override + public Image getImage(Object object) { + Assert.isTrue(object instanceof IWorkingSet); + IWorkingSet workingSet = (IWorkingSet) object; + ImageDescriptor imageDescriptor = workingSet.getImageDescriptor(); + + if (imageDescriptor == null) { + return null; + } + + Image icon = icons.get(imageDescriptor); + if (icon == null) { + icon = imageDescriptor.createImage(); + icons.put(imageDescriptor, icon); + } + return icon; + } + + @Override + public String getText(Object object) { + Assert.isTrue(object instanceof IWorkingSet); + IWorkingSet workingSet = (IWorkingSet) object; + return workingSet.getLabel(); + } + } + public String getSelectedWorkingSet(){ return selectedWorkingSet; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageCompareEditorInput.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageCompareEditorInput.java index 158028f82..2017ccd88 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageCompareEditorInput.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageCompareEditorInput.java @@ -248,8 +248,8 @@ public abstract class PageCompareEditorInput extends CompareEditorInput implemen try { // TODO: we need a better progress story here (i.e. support for cancellation) bug 127075 manager.busyCursorWhile(monitor -> { - prepareInput(input, getCompareConfiguration(), monitor); - hookContentChangeListener(input); + prepareInput(input, getCompareConfiguration(), monitor); + hookContentChangeListener(input); }); } catch (InvocationTargetException e) { Utils.handle(e); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageSaveablePart.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageSaveablePart.java index 69a0e8908..3b5ed5ddd 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageSaveablePart.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/PageSaveablePart.java @@ -269,8 +269,8 @@ public abstract class PageSaveablePart extends SaveablePartAdapter implements IC try { // TODO: we need a better progress story here (i.e. support for cancellation) bug 127075 manager.busyCursorWhile(monitor -> { - prepareInput(input, getCompareConfiguration(), monitor); - hookContentChangeListener(input); + prepareInput(input, getCompareConfiguration(), monitor); + hookContentChangeListener(input); }); } catch (InvocationTargetException e) { Utils.handle(e); @@ -372,12 +372,12 @@ public abstract class PageSaveablePart extends SaveablePartAdapter implements IC return null; } - /** - * Set whether the file contents panes should be shown. If they are not, - * only the page will be shown. - * - * @param showContentPanes whether to show contents pane - */ + /** + * Set whether the file contents panes should be shown. If they are not, + * only the page will be shown. + * + * @param showContentPanes whether to show contents pane + */ public void setShowContentPanes(boolean showContentPanes) { this.showContentPanes = showContentPanes; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamOperation.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamOperation.java index 43e3214e2..15c81f114 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamOperation.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamOperation.java @@ -66,20 +66,20 @@ public abstract class TeamOperation extends JobChangeAdapter implements IRunnabl */ private static class TeamOperationJobContext extends JobRunnableContext { - private final TeamOperation operation; - private IAction gotoAction; + private final TeamOperation operation; + private IAction gotoAction; - public TeamOperationJobContext(TeamOperation operation) { - super(operation.getJobName(), operation, operation.getSite()); - this.operation = operation; - } + public TeamOperationJobContext(TeamOperation operation) { + super(operation.getJobName(), operation, operation.getSite()); + this.operation = operation; + } @Override protected void configureJob(Job job) { - super.configureJob(job); - if (operation.isKeepOneProgressServiceEntry()) - job.setProperty(IProgressConstants.KEEPONE_PROPERTY, Boolean.TRUE); - else if(operation.getKeepOperation()) + super.configureJob(job); + if (operation.isKeepOneProgressServiceEntry()) + job.setProperty(IProgressConstants.KEEPONE_PROPERTY, Boolean.TRUE); + else if(operation.getKeepOperation()) job.setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); gotoAction = operation.getGotoAction(); if(gotoAction != null) @@ -89,30 +89,30 @@ public abstract class TeamOperation extends JobChangeAdapter implements IRunnabl job.setProperty(IProgressConstants.ICON_PROPERTY, icon); } - @Override + @Override protected boolean belongsTo(IContextJob job, Object family) { - if (family instanceof IContextJob) { - IContextJob otherJob = (IContextJob)family; - IRunnableWithProgress runnable = otherJob.getRunnable(); - if (runnable instanceof TeamOperation) { - return operation.isSameFamilyAs((TeamOperation)runnable); - } - } - return operation.belongsTo(family); - } + if (family instanceof IContextJob) { + IContextJob otherJob = (IContextJob)family; + IRunnableWithProgress runnable = otherJob.getRunnable(); + if (runnable instanceof TeamOperation) { + return operation.isSameFamilyAs((TeamOperation)runnable); + } + } + return operation.belongsTo(family); + } - @Override + @Override protected IStatus getCompletionStatus() { - if (gotoAction != null) { - return new Status(IStatus.OK, TeamUIPlugin.ID, IStatus.OK, gotoAction.getText(), null); - } - return super.getCompletionStatus(); - } + if (gotoAction != null) { + return new Status(IStatus.OK, TeamUIPlugin.ID, IStatus.OK, gotoAction.getText(), null); + } + return super.getCompletionStatus(); + } - @Override + @Override protected boolean isUser() { - return operation.isUserInitiated(); - } + return operation.isUserInitiated(); + } } /** @@ -124,7 +124,7 @@ public abstract class TeamOperation extends JobChangeAdapter implements IRunnabl this(part, null); } - /** + /** * Create an team operation that will run in the given context. * @param context a runnable context */ @@ -251,75 +251,75 @@ public abstract class TeamOperation extends JobChangeAdapter implements IRunnabl } /** - * This method is called to allow subclasses to have the results of the - * operation remain available to the user in the progress service even after - * the job is done. This method is only relevant if the operation is run as - * a job (i.e., <code>canRunAsJob</code> returns <code>true</code>). - * - * @return <code>true</code> to keep the operation and <code>false</code> - * otherwise. - */ + * This method is called to allow subclasses to have the results of the + * operation remain available to the user in the progress service even after + * the job is done. This method is only relevant if the operation is run as + * a job (i.e., <code>canRunAsJob</code> returns <code>true</code>). + * + * @return <code>true</code> to keep the operation and <code>false</code> + * otherwise. + */ protected boolean getKeepOperation() { return false; } /** - * This method is similar to <code>getKeepOperation</code> but will - * only keep one entry of a particular type available. - * This method is only relevant if the operation is run as - * a job (i.e., <code>canRunAsJob</code> returns <code>true</code>). - * Subclasses that override this method should also override - * <code>isSameFamilyAs</code> in order to match operations of the same type. - * - * @return <code>true</code> to keep the operation and <code>false</code> - * otherwise. - * @since 3.1 - */ - public boolean isKeepOneProgressServiceEntry() { - return false; - } + * This method is similar to <code>getKeepOperation</code> but will + * only keep one entry of a particular type available. + * This method is only relevant if the operation is run as + * a job (i.e., <code>canRunAsJob</code> returns <code>true</code>). + * Subclasses that override this method should also override + * <code>isSameFamilyAs</code> in order to match operations of the same type. + * + * @return <code>true</code> to keep the operation and <code>false</code> + * otherwise. + * @since 3.1 + */ + public boolean isKeepOneProgressServiceEntry() { + return false; + } - /** - * Return whether this Team operation belongs to the same family - * as the given operation for the purpose of showing only one - * operation of the same type in the progress service when - * <code>isKeepOneProgressServiceEntry</code> is overridden to - * return <code>true</code>. By default, - * <code>false</code> is returned. Subclasses may override. - * @param operation a team operation - * @since 3.1 - */ - protected boolean isSameFamilyAs(TeamOperation operation) { - return false; - } + /** + * Return whether this Team operation belongs to the same family + * as the given operation for the purpose of showing only one + * operation of the same type in the progress service when + * <code>isKeepOneProgressServiceEntry</code> is overridden to + * return <code>true</code>. By default, + * <code>false</code> is returned. Subclasses may override. + * @param operation a team operation + * @since 3.1 + */ + protected boolean isSameFamilyAs(TeamOperation operation) { + return false; + } - /** - * Return whether the job that is running this operation should be considered - * a member member of the given family. Subclasses can override this method in - * order to support the family based functionality provided by the {@link IJobManager}. - * By default, <code>false</code> is always returned. Subclasses that override the - * <code>isKeepOneProgressServiceEntry</code> method do not need to override - * this method, but instead should override <code>isSameFamilyAs</code>. - * - * @param family the family being tested. - * @return whether the job that is running this operation should be considered - * a member member of the given family. - * @since 3.1 - */ - public boolean belongsTo(Object family) { - return false; - } + /** + * Return whether the job that is running this operation should be considered + * a member member of the given family. Subclasses can override this method in + * order to support the family based functionality provided by the {@link IJobManager}. + * By default, <code>false</code> is always returned. Subclasses that override the + * <code>isKeepOneProgressServiceEntry</code> method do not need to override + * this method, but instead should override <code>isSameFamilyAs</code>. + * + * @param family the family being tested. + * @return whether the job that is running this operation should be considered + * a member member of the given family. + * @since 3.1 + */ + public boolean belongsTo(Object family) { + return false; + } - /** - * Indicates whether the operation was user initiated. The - * progress for user initiated jobs may be presented differently - * than non-user initiated operations if they are run as jobs. - * @return whether the operation is user initiated - * @since 3.1 - */ - public boolean isUserInitiated() { - return true; - } + /** + * Indicates whether the operation was user initiated. The + * progress for user initiated jobs may be presented differently + * than non-user initiated operations if they are run as jobs. + * @return whether the operation is user initiated + * @since 3.1 + */ + public boolean isUserInitiated() { + return true; + } /** * Return a shell that can be used by the operation to display dialogs, etc. diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamUI.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamUI.java index 5c51194d5..5c8b1c71d 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamUI.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/TeamUI.java @@ -43,10 +43,10 @@ public class TeamUI { */ public static final String GLOBAL_IGNORES_CHANGED = TeamUIPlugin.ID + "global_ignores_changed"; //$NON-NLS-1$ - /** - * Property constant indicating the global file types list has changed. - * @since 3.1 - */ + /** + * Property constant indicating the global file types list has changed. + * @since 3.1 + */ public static final String GLOBAL_FILE_TYPES_CHANGED = TeamUIPlugin.ID + "global_file_types_changed"; //$NON-NLS-1$ /** diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/IHistoryPage.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/IHistoryPage.java index 160ab3d2f..5287720cc 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/IHistoryPage.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/IHistoryPage.java @@ -60,19 +60,19 @@ import org.eclipse.ui.SubActionBars; */ public interface IHistoryPage { - /** - * Property name constant (value <code>"org.eclipse.team.ui.name"</code>) - * for the page's name. - * @since 3.3 - */ - public static final String P_NAME = TeamUIPlugin.ID + ".name"; //$NON-NLS-1$ - - /** - * Property name constant (value <code>"org.eclipse.team.ui.description"</code>) - * for an page's description. - * @since 3.3 - */ - public static final String P_DESCRIPTION = TeamUIPlugin.ID + ".description"; //$NON-NLS-1$ + /** + * Property name constant (value <code>"org.eclipse.team.ui.name"</code>) + * for the page's name. + * @since 3.3 + */ + public static final String P_NAME = TeamUIPlugin.ID + ".name"; //$NON-NLS-1$ + + /** + * Property name constant (value <code>"org.eclipse.team.ui.description"</code>) + * for an page's description. + * @since 3.3 + */ + public static final String P_DESCRIPTION = TeamUIPlugin.ID + ".description"; //$NON-NLS-1$ /** * Fetches and populates the history page for the given Object. Clients diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/RevisionAnnotationController.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/RevisionAnnotationController.java index e3b931542..02c54d98a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/RevisionAnnotationController.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/history/RevisionAnnotationController.java @@ -138,7 +138,7 @@ public abstract class RevisionAnnotationController { } catch (PartInitException e) { } - return null; + return null; } /** @@ -165,29 +165,29 @@ public abstract class RevisionAnnotationController { } - private static ITextEditor getEditor(String id, Object fileRevision, IStorage storage) throws PartInitException { - final IWorkbench workbench= PlatformUI.getWorkbench(); - final IWorkbenchWindow window= workbench.getActiveWorkbenchWindow(); - IWorkbenchPage page= window.getActivePage(); + private static ITextEditor getEditor(String id, Object fileRevision, IStorage storage) throws PartInitException { + final IWorkbench workbench= PlatformUI.getWorkbench(); + final IWorkbenchWindow window= workbench.getActiveWorkbenchWindow(); + IWorkbenchPage page= window.getActivePage(); IEditorPart part = page.openEditor(new FileRevisionEditorInput(fileRevision, storage), id); - if (part instanceof ITextEditor) { - return (ITextEditor)part; - } else { - // We asked for a text editor but didn't get one - // so open a vanilla text editor - page.closeEditor(part, false); - part = page.openEditor(new FileRevisionEditorInput(fileRevision, storage), EditorsUI.DEFAULT_TEXT_EDITOR_ID); - if (part instanceof ITextEditor) { - return (ITextEditor)part; - } else { - // There is something really wrong so just bail - throw new PartInitException(TeamUIMessages.RevisionAnnotationController_0); - } - } - } - - private static String getEditorId(IStorage storage) { - String id; + if (part instanceof ITextEditor) { + return (ITextEditor)part; + } else { + // We asked for a text editor but didn't get one + // so open a vanilla text editor + page.closeEditor(part, false); + part = page.openEditor(new FileRevisionEditorInput(fileRevision, storage), EditorsUI.DEFAULT_TEXT_EDITOR_ID); + if (part instanceof ITextEditor) { + return (ITextEditor)part; + } else { + // There is something really wrong so just bail + throw new PartInitException(TeamUIMessages.RevisionAnnotationController_0); + } + } + } + + private static String getEditorId(IStorage storage) { + String id; IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); IEditorDescriptor descriptor = registry.getDefaultEditor(storage.getName()); if (descriptor == null || !descriptor.isInternal()) { @@ -203,8 +203,8 @@ public abstract class RevisionAnnotationController { id = EditorsUI.DEFAULT_TEXT_EDITOR_ID; } } - return id; - } + return id; + } @@ -212,7 +212,7 @@ public abstract class RevisionAnnotationController { if (file == null) return null; FileEditorInput input = new FileEditorInput(file); - IEditorPart[] editors = findOpenEditorsForFile(page, input); + IEditorPart[] editors = findOpenEditorsForFile(page, input); return findTextEditor(page, editors, input); } @@ -235,8 +235,8 @@ public abstract class RevisionAnnotationController { for (int i = 0; i < parts.length; i++) { IEditorPart editorPart = parts[i]; if (editorPart instanceof AbstractDecoratedTextEditor) { - page.activate(mpep); - mpep.setActiveEditor(editorPart); + page.activate(mpep); + mpep.setActiveEditor(editorPart); return (AbstractDecoratedTextEditor) editorPart; } } @@ -245,15 +245,15 @@ public abstract class RevisionAnnotationController { } private static IEditorPart[] findOpenEditorsForFile(IWorkbenchPage page, FileEditorInput input) { - final IEditorReference[] references= page.findEditors(input, null, IWorkbenchPage.MATCH_INPUT); - final List<IEditorPart> editors = new ArrayList<>(); + final IEditorReference[] references= page.findEditors(input, null, IWorkbenchPage.MATCH_INPUT); + final List<IEditorPart> editors = new ArrayList<>(); for (int i= 0; i < references.length; i++) { IEditorReference reference= references[i]; IEditorPart editor= reference.getEditor(false); editors.add(editor); } - return editors.toArray(new IEditorPart[editors.size()]); + return editors.toArray(new IEditorPart[editors.size()]); } private static AbstractDecoratedTextEditor findOpenTextEditorFor(IWorkbenchPage page, Object object) { @@ -263,9 +263,9 @@ public abstract class RevisionAnnotationController { IFile file = (IFile) object; return findOpenTextEditorForFile(page, file); } - final IWorkbench workbench= PlatformUI.getWorkbench(); - final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - IEditorReference[] references= window.getActivePage().getEditorReferences(); + final IWorkbench workbench= PlatformUI.getWorkbench(); + final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + IEditorReference[] references= window.getActivePage().getEditorReferences(); for (int i= 0; i < references.length; i++) { IEditorReference reference= references[i]; try { @@ -279,7 +279,7 @@ public abstract class RevisionAnnotationController { } } - return null; + return null; } private static IRevisionRulerColumnExtension findEditorRevisonRulerColumn(IWorkbenchPage page, Object object) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SaveableComparison.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SaveableComparison.java index c8e7ebc9f..221dc057b 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SaveableComparison.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SaveableComparison.java @@ -34,10 +34,10 @@ import org.eclipse.ui.Saveable; */ public abstract class SaveableComparison extends Saveable { - /** - * The property id for <code>isDirty</code>. - */ - public static final int PROP_DIRTY = IWorkbenchPartConstants.PROP_DIRTY; + /** + * The property id for <code>isDirty</code>. + */ + public static final int PROP_DIRTY = IWorkbenchPartConstants.PROP_DIRTY; private boolean dirty; private ListenerList<IPropertyListener> listeners = new ListenerList<>(ListenerList.IDENTITY); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SynchronizationActionProvider.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SynchronizationActionProvider.java index 3f8c44aa3..9ecf1b83e 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SynchronizationActionProvider.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/mapping/SynchronizationActionProvider.java @@ -166,7 +166,7 @@ public class SynchronizationActionProvider extends CommonActionProvider { manager.registerHandler(actionId, handlers.get(actionId)); } } - final IContributionItem fileGroup = menu.find(ISynchronizePageConfiguration.FILE_GROUP); + final IContributionItem fileGroup = menu.find(ISynchronizePageConfiguration.FILE_GROUP); if (openWithActions != null && fileGroup != null) { openWithActions.fillContextMenu(menu, fileGroup.getId()); } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/AbstractSynchronizeParticipant.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/AbstractSynchronizeParticipant.java index 753c5bca8..37c1b851b 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/AbstractSynchronizeParticipant.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/AbstractSynchronizeParticipant.java @@ -291,13 +291,13 @@ public abstract class AbstractSynchronizeParticipant extends PlatformObject impl public final ISynchronizePageConfiguration createPageConfiguration() { SynchronizePageConfiguration configuration = new SynchronizePageConfiguration(this); if (isViewerContributionsSupported()) { - configuration.setProperty(ISynchronizePageConfiguration.P_OBJECT_CONTRIBUTION_ID, getId()); + configuration.setProperty(ISynchronizePageConfiguration.P_OBJECT_CONTRIBUTION_ID, getId()); } initializeConfiguration(configuration); return configuration; } - /** + /** * This method is invoked after a page configuration is created but before it is returned by the * <code>createPageConfiguration</code> method. Subclasses can implement this method to * tailor the configuration in ways appropriate to the participant. @@ -323,13 +323,13 @@ public abstract class AbstractSynchronizeParticipant extends PlatformObject impl */ @Override public void prepareCompareInput(ISynchronizeModelElement element, CompareConfiguration config, IProgressMonitor monitor) throws TeamException { - SyncInfo sync = getSyncInfo(element); - if (sync != null) - Utils.updateLabels(sync, config, monitor); - if (element instanceof SyncInfoModelElement) { + SyncInfo sync = getSyncInfo(element); + if (sync != null) + Utils.updateLabels(sync, config, monitor); + if (element instanceof SyncInfoModelElement) { SyncInfoModelElement node = (SyncInfoModelElement)element; - (node).cacheContents(monitor); - } + (node).cacheContents(monitor); + } } /* @@ -339,16 +339,16 @@ public abstract class AbstractSynchronizeParticipant extends PlatformObject impl * @return the sync info for the element or <code>null</code> */ private SyncInfo getSyncInfo(ISynchronizeModelElement element) { - if (element instanceof IAdaptable) { - return ((IAdaptable)element).getAdapter(SyncInfo.class); - } - return null; + if (element instanceof IAdaptable) { + return ((IAdaptable)element).getAdapter(SyncInfo.class); + } + return null; } - @Override + @Override public PreferencePage[] getPreferencePages() { - return new PreferencePage[] { new SyncViewerPreferencePage() }; - } + return new PreferencePage[] { new SyncViewerPreferencePage() }; + } /** * Return whether this participant supports the contribution of actions to @@ -377,11 +377,11 @@ public abstract class AbstractSynchronizeParticipant extends PlatformObject impl * </pre> * * - * @return whether this participant supports the contribution of actions to + * @return whether this participant supports the contribution of actions to * the context menu using the <code>org.eclipse.ui.popupMenus</code> extension point - * @since 3.1 - */ - protected boolean isViewerContributionsSupported() { - return false; - } + * @since 3.1 + */ + protected boolean isViewerContributionsSupported() { + return false; + } } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeModelElement.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeModelElement.java index 0325fbc20..a2e21f185 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeModelElement.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeModelElement.java @@ -25,7 +25,7 @@ import org.eclipse.team.internal.ui.TeamUIPlugin; * These are elements created to display synchronization state to the user. These elements are found in * the generated diff tree viewer created by a {@link SubscriberParticipant}. Since it implements * {@link ITypedElement} and {@link ICompareInput} they can be used as input to compare components. - * <p> + * <p> * Clients typically use this interface as is, but may implement it if required. * </p> * @since 3.0 diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizePageConfiguration.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizePageConfiguration.java index f4185e3ec..9a8cefb88 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizePageConfiguration.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizePageConfiguration.java @@ -82,7 +82,7 @@ public interface ISynchronizePageConfiguration { * determines which object contribution actions appear in the * context menu for the page. This defaults to the id of the * participant but can be set to another id or <code>null</code> - * @since 3.1 + * @since 3.1 */ public static final String P_OBJECT_CONTRIBUTION_ID = TeamUIPlugin.ID + ".P_OBJECT_CONTRIBUTION_ID"; //$NON-NLS-1$ @@ -142,7 +142,7 @@ public interface ISynchronizePageConfiguration { /** * The id of the sort group that determines where sort * actions or submenus appear. - * @since 3.1 + * @since 3.1 */ public final static String SORT_GROUP = "sort"; //$NON-NLS-1$ @@ -174,7 +174,7 @@ public interface ISynchronizePageConfiguration { * The id of the group that determines where workbench object contributions * should appear. This group will only be used if there is an * OBJECT_CONTRIBUTION_ID set in the configuration - * @since 3.1 + * @since 3.1 */ public static final String OBJECT_CONTRIBUTIONS_GROUP = IWorkbenchActionConstants.MB_ADDITIONS; diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeParticipant.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeParticipant.java index 577d2f959..f2b95e9c4 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeParticipant.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeParticipant.java @@ -253,17 +253,17 @@ public interface ISynchronizeParticipant extends IExecutableExtension, IAdaptabl * @since 3.1 */ public void prepareCompareInput( - ISynchronizeModelElement element, - CompareConfiguration configuration, - IProgressMonitor monitor) + ISynchronizeModelElement element, + CompareConfiguration configuration, + IProgressMonitor monitor) throws TeamException; - /** - * Return the list of preference pages that are associated with this participant - * @return the list of preference pages that are associated with this participant - * @since 3.1 - */ - public PreferencePage[] getPreferencePages(); + /** + * Return the list of preference pages that are associated with this participant + * @return the list of preference pages that are associated with this participant + * @since 3.1 + */ + public PreferencePage[] getPreferencePages(); /** * Returns the help context id of this participant. diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeScope.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeScope.java index 6e625c3b3..d978e202c 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeScope.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ISynchronizeScope.java @@ -34,7 +34,7 @@ public interface ISynchronizeScope { /** * Property used to indicate when the name of the scope has changed. - * @since 3.1 + * @since 3.1 */ public static final String NAME = "prop_name"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelMergeOperation.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelMergeOperation.java index 54a0acba4..a3954d833 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelMergeOperation.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelMergeOperation.java @@ -213,16 +213,16 @@ public abstract class ModelMergeOperation extends ModelOperation { * @param status the status returned from the mergers that reported the validation failures */ protected void handleValidationFailure(final IStatus status) { - final boolean[] result = new boolean[] { false }; - Runnable runnable = () -> { + final boolean[] result = new boolean[] { false }; + Runnable runnable = () -> { ErrorDialog dialog = new ErrorDialog(getShell(), TeamUIMessages.ModelMergeOperation_0, TeamUIMessages.ModelMergeOperation_1, status, IStatus.ERROR | IStatus.WARNING | IStatus.INFO) { @Override protected void createButtonsForButtonBar(Composite parent) { - createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, - false); + createButton(parent, IDialogConstants.YES_ID, IDialogConstants.YES_LABEL, + false); createButton(parent, IDialogConstants.NO_ID, IDialogConstants.NO_LABEL, true); - createDetailsButton(parent); + createDetailsButton(parent); } @Override diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelOperation.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelOperation.java index 05b57b3ae..3a8b51bde 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelOperation.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelOperation.java @@ -392,24 +392,24 @@ public abstract class ModelOperation extends TeamOperation { return showAllMappings(requestPreviewMessage); } - private boolean showAllMappings(final String requestPreviewMessage) { - final boolean[] canceled = new boolean[] { false }; - final boolean[] forcePreview = new boolean[] { false }; - Display.getDefault().syncExec(() -> { - AdditionalMappingsDialog dialog = new AdditionalMappingsDialog(getShell(), TeamUIMessages.ResourceMappingOperation_0, getScope(), getContext()); - dialog.setPreviewMessage(requestPreviewMessage); - int result = dialog.open(); - canceled[0] = result != Window.OK; - if (requestPreviewMessage != null) { - forcePreview[0] = dialog.isForcePreview(); - } + private boolean showAllMappings(final String requestPreviewMessage) { + final boolean[] canceled = new boolean[] { false }; + final boolean[] forcePreview = new boolean[] { false }; + Display.getDefault().syncExec(() -> { + AdditionalMappingsDialog dialog = new AdditionalMappingsDialog(getShell(), TeamUIMessages.ResourceMappingOperation_0, getScope(), getContext()); + dialog.setPreviewMessage(requestPreviewMessage); + int result = dialog.open(); + canceled[0] = result != Window.OK; + if (requestPreviewMessage != null) { + forcePreview[0] = dialog.isForcePreview(); + } }); - if (canceled[0]) { - throw new OperationCanceledException(); - } - return forcePreview[0]; - } + if (canceled[0]) { + throw new OperationCanceledException(); + } + return forcePreview[0]; + } /** * Return the synchronization context for the operation or <code>null</code> diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipant.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipant.java index 14c0ee082..bf5ad9a3c 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipant.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipant.java @@ -213,7 +213,7 @@ public class ModelSynchronizeParticipant extends * @since 3.1 */ protected final String getShortName() { - return super.getName(); + return super.getName(); } @Override @@ -365,9 +365,9 @@ public class ModelSynchronizeParticipant extends private void internalRefresh(ResourceMapping[] mappings, String jobName, String taskName, IWorkbenchSite site, IRefreshSubscriberListener listener) { if (jobName == null) - jobName = getShortTaskName(); + jobName = getShortTaskName(); if (taskName == null) - taskName = getLongTaskName(mappings); + taskName = getLongTaskName(mappings); Job.getJobManager().cancel(this); RefreshParticipantJob job = new RefreshModelParticipantJob(this, jobName, taskName, mappings, listener); job.setUser(true); @@ -401,22 +401,22 @@ public class ModelSynchronizeParticipant extends * @return the long task name * @since 3.1 */ - protected String getLongTaskName(ResourceMapping[] mappings) { - if (mappings == null) { - // If the mappings are null, assume we are refreshing everything - mappings = getContext().getScope().getMappings(); - } - int mappingCount = mappings.length; - if (mappingCount == getContext().getScope().getMappings().length) { - // Assume we are refreshing everything and only use the input mapping count - mappings = getContext().getScope().getInputMappings(); - mappingCount = mappings.length; - } - if (mappingCount == 1) { - return NLS.bind(TeamUIMessages.Participant_synchronizingMoreDetails, new String[] { getShortName(), Utils.getLabel(mappings[0]) }); - } - return NLS.bind(TeamUIMessages.Participant_synchronizingResources, new String[] { getShortName(), Integer.toString(mappingCount) }); - } + protected String getLongTaskName(ResourceMapping[] mappings) { + if (mappings == null) { + // If the mappings are null, assume we are refreshing everything + mappings = getContext().getScope().getMappings(); + } + int mappingCount = mappings.length; + if (mappingCount == getContext().getScope().getMappings().length) { + // Assume we are refreshing everything and only use the input mapping count + mappings = getContext().getScope().getInputMappings(); + mappingCount = mappings.length; + } + if (mappingCount == 1) { + return NLS.bind(TeamUIMessages.Participant_synchronizingMoreDetails, new String[] { getShortName(), Utils.getLabel(mappings[0]) }); + } + return NLS.bind(TeamUIMessages.Participant_synchronizingResources, new String[] { getShortName(), Integer.toString(mappingCount) }); + } private IRefreshable createRefreshable() { return new IRefreshable() { @@ -576,10 +576,10 @@ public class ModelSynchronizeParticipant extends if (refreshSchedule != null) { refreshSchedule.dispose(); } - this.refreshSchedule = schedule; + this.refreshSchedule = schedule; } // Always fir the event since the schedule may have been changed - firePropertyChange(this, AbstractSynchronizeParticipant.P_SCHEDULED, schedule, schedule); + firePropertyChange(this, AbstractSynchronizeParticipant.P_SCHEDULED, schedule, schedule); } /** diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipantActionGroup.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipantActionGroup.java index 94ac3f6b0..b3222d10e 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipantActionGroup.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ModelSynchronizeParticipantActionGroup.java @@ -120,10 +120,10 @@ public class ModelSynchronizeParticipantActionGroup extends SynchronizePageActio @Override public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); - if (actionBars != null && showPreferences != null) { - IMenuManager menu = actionBars.getMenuManager(); - appendToGroup(menu, ISynchronizePageConfiguration.PREFERENCES_GROUP, showPreferences); - } + if (actionBars != null && showPreferences != null) { + IMenuManager menu = actionBars.getMenuManager(); + appendToGroup(menu, ISynchronizePageConfiguration.PREFERENCES_GROUP, showPreferences); + } } @Override @@ -134,22 +134,22 @@ public class ModelSynchronizeParticipantActionGroup extends SynchronizePageActio addMergeActions(cmm); } Object[] elements = ((IStructuredSelection)getContext().getSelection()).toArray(); - if (elements.length > 0 && openInCompareAction != null) { - IContributionItem fileGroup = findGroup(menu, ISynchronizePageConfiguration.FILE_GROUP); - if (fileGroup != null) { - ModelSynchronizeParticipant msp = ((ModelSynchronizeParticipant)getConfiguration().getParticipant()); - boolean allElementsHaveCompareInput = true; - for (int i = 0; i < elements.length; i++) { - if (!msp.hasCompareInputFor(elements[i])) { - allElementsHaveCompareInput = false; - break; - } - } - if (allElementsHaveCompareInput) { - menu.appendToGroup(fileGroup.getId(), openInCompareAction); - } - } - } + if (elements.length > 0 && openInCompareAction != null) { + IContributionItem fileGroup = findGroup(menu, ISynchronizePageConfiguration.FILE_GROUP); + if (fileGroup != null) { + ModelSynchronizeParticipant msp = ((ModelSynchronizeParticipant)getConfiguration().getParticipant()); + boolean allElementsHaveCompareInput = true; + for (int i = 0; i < elements.length; i++) { + if (!msp.hasCompareInputFor(elements[i])) { + allElementsHaveCompareInput = false; + break; + } + } + if (allElementsHaveCompareInput) { + menu.appendToGroup(fileGroup.getId(), openInCompareAction); + } + } + } } /* diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageCompareEditorInput.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageCompareEditorInput.java index c85856776..c53e2b822 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageCompareEditorInput.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageCompareEditorInput.java @@ -186,7 +186,7 @@ public class ParticipantPageCompareEditorInput extends PageCompareEditorInput { CompareConfiguration configuration, IProgressMonitor monitor) throws InvocationTargetException { monitor.beginTask(TeamUIMessages.SyncInfoCompareInput_3, 100); - monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); + monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); try { // First, see if the active buffer is changing checkForBufferChange(pageConfiguration.getSite().getShell(), input, false /* cancel not allowed */, monitor); @@ -205,8 +205,8 @@ public class ParticipantPageCompareEditorInput extends PageCompareEditorInput { } catch (CoreException e) { throw new InvocationTargetException(e); } finally { - monitor.done(); - } + monitor.done(); + } } private void checkForBufferChange(Shell shell, final ICompareInput input, boolean cancelAllowed, IProgressMonitor monitor) throws CoreException { @@ -257,11 +257,11 @@ public class ParticipantPageCompareEditorInput extends PageCompareEditorInput { private static void commit(IProgressMonitor pm, DiffNode node) throws CoreException { ITypedElement left = node.getLeft(); if (left instanceof LocalResourceTypedElement) - ((LocalResourceTypedElement) left).commit(pm); + ((LocalResourceTypedElement) left).commit(pm); ITypedElement right = node.getRight(); if (right instanceof LocalResourceTypedElement) - ((LocalResourceTypedElement) right).commit(pm); + ((LocalResourceTypedElement) right).commit(pm); IDiffElement[] children = node.getChildren(); for (int i = 0; i < children.length; i++) { @@ -276,7 +276,7 @@ public class ParticipantPageCompareEditorInput extends PageCompareEditorInput { if (source instanceof DiffNode) { commit(new NullProgressMonitor(), (DiffNode) source); } else if (source instanceof LocalResourceTypedElement) { - ((LocalResourceTypedElement) source).commit(new NullProgressMonitor()); + ((LocalResourceTypedElement) source).commit(new NullProgressMonitor()); } } catch (CoreException e) { Utils.handle(e); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPagePane.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPagePane.java index b3da4335a..5b2fe962a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPagePane.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPagePane.java @@ -117,7 +117,7 @@ public final class ParticipantPagePane { try { ((ISynchronizePage)fPage).init(pageConfiguration.getSite()); } catch (PartInitException e1) { - TeamUIPlugin.log(IStatus.ERROR, TeamUIMessages.ParticipantPagePane_0, e1); + TeamUIPlugin.log(IStatus.ERROR, TeamUIMessages.ParticipantPagePane_0, e1); } fPage.createControl(fEditionPane); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageSaveablePart.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageSaveablePart.java index 50458b981..d563cb125 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageSaveablePart.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/ParticipantPageSaveablePart.java @@ -137,7 +137,7 @@ public class ParticipantPageSaveablePart extends PageSaveablePart implements ICo if (source instanceof DiffNode) { commit(new NullProgressMonitor(), (DiffNode) source); } else if (source instanceof LocalResourceTypedElement) { - ((LocalResourceTypedElement) source).commit(new NullProgressMonitor()); + ((LocalResourceTypedElement) source).commit(new NullProgressMonitor()); } } catch (CoreException e) { Utils.handle(e); @@ -237,7 +237,7 @@ public class ParticipantPageSaveablePart extends PageSaveablePart implements ICo @Override protected void prepareInput(final ICompareInput input, CompareConfiguration configuration, IProgressMonitor monitor) throws InvocationTargetException { monitor.beginTask(TeamUIMessages.SyncInfoCompareInput_3, 100); - monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); + monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); try { // First, see if the active buffer is changing checkForBufferChange(pageConfiguration.getSite().getShell(), input, false /* cancel not allowed */, monitor); @@ -256,8 +256,8 @@ public class ParticipantPageSaveablePart extends PageSaveablePart implements ICo } catch (CoreException e) { throw new InvocationTargetException(e); } finally { - monitor.done(); - } + monitor.done(); + } } private void checkForBufferChange(Shell shell, final ICompareInput input, boolean cancelAllowed, IProgressMonitor monitor) throws CoreException { @@ -286,11 +286,11 @@ public class ParticipantPageSaveablePart extends PageSaveablePart implements ICo private static void commit(IProgressMonitor pm, DiffNode node) throws CoreException { ITypedElement left = node.getLeft(); if (left instanceof LocalResourceTypedElement) - ((LocalResourceTypedElement) left).commit(pm); + ((LocalResourceTypedElement) left).commit(pm); ITypedElement right = node.getRight(); if (right instanceof LocalResourceTypedElement) - ((LocalResourceTypedElement) right).commit(pm); + ((LocalResourceTypedElement) right).commit(pm); IDiffElement[] children = node.getChildren(); for (int i = 0; i < children.length; i++) { diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SubscriberParticipant.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SubscriberParticipant.java index 2d653c03a..bfe0fa805 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SubscriberParticipant.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SubscriberParticipant.java @@ -203,12 +203,12 @@ public abstract class SubscriberParticipant extends AbstractSynchronizeParticipa internalRefresh(resources, shortTaskName, longTaskName, site, listener); } - /** + /** * Refresh a participant. The returned status describes the result of the refresh. - * @param resources - * @param taskName - * @param monitor - * @return a status + * @param resources + * @param taskName + * @param monitor + * @return a status */ public final IStatus refreshNow(IResource[] resources, String taskName, IProgressMonitor monitor) { Job.getJobManager().cancel(this); @@ -239,7 +239,7 @@ public abstract class SubscriberParticipant extends AbstractSynchronizeParticipa * @since 3.1 */ protected final String getShortName() { - return super.getName(); + return super.getName(); } /** @@ -361,10 +361,10 @@ public abstract class SubscriberParticipant extends AbstractSynchronizeParticipa if (refreshSchedule != null) { refreshSchedule.dispose(); } - this.refreshSchedule = schedule; + this.refreshSchedule = schedule; } // Always fir the event since the schedule may have been changed - firePropertyChange(this, AbstractSynchronizeParticipant.P_SCHEDULED, schedule, schedule); + firePropertyChange(this, AbstractSynchronizeParticipant.P_SCHEDULED, schedule, schedule); } /** @@ -413,32 +413,32 @@ public abstract class SubscriberParticipant extends AbstractSynchronizeParticipa * Returns the long task name to describe the behavior of the * refresh operation to the user. This is typically shown in the status line when this subscriber is refreshed * in the background. - * @param resources - * @return the long task name - * @since 3.1 - */ - protected String getLongTaskName(IResource[] resources) { - int resourceCount = 0; - if (getResources().length == resources.length) { - // Assume that the resources are the same as the roots. - // If we are wrong, the message may no mention the specific resources which is OK - ISynchronizeScope scope = getScope(); - if (scope instanceof ResourceScope) { - resourceCount = scope.getRoots().length; - } - } else { - resourceCount = resources.length; - } - if (resourceCount == 1) { - return NLS.bind(TeamUIMessages.Participant_synchronizingMoreDetails, new String[] { getShortName(), resources[0].getFullPath().toString() }); - } else if (resourceCount > 1) { - return NLS.bind(TeamUIMessages.Participant_synchronizingResources, new String[] { getShortName(), Integer.toString(resourceCount) }); - } - // A resource count of zero means that it is a non-resource scope so we can print the scope name - return NLS.bind(TeamUIMessages.Participant_synchronizingDetails, new String[] { getName() }); - } - - /** + * @param resources + * @return the long task name + * @since 3.1 + */ + protected String getLongTaskName(IResource[] resources) { + int resourceCount = 0; + if (getResources().length == resources.length) { + // Assume that the resources are the same as the roots. + // If we are wrong, the message may no mention the specific resources which is OK + ISynchronizeScope scope = getScope(); + if (scope instanceof ResourceScope) { + resourceCount = scope.getRoots().length; + } + } else { + resourceCount = resources.length; + } + if (resourceCount == 1) { + return NLS.bind(TeamUIMessages.Participant_synchronizingMoreDetails, new String[] { getShortName(), resources[0].getFullPath().toString() }); + } else if (resourceCount > 1) { + return NLS.bind(TeamUIMessages.Participant_synchronizingResources, new String[] { getShortName(), Integer.toString(resourceCount) }); + } + // A resource count of zero means that it is a non-resource scope so we can print the scope name + return NLS.bind(TeamUIMessages.Participant_synchronizingDetails, new String[] { getName() }); + } + + /** * This method is invoked before the given configuration is used to * create the page (see <code>createPage(ISynchronizePageConfiguration)</code>). * The configuration would have been initialized by @@ -501,9 +501,9 @@ public abstract class SubscriberParticipant extends AbstractSynchronizeParticipa */ private void internalRefresh(IResource[] resources, String jobName, String taskName, IWorkbenchSite site, IRefreshSubscriberListener listener) { if (jobName == null) - jobName = getShortTaskName(); + jobName = getShortTaskName(); if (taskName == null) - taskName = getLongTaskName(resources); + taskName = getLongTaskName(resources); Job.getJobManager().cancel(this); RefreshParticipantJob job = new RefreshSubscriberParticipantJob(this, jobName, taskName, resources, listener); job.setUser(true); diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SyncInfoCompareInput.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SyncInfoCompareInput.java index 217b35a71..e1d8b350a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SyncInfoCompareInput.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SyncInfoCompareInput.java @@ -64,7 +64,7 @@ public final class SyncInfoCompareInput extends SaveableCompareEditorInput imple private MyDiffNode node; private String description; private IResource resource; - private ISynchronizeParticipant participant; + private ISynchronizeParticipant participant; private ISynchronizePageConfiguration synchronizeConfiguration; /* @@ -107,37 +107,37 @@ public final class SyncInfoCompareInput extends SaveableCompareEditorInput imple * @param participant the participant from which the sync info was obtained. The * name of the participant is used as the description which is displayed to the user. * @param sync the <code>SyncInfo</code> used as the base for the compare input. - * - * @since 3.1 - */ - public SyncInfoCompareInput(ISynchronizeParticipant participant, SyncInfo sync) { - this(participant.getName(), sync); - this.participant = participant; - } + * + * @since 3.1 + */ + public SyncInfoCompareInput(ISynchronizeParticipant participant, SyncInfo sync) { + this(participant.getName(), sync); + this.participant = participant; + } - public SyncInfoCompareInput(ISynchronizePageConfiguration configuration, + public SyncInfoCompareInput(ISynchronizePageConfiguration configuration, SyncInfo info) { this(configuration.getParticipant(), info); this.synchronizeConfiguration = configuration; } - @Override + @Override protected void handleDispose() { - super.handleDispose(); - if (synchronizeConfiguration != null) { - ICompareNavigator navigator = (ICompareNavigator)synchronizeConfiguration.getProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR); - if (navigator != null && navigator == super.getNavigator()) { - synchronizeConfiguration.setProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR, new CompareNavigator() { + super.handleDispose(); + if (synchronizeConfiguration != null) { + ICompareNavigator navigator = (ICompareNavigator)synchronizeConfiguration.getProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR); + if (navigator != null && navigator == super.getNavigator()) { + synchronizeConfiguration.setProperty(SynchronizePageConfiguration.P_INPUT_NAVIGATOR, new CompareNavigator() { @Override protected INavigatable[] getNavigatables() { return new INavigatable[0]; } }); - } - } - } + } + } + } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> adapter) { if (IFile.class.equals(adapter) && resource.getType() == IResource.FILE) { @@ -183,20 +183,20 @@ public final class SyncInfoCompareInput extends SaveableCompareEditorInput imple // update the title now that the remote revision number as been fetched // from the server setTitle(getTitle()); - monitor.beginTask(TeamUIMessages.SyncInfoCompareInput_3, 100); - monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); + monitor.beginTask(TeamUIMessages.SyncInfoCompareInput_3, 100); + monitor.setTaskName(TeamUIMessages.SyncInfoCompareInput_3); try { if (participant != null) { - participant.prepareCompareInput(node, getCompareConfiguration(), Policy.subMonitorFor(monitor, 100)); + participant.prepareCompareInput(node, getCompareConfiguration(), Policy.subMonitorFor(monitor, 100)); } else { - Utils.updateLabels(node.getSyncInfo(), getCompareConfiguration(), monitor); + Utils.updateLabels(node.getSyncInfo(), getCompareConfiguration(), monitor); node.cacheContents(Policy.subMonitorFor(monitor, 100)); } } catch (TeamException e) { throw new InvocationTargetException(e); } finally { - monitor.done(); - } + monitor.done(); + } return node; } diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizeModelAction.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizeModelAction.java index 7dc79f057..6a8d5be1a 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizeModelAction.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizeModelAction.java @@ -101,18 +101,18 @@ public abstract class SynchronizeModelAction extends BaseSelectionListenerAction } } - /** - * Create and run the operation for this action. By default, the operation is created - * by calling <code>getSubscriberOperation</code> and then run. Subclasses may - * override. - * - * @throws InvocationTargetException - * @throws InterruptedException - * @since 3.1 - */ - protected void runOperation() throws InvocationTargetException, InterruptedException { - getSubscriberOperation(configuration, getFilteredDiffElements()).run(); - } + /** + * Create and run the operation for this action. By default, the operation is created + * by calling <code>getSubscriberOperation</code> and then run. Subclasses may + * override. + * + * @throws InvocationTargetException + * @throws InterruptedException + * @since 3.1 + */ + protected void runOperation() throws InvocationTargetException, InterruptedException { + getSubscriberOperation(configuration, getFilteredDiffElements()).run(); + } /** * Return whether dirty editor should be saved before this action is run. diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizePageActionGroup.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizePageActionGroup.java index db5754927..2f54bc694 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizePageActionGroup.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/ui/synchronize/SynchronizePageActionGroup.java @@ -379,7 +379,7 @@ public abstract class SynchronizePageActionGroup extends ActionGroup { * * @since 3.1 */ - public ISynchronizePageConfiguration getConfiguration() { - return configuration; - } + public ISynchronizePageConfiguration getConfiguration() { + return configuration; + } } diff --git a/bundles/org.eclipse.ui.net/META-INF/MANIFEST.MF b/bundles/org.eclipse.ui.net/META-INF/MANIFEST.MF index d3415fe58..5a7089344 100644 --- a/bundles/org.eclipse.ui.net/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.ui.net/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %PLUGIN_NAME Bundle-SymbolicName: org.eclipse.ui.net; singleton:=true -Bundle-Version: 1.3.300.qualifier +Bundle-Version: 1.3.400.qualifier Bundle-Activator: org.eclipse.ui.internal.net.Activator Bundle-Vendor: %PLUGIN_PROVIDER Bundle-Localization: plugin diff --git a/bundles/org.eclipse.ui.net/pom.xml b/bundles/org.eclipse.ui.net/pom.xml index 8cbcc90c2..1fe620f46 100644 --- a/bundles/org.eclipse.ui.net/pom.xml +++ b/bundles/org.eclipse.ui.net/pom.xml @@ -19,6 +19,6 @@ </parent> <groupId>org.eclipse.ui</groupId> <artifactId>org.eclipse.ui.net</artifactId> - <version>1.3.300-SNAPSHOT</version> + <version>1.3.400-SNAPSHOT</version> <packaging>eclipse-plugin</packaging> </project> diff --git a/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/NetAuthenticator.java b/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/NetAuthenticator.java index 9be899e49..e2768a113 100644 --- a/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/NetAuthenticator.java +++ b/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/NetAuthenticator.java @@ -25,8 +25,8 @@ public class NetAuthenticator extends Authenticator { String prompt = getRequestingPrompt(); // realm or message, not documented that can be null // String scheme = getRequestingScheme(); // not documented that can be null - // get the host name from the address since #getRequestingHost - // is not available in the foundation 1.0 class libraries + // get the host name from the address since #getRequestingHost + // is not available in the foundation 1.0 class libraries String hostString = null; if (address != null) { hostString = address.getHostName(); diff --git a/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/UserValidationDialog.java b/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/UserValidationDialog.java index 1e84ad930..6746e875a 100644 --- a/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/UserValidationDialog.java +++ b/bundles/org.eclipse.ui.net/src/org/eclipse/ui/internal/net/auth/UserValidationDialog.java @@ -122,7 +122,7 @@ public class UserValidationDialog extends Dialog { createUsernameFields(main); createPasswordFields(main); - PlatformUI.getWorkbench().getHelpSystem().setHelp(main, + PlatformUI.getWorkbench().getHelpSystem().setHelp(main, "org.eclipse.update.ui.UserValidationDialog"); //$NON-NLS-1$ return main; } diff --git a/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/AbstractMatching.java b/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/AbstractMatching.java index 30fdfb540..032330665 100644 --- a/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/AbstractMatching.java +++ b/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/AbstractMatching.java @@ -94,9 +94,9 @@ public abstract class AbstractMatching { } /* for testing */ - public Vector getMatches() { - return fMatches; - } + public Vector getMatches() { + return fMatches; + } protected class XMLComparator implements IRangeComparator { diff --git a/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLCompareAddIdMapDialog.java b/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLCompareAddIdMapDialog.java index 13957c590..a11a2f48f 100644 --- a/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLCompareAddIdMapDialog.java +++ b/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLCompareAddIdMapDialog.java @@ -112,7 +112,7 @@ public class XMLCompareAddIdMapDialog extends StatusDialog { status.setError(XMLCompareMessages.XMLCompareAddIdMapDialog_error_invalidname); else if ( (!fEdit && (fIdMaps.containsKey(newText) || fIdMapsInternal.containsKey(newText)) ) || (fEdit && !newText.equals(fIdMap.getName()) && (fIdMaps.containsKey(newText) || fIdMapsInternal.containsKey(newText)) ) - ) + ) status.setError(XMLCompareMessages.XMLCompareAddIdMapDialog_error_idmapExists); newText= fIdMapExtText.getText().toLowerCase(); if (newText.length() > 0) { diff --git a/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLStructureCreator.java b/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLStructureCreator.java index 5318bbd4b..f78e35de7 100644 --- a/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLStructureCreator.java +++ b/examples/org.eclipse.compare.examples.xml/src/org/eclipse/compare/examples/xml/XMLStructureCreator.java @@ -58,600 +58,600 @@ import org.eclipse.compare.structuremergeviewer.IStructureCreator; */ public class XMLStructureCreator implements IStructureCreator { - protected static final boolean DEBUG_MODE= false; - - public static final String DEFAULT_NAME= XMLCompareMessages.XMLStructureCreator_pluginname; - - public static final String USE_UNORDERED= XMLCompareMessages.XMLStructureCreator_unordered; - public static final String USE_ORDERED= XMLCompareMessages.XMLStructureCreator_ordered; - public static final String DEFAULT_IDMAP= USE_ORDERED; - - public static final String TYPE_ELEMENT= "element"; //$NON-NLS-1$ - public static final String TYPE_TEXT= "text"; //$NON-NLS-1$ - public static final String TYPE_ATTRIBUTE= "attribute"; //$NON-NLS-1$ - - // for signatures - public static final String ROOT_ID= "root"; //$NON-NLS-1$ - public static final char SIGN_SEPARATOR= '>';//'.' - public static final char SIGN_ENCLOSING= '$'; - public static final String SIGN_ELEMENT= SIGN_ENCLOSING + TYPE_ELEMENT + SIGN_ENCLOSING; - public static final String SIGN_TEXT= SIGN_ENCLOSING + TYPE_TEXT + SIGN_ENCLOSING; - public static final String SIGN_ATTRIBUTE= SIGN_ENCLOSING + TYPE_ATTRIBUTE + SIGN_ENCLOSING; - - public static final String IDMAP_UNORDERED= XMLCompareMessages.XMLStructureCreator_idmap_unordered; - public static final char ID_SEPARATOR= '<'; - public static final char ID_TYPE_BODY= '<'; - - private XMLNode fcurrentParent; - private String fsignature; - private Document fdoc; - private boolean ignoreBodies= false; - private HashMap fIdMapsInternal; - private HashMap fIdMaps; - private HashMap fIdExtensionToName; - private HashMap fOrderedElementsInternal; - private HashMap fOrderedElements; - private HashMap idMap; - private ArrayList fOrdered; - private String fIdMapToUse; - private boolean fUseIdMap; - private String fFileExt; - private boolean fFirstCall= true; - private boolean fRemoveWhiteSpace; - - protected class XMLHandler extends DefaultHandler { - - protected Locator prevlocator; //previous locator - protected Locator locator; //current locator - - @Override + protected static final boolean DEBUG_MODE= false; + + public static final String DEFAULT_NAME= XMLCompareMessages.XMLStructureCreator_pluginname; + + public static final String USE_UNORDERED= XMLCompareMessages.XMLStructureCreator_unordered; + public static final String USE_ORDERED= XMLCompareMessages.XMLStructureCreator_ordered; + public static final String DEFAULT_IDMAP= USE_ORDERED; + + public static final String TYPE_ELEMENT= "element"; //$NON-NLS-1$ + public static final String TYPE_TEXT= "text"; //$NON-NLS-1$ + public static final String TYPE_ATTRIBUTE= "attribute"; //$NON-NLS-1$ + + // for signatures + public static final String ROOT_ID= "root"; //$NON-NLS-1$ + public static final char SIGN_SEPARATOR= '>';//'.' + public static final char SIGN_ENCLOSING= '$'; + public static final String SIGN_ELEMENT= SIGN_ENCLOSING + TYPE_ELEMENT + SIGN_ENCLOSING; + public static final String SIGN_TEXT= SIGN_ENCLOSING + TYPE_TEXT + SIGN_ENCLOSING; + public static final String SIGN_ATTRIBUTE= SIGN_ENCLOSING + TYPE_ATTRIBUTE + SIGN_ENCLOSING; + + public static final String IDMAP_UNORDERED= XMLCompareMessages.XMLStructureCreator_idmap_unordered; + public static final char ID_SEPARATOR= '<'; + public static final char ID_TYPE_BODY= '<'; + + private XMLNode fcurrentParent; + private String fsignature; + private Document fdoc; + private boolean ignoreBodies= false; + private HashMap fIdMapsInternal; + private HashMap fIdMaps; + private HashMap fIdExtensionToName; + private HashMap fOrderedElementsInternal; + private HashMap fOrderedElements; + private HashMap idMap; + private ArrayList fOrdered; + private String fIdMapToUse; + private boolean fUseIdMap; + private String fFileExt; + private boolean fFirstCall= true; + private boolean fRemoveWhiteSpace; + + protected class XMLHandler extends DefaultHandler { + + protected Locator prevlocator; //previous locator + protected Locator locator; //current locator + + @Override public void setDocumentLocator(Locator locator0) { - this.locator= locator0; - } + this.locator= locator0; + } - // DocumentHandler methods - - /* Processing instruction. */ - @Override + // DocumentHandler methods + + /* Processing instruction. */ + @Override public void processingInstruction(String target, String data) { - // System.out.println("target: " + target); - // System.out.println("data: " + data); - // System.out.print("<?"); - // System.out.print(target); - // if (data != null && data.length() > 0) { - // System.out.print(' '); - // System.out.print(data); - // } - // System.out.print("?>"); - // System.out.flush(); - prevlocator= new LocatorImpl(locator); - } - - /** Start document. */ - @Override + // System.out.println("target: " + target); + // System.out.println("data: " + data); + // System.out.print("<?"); + // System.out.print(target); + // if (data != null && data.length() > 0) { + // System.out.print(' '); + // System.out.print(data); + // } + // System.out.print("?>"); + // System.out.flush(); + prevlocator= new LocatorImpl(locator); + } + + /** Start document. */ + @Override public void startDocument() { - prevlocator= new LocatorImpl(locator); - } + prevlocator= new LocatorImpl(locator); + } - /* Start element. */ - @Override + /* Start element. */ + @Override public void startElement(String uri, String local, String raw, Attributes attrs) { - XMLNode currentElement; - - /* add root node for this element */ - - if (XMLStructureCreator.DEBUG_MODE) { - if (locator != null && prevlocator != null) { - System.out.println("prevlocator: line " + prevlocator.getLineNumber() + " column " + prevlocator.getColumnNumber() + " id " + prevlocator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - System.out.println("locator: line " + locator.getLineNumber() + " column " + locator.getColumnNumber() + " id " + locator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - } - } - - try { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Node where children field accessed: " + fcurrentParent.getId()); //$NON-NLS-1$ - XMLChildren currentParent= (XMLChildren) fcurrentParent; - currentParent.children++; - String elementId; - String elementName; - IRegion r= fdoc.getLineInformation(prevlocator.getLineNumber() - 1); - - String parentSig= fsignature; - fsignature= fsignature + raw + SIGN_SEPARATOR; - - if (isUseIdMap() && idMap.containsKey(fsignature)) { - String attrName= (String) idMap.get(fsignature); - elementId= raw + Character.valueOf(ID_SEPARATOR) + attrs.getValue(attrName); - elementName= raw + " [" + attrName + "=" + attrs.getValue(attrName) + "]"; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - } else { - if (!currentParent.childElements.containsKey(raw)) { - currentParent.childElements.put(raw, Integer.valueOf(1)); - } else { - currentParent.childElements.put(raw, Integer.valueOf(currentParent.childElements.get(raw).intValue() + 1)); - } - elementId= raw + Character.valueOf(ID_SEPARATOR) + "[" + currentParent.childElements.get(raw) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ - elementName= MessageFormat.format("{0} [{1}]", raw, currentParent.childElements.get(raw).toString()); //$NON-NLS-1$ - } - int start= r.getOffset() + prevlocator.getColumnNumber() - 1; - if (start < 0) - start= 0; - currentElement= new XMLChildren(TYPE_ELEMENT, elementId, elementId, (fsignature + SIGN_ELEMENT), fdoc, start, 0); - currentElement.setName(elementName); - if (isUseIdMap() && idMap.containsKey(fsignature)) - currentElement.setUsesIDMAP(true); - if (fOrdered != null && fOrdered.contains(parentSig)) - currentElement.setIsOrderedChild(true); - - fcurrentParent.addChild(currentElement); - currentElement.setParent(fcurrentParent); - fcurrentParent= currentElement; - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("\nAdded Element " + raw + " with offset " + r.getOffset()); //$NON-NLS-2$ //$NON-NLS-1$ - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("fcurrentParent1: " + fcurrentParent.getId()); //$NON-NLS-1$ - - if (attrs != null) { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("attrs != null, fcurrentParent is " + fcurrentParent.getId()); //$NON-NLS-1$ - //attrs = sortAttributes(attrs); - int len= attrs.getLength(); - int element_lines_length_size; - int[] element_lines_length; - int column_offset; - String element_string; - if (fcurrentParent.getParent().getId().equals(ROOT_ID)) { - element_lines_length_size= locator.getLineNumber() - prevlocator.getLineNumber(); - element_lines_length= new int[element_lines_length_size]; - column_offset= 0; - element_string= ""; //$NON-NLS-1$ - for (int i_ell= 0; i_ell < element_lines_length.length; i_ell++) { - IRegion attr_r= fdoc.getLineInformation(i_ell + prevlocator.getLineNumber()); - element_lines_length[i_ell]= fdoc.get(attr_r.getOffset(), attr_r.getLength()).length() + 1; - element_string= element_string + fdoc.get(attr_r.getOffset(), attr_r.getLength()) + " "; //$NON-NLS-1$ - } - } else { - element_lines_length_size= locator.getLineNumber() - prevlocator.getLineNumber() + 1; - //if (element_lines_length_size < 1) - // element_lines_length_size = 1; - element_lines_length= new int[element_lines_length_size]; - IRegion first_line= fdoc.getLineInformation(prevlocator.getLineNumber() - 1); - column_offset= prevlocator.getColumnNumber() - 1; - int first_line_relevant_offset= first_line.getOffset() + column_offset; - int first_line_relevant_length= first_line.getLength() - column_offset; - element_string= fdoc.get(first_line_relevant_offset, first_line_relevant_length) + " "; //$NON-NLS-1$ - element_lines_length[0]= element_string.length(); - for (int i_ell= 1; i_ell < element_lines_length.length; i_ell++) { - IRegion attr_r= fdoc.getLineInformation(i_ell + prevlocator.getLineNumber() - 1); - element_lines_length[i_ell]= fdoc.get(attr_r.getOffset(), attr_r.getLength()).length() + 1; - element_string= element_string + fdoc.get(attr_r.getOffset(), attr_r.getLength()) + " "; //$NON-NLS-1$ - } - } - - for (int i_attr= 0; i_attr < len; i_attr++) { - String attr_name= attrs.getQName(i_attr); - String attr_value= attrs.getValue(i_attr); - - /* - * find range of attribute in doc; manually parses the - * line - */ - boolean found= false; - int first_quotes= -1; - int second_quotes= -1; - int id_index= -1; - while (!found) { - first_quotes= element_string.indexOf("\"", second_quotes + 1); //$NON-NLS-1$ - second_quotes= element_string.indexOf("\"", first_quotes + 1); //$NON-NLS-1$ - String value; - try { - value= element_string.substring(first_quotes + 1, second_quotes); - } catch (Exception e) { - value= ""; //$NON-NLS-1$ - } - if (value.equals("")) //$NON-NLS-1$ - found= true; - else if (value.equals(attr_value)) { - id_index= element_string.lastIndexOf(attr_name, first_quotes - 1); - boolean wrong= false; - boolean found_equal= false; - for (int i_char= id_index + attr_name.length(); i_char < first_quotes && !wrong; i_char++) { - if (element_string.charAt(i_char) == '=') - if (!found_equal) - found_equal= true; - else - wrong= true; - else if (!Character.isWhitespace(element_string.charAt(i_char))) - wrong= true; - } - if (!wrong) - found= true; - } - } - //id_index has one char missing for every line (the - // final cr) - int line_of_index= 0; - for (line_of_index= 0; id_index > element_lines_length[line_of_index] - 1; line_of_index++) - id_index-= (element_lines_length[line_of_index]); - if (line_of_index == 0) - id_index+= column_offset; - if (fcurrentParent.getParent().getId().equals(ROOT_ID)) - line_of_index+= prevlocator.getLineNumber(); - else - line_of_index+= prevlocator.getLineNumber() - 1; - //index at line line_of_index, line offset id_index - int line_of_end_of_value= 0; - int end_of_value_index= second_quotes; - for (line_of_end_of_value= 0; end_of_value_index > element_lines_length[line_of_end_of_value] - 1; line_of_end_of_value++) - end_of_value_index-= (element_lines_length[line_of_end_of_value]); - if (line_of_end_of_value == 0) - end_of_value_index+= column_offset; - if (fcurrentParent.getParent().getId().equals(ROOT_ID)) - line_of_end_of_value+= prevlocator.getLineNumber(); - else - line_of_end_of_value+= prevlocator.getLineNumber() - 1; - //end of value at line line_of_end_of_value, line - // offset end_of_value_index - - int attr_start_doc_offset= fdoc.getLineInformation(line_of_index).getOffset() + id_index; - //int attr_length_doc_offset = - // fdoc.getLineInformation(line_of_value).getOffset()+value_index+attr_value.length()+1+(line_of_end_of_value-line_of_index) - // - attr_start_doc_offset; - int attr_length_doc_offset= fdoc.getLineInformation(line_of_end_of_value).getOffset() + end_of_value_index + 1 - attr_start_doc_offset; - currentElement= new XMLNode(TYPE_ATTRIBUTE, attr_name, attr_value, (fsignature + attr_name + SIGN_SEPARATOR + SIGN_ATTRIBUTE), fdoc, attr_start_doc_offset, attr_length_doc_offset); - currentElement.setName(attr_name); - fcurrentParent.addChild(currentElement); - currentElement.setParent(fcurrentParent); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("added attribute " + currentElement.getId() + " with value >" + currentElement.getValue() + "<" + " to element " + fcurrentParent.getId() + " which has parent " + fcurrentParent.getParent().getId()); //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - } - } - } catch (BadLocationException ex) { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("BadLocationException in startElement(...) " + ex); //$NON-NLS-1$ - currentElement= new XMLChildren(TYPE_ELEMENT, raw + "_(" + ((XMLChildren) fcurrentParent).children + ")", raw + "_(" + ((XMLChildren) fcurrentParent).children + ")", (fsignature + SIGN_ELEMENT), fdoc, 0, 0); //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - } - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("At the end of startElement(...), fcurrentParent is " + fcurrentParent.getId()); //$NON-NLS-1$ - prevlocator= new LocatorImpl(locator); - } - - /* Characters. */ - @Override + XMLNode currentElement; + + /* add root node for this element */ + + if (XMLStructureCreator.DEBUG_MODE) { + if (locator != null && prevlocator != null) { + System.out.println("prevlocator: line " + prevlocator.getLineNumber() + " column " + prevlocator.getColumnNumber() + " id " + prevlocator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + System.out.println("locator: line " + locator.getLineNumber() + " column " + locator.getColumnNumber() + " id " + locator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + } + } + + try { + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Node where children field accessed: " + fcurrentParent.getId()); //$NON-NLS-1$ + XMLChildren currentParent= (XMLChildren) fcurrentParent; + currentParent.children++; + String elementId; + String elementName; + IRegion r= fdoc.getLineInformation(prevlocator.getLineNumber() - 1); + + String parentSig= fsignature; + fsignature= fsignature + raw + SIGN_SEPARATOR; + + if (isUseIdMap() && idMap.containsKey(fsignature)) { + String attrName= (String) idMap.get(fsignature); + elementId= raw + Character.valueOf(ID_SEPARATOR) + attrs.getValue(attrName); + elementName= raw + " [" + attrName + "=" + attrs.getValue(attrName) + "]"; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + } else { + if (!currentParent.childElements.containsKey(raw)) { + currentParent.childElements.put(raw, Integer.valueOf(1)); + } else { + currentParent.childElements.put(raw, Integer.valueOf(currentParent.childElements.get(raw).intValue() + 1)); + } + elementId= raw + Character.valueOf(ID_SEPARATOR) + "[" + currentParent.childElements.get(raw) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ + elementName= MessageFormat.format("{0} [{1}]", raw, currentParent.childElements.get(raw).toString()); //$NON-NLS-1$ + } + int start= r.getOffset() + prevlocator.getColumnNumber() - 1; + if (start < 0) + start= 0; + currentElement= new XMLChildren(TYPE_ELEMENT, elementId, elementId, (fsignature + SIGN_ELEMENT), fdoc, start, 0); + currentElement.setName(elementName); + if (isUseIdMap() && idMap.containsKey(fsignature)) + currentElement.setUsesIDMAP(true); + if (fOrdered != null && fOrdered.contains(parentSig)) + currentElement.setIsOrderedChild(true); + + fcurrentParent.addChild(currentElement); + currentElement.setParent(fcurrentParent); + fcurrentParent= currentElement; + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("\nAdded Element " + raw + " with offset " + r.getOffset()); //$NON-NLS-2$ //$NON-NLS-1$ + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("fcurrentParent1: " + fcurrentParent.getId()); //$NON-NLS-1$ + + if (attrs != null) { + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("attrs != null, fcurrentParent is " + fcurrentParent.getId()); //$NON-NLS-1$ + //attrs = sortAttributes(attrs); + int len= attrs.getLength(); + int element_lines_length_size; + int[] element_lines_length; + int column_offset; + String element_string; + if (fcurrentParent.getParent().getId().equals(ROOT_ID)) { + element_lines_length_size= locator.getLineNumber() - prevlocator.getLineNumber(); + element_lines_length= new int[element_lines_length_size]; + column_offset= 0; + element_string= ""; //$NON-NLS-1$ + for (int i_ell= 0; i_ell < element_lines_length.length; i_ell++) { + IRegion attr_r= fdoc.getLineInformation(i_ell + prevlocator.getLineNumber()); + element_lines_length[i_ell]= fdoc.get(attr_r.getOffset(), attr_r.getLength()).length() + 1; + element_string= element_string + fdoc.get(attr_r.getOffset(), attr_r.getLength()) + " "; //$NON-NLS-1$ + } + } else { + element_lines_length_size= locator.getLineNumber() - prevlocator.getLineNumber() + 1; + //if (element_lines_length_size < 1) + // element_lines_length_size = 1; + element_lines_length= new int[element_lines_length_size]; + IRegion first_line= fdoc.getLineInformation(prevlocator.getLineNumber() - 1); + column_offset= prevlocator.getColumnNumber() - 1; + int first_line_relevant_offset= first_line.getOffset() + column_offset; + int first_line_relevant_length= first_line.getLength() - column_offset; + element_string= fdoc.get(first_line_relevant_offset, first_line_relevant_length) + " "; //$NON-NLS-1$ + element_lines_length[0]= element_string.length(); + for (int i_ell= 1; i_ell < element_lines_length.length; i_ell++) { + IRegion attr_r= fdoc.getLineInformation(i_ell + prevlocator.getLineNumber() - 1); + element_lines_length[i_ell]= fdoc.get(attr_r.getOffset(), attr_r.getLength()).length() + 1; + element_string= element_string + fdoc.get(attr_r.getOffset(), attr_r.getLength()) + " "; //$NON-NLS-1$ + } + } + + for (int i_attr= 0; i_attr < len; i_attr++) { + String attr_name= attrs.getQName(i_attr); + String attr_value= attrs.getValue(i_attr); + + /* + * find range of attribute in doc; manually parses the + * line + */ + boolean found= false; + int first_quotes= -1; + int second_quotes= -1; + int id_index= -1; + while (!found) { + first_quotes= element_string.indexOf("\"", second_quotes + 1); //$NON-NLS-1$ + second_quotes= element_string.indexOf("\"", first_quotes + 1); //$NON-NLS-1$ + String value; + try { + value= element_string.substring(first_quotes + 1, second_quotes); + } catch (Exception e) { + value= ""; //$NON-NLS-1$ + } + if (value.equals("")) //$NON-NLS-1$ + found= true; + else if (value.equals(attr_value)) { + id_index= element_string.lastIndexOf(attr_name, first_quotes - 1); + boolean wrong= false; + boolean found_equal= false; + for (int i_char= id_index + attr_name.length(); i_char < first_quotes && !wrong; i_char++) { + if (element_string.charAt(i_char) == '=') + if (!found_equal) + found_equal= true; + else + wrong= true; + else if (!Character.isWhitespace(element_string.charAt(i_char))) + wrong= true; + } + if (!wrong) + found= true; + } + } + //id_index has one char missing for every line (the + // final cr) + int line_of_index= 0; + for (line_of_index= 0; id_index > element_lines_length[line_of_index] - 1; line_of_index++) + id_index-= (element_lines_length[line_of_index]); + if (line_of_index == 0) + id_index+= column_offset; + if (fcurrentParent.getParent().getId().equals(ROOT_ID)) + line_of_index+= prevlocator.getLineNumber(); + else + line_of_index+= prevlocator.getLineNumber() - 1; + //index at line line_of_index, line offset id_index + int line_of_end_of_value= 0; + int end_of_value_index= second_quotes; + for (line_of_end_of_value= 0; end_of_value_index > element_lines_length[line_of_end_of_value] - 1; line_of_end_of_value++) + end_of_value_index-= (element_lines_length[line_of_end_of_value]); + if (line_of_end_of_value == 0) + end_of_value_index+= column_offset; + if (fcurrentParent.getParent().getId().equals(ROOT_ID)) + line_of_end_of_value+= prevlocator.getLineNumber(); + else + line_of_end_of_value+= prevlocator.getLineNumber() - 1; + //end of value at line line_of_end_of_value, line + // offset end_of_value_index + + int attr_start_doc_offset= fdoc.getLineInformation(line_of_index).getOffset() + id_index; + //int attr_length_doc_offset = + // fdoc.getLineInformation(line_of_value).getOffset()+value_index+attr_value.length()+1+(line_of_end_of_value-line_of_index) + // - attr_start_doc_offset; + int attr_length_doc_offset= fdoc.getLineInformation(line_of_end_of_value).getOffset() + end_of_value_index + 1 - attr_start_doc_offset; + currentElement= new XMLNode(TYPE_ATTRIBUTE, attr_name, attr_value, (fsignature + attr_name + SIGN_SEPARATOR + SIGN_ATTRIBUTE), fdoc, attr_start_doc_offset, attr_length_doc_offset); + currentElement.setName(attr_name); + fcurrentParent.addChild(currentElement); + currentElement.setParent(fcurrentParent); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("added attribute " + currentElement.getId() + " with value >" + currentElement.getValue() + "<" + " to element " + fcurrentParent.getId() + " which has parent " + fcurrentParent.getParent().getId()); //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + } + } + } catch (BadLocationException ex) { + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("BadLocationException in startElement(...) " + ex); //$NON-NLS-1$ + currentElement= new XMLChildren(TYPE_ELEMENT, raw + "_(" + ((XMLChildren) fcurrentParent).children + ")", raw + "_(" + ((XMLChildren) fcurrentParent).children + ")", (fsignature + SIGN_ELEMENT), fdoc, 0, 0); //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + } + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("At the end of startElement(...), fcurrentParent is " + fcurrentParent.getId()); //$NON-NLS-1$ + prevlocator= new LocatorImpl(locator); + } + + /* Characters. */ + @Override public void characters(char ch[], int start, int length) { - if (!ignoreBodies) { - // String chars = (new String(ch, start, length)).trim(); - String chars= new String(ch, start, length); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("characters: >" + chars + "<"); //$NON-NLS-2$ //$NON-NLS-1$ - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Body Location: line " + locator.getLineNumber() + " column " + locator.getColumnNumber()); //$NON-NLS-2$ //$NON-NLS-1$ - - //if text contains only white space, it will be ignored. - if (!trimWhiteSpace(chars).equals("")) { //$NON-NLS-1$ - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Adding body"); //$NON-NLS-1$ - try { - IRegion r= fdoc.getLineInformation(locator.getLineNumber() - 1); - //location returns the END of the characters - //offset of BEGINNING of characters: - int offset= r.getOffset() + locator.getColumnNumber() - 1 - length; - fcurrentParent.bodies++; - String body_value= new String(ch, start, length); - if (fRemoveWhiteSpace) { - body_value= removeWhiteSpace(body_value); - } - XMLNode bodynode= new XMLNode(TYPE_TEXT, "body_(" + fcurrentParent.bodies + ")", body_value, (fsignature + SIGN_TEXT), fdoc, offset, length); //$NON-NLS-2$ //$NON-NLS-1$ - bodynode.setName(MessageFormat.format("{0} ({1})", XMLCompareMessages.XMLStructureCreator_body, Integer.toString(fcurrentParent.bodies))); //$NON-NLS-1$ - fcurrentParent.addChild(bodynode); - bodynode.setParent(fcurrentParent); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Created body " + fcurrentParent.bodies //$NON-NLS-1$ - + " with offset " + offset + " and length " + length //$NON-NLS-2$ //$NON-NLS-1$ - + " with parent " + bodynode.getParent().getId()); //$NON-NLS-1$ - //bodies as id attributes - String popsig= fcurrentParent.getParent().getSignature(); //signature of parent of - // parent - popsig= popsig.substring(0, popsig.lastIndexOf(SIGN_ELEMENT)); - if (isUseIdMap() && fcurrentParent.bodies == 1 && idMap.containsKey(popsig)) { - String pid= fcurrentParent.getId();//id of parent - String pelementname= pid.substring(0, pid.indexOf("<")); //name of parent element //$NON-NLS-1$ - if (((String) idMap.get(popsig)).equals(ID_TYPE_BODY + pelementname)) { - XMLNode pop= fcurrentParent.getParent(); - String popid= pop.getId(); - String popelementname= popid.substring(0, popid.indexOf("<")); //$NON-NLS-1$ - pop.setId(popelementname + "<" + body_value); //$NON-NLS-1$ - pop.setOrigId(popelementname + "<" + body_value); //$NON-NLS-1$ - pop.setName(MessageFormat.format("{0} [{1}={2}]", popelementname, pelementname, body_value)); //$NON-NLS-1$ - pop.setUsesIDMAP(true); - } - } - } catch (BadLocationException ex) { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("BadLocationException in characters(...) " + ex); //$NON-NLS-1$ - fcurrentParent.addChild(new XMLNode(TYPE_TEXT, "body_(" + fcurrentParent.bodies + ")", new String(ch, start, length), (fsignature + SIGN_TEXT), fdoc, 0, 0)); //$NON-NLS-2$ //$NON-NLS-1$ - } - } - } - prevlocator= new LocatorImpl(locator); - } - - /* Ignorable whitespace. */ - @Override + if (!ignoreBodies) { + // String chars = (new String(ch, start, length)).trim(); + String chars= new String(ch, start, length); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("characters: >" + chars + "<"); //$NON-NLS-2$ //$NON-NLS-1$ + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Body Location: line " + locator.getLineNumber() + " column " + locator.getColumnNumber()); //$NON-NLS-2$ //$NON-NLS-1$ + + //if text contains only white space, it will be ignored. + if (!trimWhiteSpace(chars).equals("")) { //$NON-NLS-1$ + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Adding body"); //$NON-NLS-1$ + try { + IRegion r= fdoc.getLineInformation(locator.getLineNumber() - 1); + //location returns the END of the characters + //offset of BEGINNING of characters: + int offset= r.getOffset() + locator.getColumnNumber() - 1 - length; + fcurrentParent.bodies++; + String body_value= new String(ch, start, length); + if (fRemoveWhiteSpace) { + body_value= removeWhiteSpace(body_value); + } + XMLNode bodynode= new XMLNode(TYPE_TEXT, "body_(" + fcurrentParent.bodies + ")", body_value, (fsignature + SIGN_TEXT), fdoc, offset, length); //$NON-NLS-2$ //$NON-NLS-1$ + bodynode.setName(MessageFormat.format("{0} ({1})", XMLCompareMessages.XMLStructureCreator_body, Integer.toString(fcurrentParent.bodies))); //$NON-NLS-1$ + fcurrentParent.addChild(bodynode); + bodynode.setParent(fcurrentParent); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Created body " + fcurrentParent.bodies //$NON-NLS-1$ + + " with offset " + offset + " and length " + length //$NON-NLS-2$ //$NON-NLS-1$ + + " with parent " + bodynode.getParent().getId()); //$NON-NLS-1$ + //bodies as id attributes + String popsig= fcurrentParent.getParent().getSignature(); //signature of parent of + // parent + popsig= popsig.substring(0, popsig.lastIndexOf(SIGN_ELEMENT)); + if (isUseIdMap() && fcurrentParent.bodies == 1 && idMap.containsKey(popsig)) { + String pid= fcurrentParent.getId();//id of parent + String pelementname= pid.substring(0, pid.indexOf("<")); //name of parent element //$NON-NLS-1$ + if (((String) idMap.get(popsig)).equals(ID_TYPE_BODY + pelementname)) { + XMLNode pop= fcurrentParent.getParent(); + String popid= pop.getId(); + String popelementname= popid.substring(0, popid.indexOf("<")); //$NON-NLS-1$ + pop.setId(popelementname + "<" + body_value); //$NON-NLS-1$ + pop.setOrigId(popelementname + "<" + body_value); //$NON-NLS-1$ + pop.setName(MessageFormat.format("{0} [{1}={2}]", popelementname, pelementname, body_value)); //$NON-NLS-1$ + pop.setUsesIDMAP(true); + } + } + } catch (BadLocationException ex) { + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("BadLocationException in characters(...) " + ex); //$NON-NLS-1$ + fcurrentParent.addChild(new XMLNode(TYPE_TEXT, "body_(" + fcurrentParent.bodies + ")", new String(ch, start, length), (fsignature + SIGN_TEXT), fdoc, 0, 0)); //$NON-NLS-2$ //$NON-NLS-1$ + } + } + } + prevlocator= new LocatorImpl(locator); + } + + /* Ignorable whitespace. */ + @Override public void ignorableWhitespace(char ch[], int start, int length) { - // - //// characters(ch, start, length); - //// System.out.flush(); - // - prevlocator= new LocatorImpl(locator); - } - - /* End element. */ - @Override + // + //// characters(ch, start, length); + //// System.out.flush(); + // + prevlocator= new LocatorImpl(locator); + } + + /* End element. */ + @Override public void endElement(String uri, String local, String raw) { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("\nExiting element " + fcurrentParent.getId()); //$NON-NLS-1$ - - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("prevlocator: line " + prevlocator.getLineNumber() + " column " + prevlocator.getColumnNumber() + " id " + prevlocator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("locator: line " + locator.getLineNumber() + " column " + locator.getColumnNumber() + " id " + locator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - - if (fcurrentParent.getParent() != null) { - try { - IRegion r2= fdoc.getLineInformation(locator.getLineNumber() - 1); - Position pos= fcurrentParent.getRange(); - - int elem_length= r2.getOffset() + locator.getColumnNumber() - 1 - pos.getOffset();//length of element from - // start tag to end tag - fcurrentParent.setLength(elem_length); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("pos.getOffset: " + pos.getOffset() + " elem_length: " + elem_length); //$NON-NLS-2$ //$NON-NLS-1$ - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("fdoc.get(pos.getOffset()+elem_length-5,4): >" + fdoc.get(pos.getOffset() + elem_length - 5, 4) + "<"); //$NON-NLS-2$ //$NON-NLS-1$ - //if (fdoc.get(pos.getOffset()+elem_length-2,1) != ">") - // elem_length-=1; - try { - fcurrentParent.setValue(fdoc.get(pos.getOffset(), elem_length)); - } catch (BadLocationException ex) { - try { - fcurrentParent.setValue(fdoc.get(pos.getOffset(), elem_length - 1)); - } catch (BadLocationException ex2) { - if (XMLStructureCreator.DEBUG_MODE) { - System.out.println("BadLocationException in endElement(...) while attempting fcurrentParent.setValue(...): " + ex); //$NON-NLS-1$ - System.out.println("Attempt to correct BadLocationException failed: " + ex2); //$NON-NLS-1$ - } - } - } - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Value of " + fcurrentParent.getId() + " is >" + fcurrentParent.getValue() + "<"); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - - //going from ending element to parent element - fcurrentParent= fcurrentParent.getParent(); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("fcurrentParent = fcurrentParent.getParent();"); //$NON-NLS-1$ - } catch (BadLocationException ex) { - if (XMLStructureCreator.DEBUG_MODE) { - System.out.println("BadLocationException in endElement(...): " + ex); //$NON-NLS-1$ - System.out.println("fcurrentParent.getId(): " + fcurrentParent.getId()); //$NON-NLS-1$ - } - } - } else { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Error: Cannot reach Parent of Parent"); //$NON-NLS-1$ - } - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("fcurrentParent is now " + fcurrentParent.getId()); //$NON-NLS-1$ - - prevlocator= new LocatorImpl(locator); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Signature before cutting: " + fsignature); //$NON-NLS-1$ - int ssi= fsignature.lastIndexOf(SIGN_SEPARATOR);//fsignature - // separator index - ssi= fsignature.lastIndexOf(SIGN_SEPARATOR, ssi - 1);//second-last - // ".", e.g. in - // root.a.b. to - // obtain - // root.a. - fsignature= fsignature.substring(0, ssi + 1); - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Signature after cutting: " + fsignature); //$NON-NLS-1$ - } - - // - // ErrorHandler methods - // - - /* Warning. */ - @Override + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("\nExiting element " + fcurrentParent.getId()); //$NON-NLS-1$ + + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("prevlocator: line " + prevlocator.getLineNumber() + " column " + prevlocator.getColumnNumber() + " id " + prevlocator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("locator: line " + locator.getLineNumber() + " column " + locator.getColumnNumber() + " id " + locator.getPublicId()); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + + if (fcurrentParent.getParent() != null) { + try { + IRegion r2= fdoc.getLineInformation(locator.getLineNumber() - 1); + Position pos= fcurrentParent.getRange(); + + int elem_length= r2.getOffset() + locator.getColumnNumber() - 1 - pos.getOffset();//length of element from + // start tag to end tag + fcurrentParent.setLength(elem_length); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("pos.getOffset: " + pos.getOffset() + " elem_length: " + elem_length); //$NON-NLS-2$ //$NON-NLS-1$ + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("fdoc.get(pos.getOffset()+elem_length-5,4): >" + fdoc.get(pos.getOffset() + elem_length - 5, 4) + "<"); //$NON-NLS-2$ //$NON-NLS-1$ + //if (fdoc.get(pos.getOffset()+elem_length-2,1) != ">") + // elem_length-=1; + try { + fcurrentParent.setValue(fdoc.get(pos.getOffset(), elem_length)); + } catch (BadLocationException ex) { + try { + fcurrentParent.setValue(fdoc.get(pos.getOffset(), elem_length - 1)); + } catch (BadLocationException ex2) { + if (XMLStructureCreator.DEBUG_MODE) { + System.out.println("BadLocationException in endElement(...) while attempting fcurrentParent.setValue(...): " + ex); //$NON-NLS-1$ + System.out.println("Attempt to correct BadLocationException failed: " + ex2); //$NON-NLS-1$ + } + } + } + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Value of " + fcurrentParent.getId() + " is >" + fcurrentParent.getValue() + "<"); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + + //going from ending element to parent element + fcurrentParent= fcurrentParent.getParent(); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("fcurrentParent = fcurrentParent.getParent();"); //$NON-NLS-1$ + } catch (BadLocationException ex) { + if (XMLStructureCreator.DEBUG_MODE) { + System.out.println("BadLocationException in endElement(...): " + ex); //$NON-NLS-1$ + System.out.println("fcurrentParent.getId(): " + fcurrentParent.getId()); //$NON-NLS-1$ + } + } + } else { + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Error: Cannot reach Parent of Parent"); //$NON-NLS-1$ + } + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("fcurrentParent is now " + fcurrentParent.getId()); //$NON-NLS-1$ + + prevlocator= new LocatorImpl(locator); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Signature before cutting: " + fsignature); //$NON-NLS-1$ + int ssi= fsignature.lastIndexOf(SIGN_SEPARATOR);//fsignature + // separator index + ssi= fsignature.lastIndexOf(SIGN_SEPARATOR, ssi - 1);//second-last + // ".", e.g. in + // root.a.b. to + // obtain + // root.a. + fsignature= fsignature.substring(0, ssi + 1); + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Signature after cutting: " + fsignature); //$NON-NLS-1$ + } + + // + // ErrorHandler methods + // + + /* Warning. */ + @Override public void warning(SAXParseException ex) { - System.err.println("[Warning] " + //$NON-NLS-1$ - getLocationString(ex) + ": " + //$NON-NLS-1$ - ex.getMessage()); - } + System.err.println("[Warning] " + //$NON-NLS-1$ + getLocationString(ex) + ": " + //$NON-NLS-1$ + ex.getMessage()); + } - /* Error. */ - @Override + /* Error. */ + @Override public void error(SAXParseException ex) { - System.err.println("[Error] " + //$NON-NLS-1$ - getLocationString(ex) + ": " + //$NON-NLS-1$ - ex.getMessage()); - } + System.err.println("[Error] " + //$NON-NLS-1$ + getLocationString(ex) + ": " + //$NON-NLS-1$ + ex.getMessage()); + } - /* Fatal error. */ - @Override + /* Fatal error. */ + @Override public void fatalError(SAXParseException ex) throws SAXException { - System.err.println("[Fatal Error] " + //$NON-NLS-1$ - getLocationString(ex) + ": " + //$NON-NLS-1$ - ex.getMessage()); - //System.out.println(ex); - //throw ex; - } - - /* Returns a string of the location. */ - private String getLocationString(SAXParseException ex) { - StringBuilder str= new StringBuilder(); - - String systemId= ex.getSystemId(); - if (systemId != null) { - int index= systemId.lastIndexOf('/'); - if (index != -1) - systemId= systemId.substring(index + 1); - str.append(systemId); - } - str.append(':'); - str.append(ex.getLineNumber()); - str.append(':'); - str.append(ex.getColumnNumber()); - - return str.toString(); - - } - } - - public XMLStructureCreator() { - //set default idmap - fIdMapToUse= DEFAULT_IDMAP; - fUseIdMap= false; - XMLPlugin plugin= XMLPlugin.getDefault(); - //if statement required for tests - if (plugin != null) { - fIdMaps= plugin.getIdMaps(); - fIdMapsInternal= plugin.getIdMapsInternal(); - fIdExtensionToName= plugin.getIdExtensionToName(); - fOrderedElements= plugin.getOrderedElements(); - fOrderedElementsInternal= plugin.getOrderedElementsInternal(); - } - fRemoveWhiteSpace= false; - } - - /* - * This title will be shown in the title bar of the structure compare pane. - */ - @Override + System.err.println("[Fatal Error] " + //$NON-NLS-1$ + getLocationString(ex) + ": " + //$NON-NLS-1$ + ex.getMessage()); + //System.out.println(ex); + //throw ex; + } + + /* Returns a string of the location. */ + private String getLocationString(SAXParseException ex) { + StringBuilder str= new StringBuilder(); + + String systemId= ex.getSystemId(); + if (systemId != null) { + int index= systemId.lastIndexOf('/'); + if (index != -1) + systemId= systemId.substring(index + 1); + str.append(systemId); + } + str.append(':'); + str.append(ex.getLineNumber()); + str.append(':'); + str.append(ex.getColumnNumber()); + + return str.toString(); + + } + } + + public XMLStructureCreator() { + //set default idmap + fIdMapToUse= DEFAULT_IDMAP; + fUseIdMap= false; + XMLPlugin plugin= XMLPlugin.getDefault(); + //if statement required for tests + if (plugin != null) { + fIdMaps= plugin.getIdMaps(); + fIdMapsInternal= plugin.getIdMapsInternal(); + fIdExtensionToName= plugin.getIdExtensionToName(); + fOrderedElements= plugin.getOrderedElements(); + fOrderedElementsInternal= plugin.getOrderedElementsInternal(); + } + fRemoveWhiteSpace= false; + } + + /* + * This title will be shown in the title bar of the structure compare pane. + */ + @Override public String getName() { - return DEFAULT_NAME; - } - - /* - * Set File extension of the parsed file. This extension will be used to choose an Id Map scheme. - */ - public void setFileExtension(String ext) { - fFileExt= ext; - } - - /** - * Initialize the Id Mappings for the Id Mapping Scheme and the Ordered Elements - * This method must be called before getStructure(Object) is called on the two/three inputs of the compare - */ - public void initIdMaps() { - if (fFirstCall && fFileExt != null) { - fFirstCall= false; - String fileExtLower= fFileExt.toLowerCase(); - if (fIdExtensionToName.containsKey(fileExtLower)) - setIdMap((String) fIdExtensionToName.get(fileExtLower)); - } - - setUseIdMap(); - fOrdered= null; - if (!isUseIdMap()) - idMap= null; - else if (fIdMaps.containsKey(fIdMapToUse)) { - idMap= (HashMap) fIdMaps.get(fIdMapToUse); - } else if (fIdMapsInternal.containsKey(fIdMapToUse)) { - idMap= (HashMap) fIdMapsInternal.get(fIdMapToUse); - } - - if (fOrderedElements != null) - fOrdered= (ArrayList) fOrderedElements.get(fIdMapToUse); - if (fOrdered == null && fOrderedElementsInternal != null) - fOrdered= (ArrayList) fOrderedElementsInternal.get(fIdMapToUse); - } - - /* - * Returns the XML parse tree of the input. - */ - @Override + return DEFAULT_NAME; + } + + /* + * Set File extension of the parsed file. This extension will be used to choose an Id Map scheme. + */ + public void setFileExtension(String ext) { + fFileExt= ext; + } + + /** + * Initialize the Id Mappings for the Id Mapping Scheme and the Ordered Elements + * This method must be called before getStructure(Object) is called on the two/three inputs of the compare + */ + public void initIdMaps() { + if (fFirstCall && fFileExt != null) { + fFirstCall= false; + String fileExtLower= fFileExt.toLowerCase(); + if (fIdExtensionToName.containsKey(fileExtLower)) + setIdMap((String) fIdExtensionToName.get(fileExtLower)); + } + + setUseIdMap(); + fOrdered= null; + if (!isUseIdMap()) + idMap= null; + else if (fIdMaps.containsKey(fIdMapToUse)) { + idMap= (HashMap) fIdMaps.get(fIdMapToUse); + } else if (fIdMapsInternal.containsKey(fIdMapToUse)) { + idMap= (HashMap) fIdMapsInternal.get(fIdMapToUse); + } + + if (fOrderedElements != null) + fOrdered= (ArrayList) fOrderedElements.get(fIdMapToUse); + if (fOrdered == null && fOrderedElementsInternal != null) + fOrdered= (ArrayList) fOrderedElementsInternal.get(fIdMapToUse); + } + + /* + * Returns the XML parse tree of the input. + */ + @Override public IStructureComparator getStructure(Object input) { - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("Starting parse"); //$NON-NLS-1$ - - if (!(input instanceof IStreamContentAccessor)) - return null; - - IStreamContentAccessor sca= (IStreamContentAccessor) input; - - try { - // Input parsed with parser.parse(new InputSource(sca.getContents)); - - String contents= readString(sca); - if (contents == null) - contents= ""; //$NON-NLS-1$ - fdoc= new Document(contents); - - fsignature= ROOT_ID + SIGN_SEPARATOR; - XMLChildren root= new XMLChildren(TYPE_ELEMENT, ROOT_ID, "", (fsignature + SIGN_ELEMENT), fdoc, 0, fdoc.getLength()); //$NON-NLS-1$ - fcurrentParent= root; - - XMLHandler handler= new XMLHandler(); - - try { - // /* original xerces code - // SAXParser parser = (SAXParser)Class.forName(parserName).newInstance(); - // */ - // XMLReader parser = XMLReaderFactory.createXMLReader(parserName); - // - // parser.setFeature( "http://xml.org/sax/features/validation", setValidation); //$NON-NLS-1$ - // parser.setFeature( "http://xml.org/sax/features/namespaces", setNameSpaces ); //$NON-NLS-1$ - // /* - // parser.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$ - // parser.setFeature( "http://apache.org/xml/features/validation/schema", setSchemaSupport ); //$NON-NLS-1$ - // parser.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", setSchemaFullSupport); //$NON-NLS-1$ - // */ - // parser.setContentHandler(handler); - // parser.setErrorHandler(handler); - // - // parser.parse(new InputSource(sca.getContents())); - - SAXParserFactory factory= SAXParserFactory.newInstance(); - factory.setNamespaceAware(true); - SAXParser parser= factory.newSAXParser(); - parser.parse(new InputSource(new StringReader(contents)), handler); - - if (XMLStructureCreator.DEBUG_MODE) - System.out.println("End of parse"); //$NON-NLS-1$ - } catch (SAXParseException e) { - XMLPlugin.log(e); - return null; - } catch (Exception e) { - // MessageDialog.openError(XMLPlugin.getActiveWorkbenchShell(),"Error in XML parser","An error occured in the XML parser.\nNo structured compare can be shown"); - XMLPlugin.log(e); - return null; - } - return root; - } catch (CoreException ex) { - XMLPlugin.log(ex); - } - return null; - } - - public boolean canSave() { - return true; - } - - public boolean canRewriteTree() { - return false; - } - - public void rewriteTree(Differencer differencer, IDiffContainer root) { - // nothing to do - } - - @Override + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("Starting parse"); //$NON-NLS-1$ + + if (!(input instanceof IStreamContentAccessor)) + return null; + + IStreamContentAccessor sca= (IStreamContentAccessor) input; + + try { + // Input parsed with parser.parse(new InputSource(sca.getContents)); + + String contents= readString(sca); + if (contents == null) + contents= ""; //$NON-NLS-1$ + fdoc= new Document(contents); + + fsignature= ROOT_ID + SIGN_SEPARATOR; + XMLChildren root= new XMLChildren(TYPE_ELEMENT, ROOT_ID, "", (fsignature + SIGN_ELEMENT), fdoc, 0, fdoc.getLength()); //$NON-NLS-1$ + fcurrentParent= root; + + XMLHandler handler= new XMLHandler(); + + try { + // /* original xerces code + // SAXParser parser = (SAXParser)Class.forName(parserName).newInstance(); + // */ + // XMLReader parser = XMLReaderFactory.createXMLReader(parserName); + // + // parser.setFeature( "http://xml.org/sax/features/validation", setValidation); //$NON-NLS-1$ + // parser.setFeature( "http://xml.org/sax/features/namespaces", setNameSpaces ); //$NON-NLS-1$ + // /* + // parser.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$ + // parser.setFeature( "http://apache.org/xml/features/validation/schema", setSchemaSupport ); //$NON-NLS-1$ + // parser.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", setSchemaFullSupport); //$NON-NLS-1$ + // */ + // parser.setContentHandler(handler); + // parser.setErrorHandler(handler); + // + // parser.parse(new InputSource(sca.getContents())); + + SAXParserFactory factory= SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + SAXParser parser= factory.newSAXParser(); + parser.parse(new InputSource(new StringReader(contents)), handler); + + if (XMLStructureCreator.DEBUG_MODE) + System.out.println("End of parse"); //$NON-NLS-1$ + } catch (SAXParseException e) { + XMLPlugin.log(e); + return null; + } catch (Exception e) { + // MessageDialog.openError(XMLPlugin.getActiveWorkbenchShell(),"Error in XML parser","An error occured in the XML parser.\nNo structured compare can be shown"); + XMLPlugin.log(e); + return null; + } + return root; + } catch (CoreException ex) { + XMLPlugin.log(ex); + } + return null; + } + + public boolean canSave() { + return true; + } + + public boolean canRewriteTree() { + return false; + } + + public void rewriteTree(Differencer differencer, IDiffContainer root) { + // nothing to do + } + + @Override public void save(IStructureComparator structure, Object input) { - if (input instanceof IEditableContent && structure instanceof XMLNode) { - IDocument document= ((XMLNode) structure).getDocument(); - IEditableContent bca= (IEditableContent) input; + if (input instanceof IEditableContent && structure instanceof XMLNode) { + IDocument document= ((XMLNode) structure).getDocument(); + IEditableContent bca= (IEditableContent) input; String contents= document.get(); String encoding= null; if (input instanceof IEncodedStreamContentAccessor) { @@ -664,162 +664,162 @@ public class XMLStructureCreator implements IStructureCreator { if (encoding == null) encoding= "UTF-8"; //$NON-NLS-1$ try { - bca.setContent(contents.getBytes(encoding)); + bca.setContent(contents.getBytes(encoding)); } catch (UnsupportedEncodingException e) { - bca.setContent(contents.getBytes()); + bca.setContent(contents.getBytes()); } } } - @Override + @Override public String getContents(Object node, boolean ignoreWhitespace) { - if (node instanceof XMLNode) { - String s= ((XMLNode) node).getValue(); - if (ignoreWhitespace) - s= s.trim(); - return s; - } - return null; - } - - @Override + if (node instanceof XMLNode) { + String s= ((XMLNode) node).getValue(); + if (ignoreWhitespace) + s= s.trim(); + return s; + } + return null; + } + + @Override public IStructureComparator locate(Object path, Object source) { - return null; - } - - static String readString(IStreamContentAccessor sa) throws CoreException { - InputStream is= sa.getContents(); - String encoding= null; - if (sa instanceof IEncodedStreamContentAccessor) - encoding= ((IEncodedStreamContentAccessor) sa).getCharset(); - if (encoding == null) - encoding= "UTF-8"; //$NON-NLS-1$ - return readString(is, encoding); - } - - /* - * Returns null if an error occurred. - */ - private static String readString(InputStream is, String encoding) { - if (is == null) - return null; - BufferedReader reader= null; - try { - StringBuilder buffer= new StringBuilder(); - char[] part= new char[2048]; - int read= 0; - reader= new BufferedReader(new InputStreamReader(is, encoding)); - - while ((read= reader.read(part)) != -1) - buffer.append(part, 0, read); - - return buffer.toString(); - - } catch (IOException ex) { - // NeedWork - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ex) { - // silently ignored - } - } - } - return null; - } - - /* Returns a sorted list of attributes. - */ - protected Attributes sortAttributes(Attributes attrs) { - - AttributesImpl attributes= new AttributesImpl(); - int len= (attrs != null) ? attrs.getLength() : 0; - for (int i= 0; i < len; i++) { - String name= attrs.getQName(i); - int count= attributes.getLength(); - int j= 0; - while (j < count) { - if (name.compareTo(attributes.getQName(j)) < 0) - break; - j++; - } - attributes.insertAttributeAt(j, name, attrs.getType(i), attrs.getValue(i)); - } - - return attributes; - - } - - public void setIdMap(String idmap_name) { - fIdMapToUse= idmap_name; - } - - /* - * Returns the name of the IdMap Scheme that will be used to set ids. - */ - public String getIdMap() { - return fIdMapToUse; - } - - public void setUseIdMap() { - if (fIdMaps != null && fIdMapsInternal != null) - fUseIdMap= fIdMaps.containsKey(fIdMapToUse) || fIdMapsInternal.containsKey(fIdMapToUse); - } - - public boolean isUseIdMap() { - return fUseIdMap; - } - - public void updateIdMaps() { - fIdMaps= XMLPlugin.getDefault().getIdMaps(); - fOrderedElements= XMLPlugin.getDefault().getOrderedElements(); - } - - protected boolean isWhiteSpace(char c) { - return c == '\t' || c == '\n' || c == '\r' || c == ' '; - } - - protected String removeWhiteSpace(String str) { - str= trimWhiteSpace(str); - StringBuilder retStr= new StringBuilder(); - int start= 0, end= 0; - outer_while: while (true) { - while (end < str.length() && !isWhiteSpace(str.charAt(end))) { - end++; - } - if (end > str.length()) - break outer_while; - if (start != 0) - retStr.append(' '); - retStr.append(str.substring(start, end)); - end++; - while (end < str.length() && isWhiteSpace(str.charAt(end))) { - end++; - } - start= end; - } - return retStr.toString(); - } - - protected String trimWhiteSpace(String str) { - int start= 0, end= str.length() - 1; - while (start < str.length() && isWhiteSpace(str.charAt(start))) { - start++; - } - if (start == str.length()) - return ""; //$NON-NLS-1$ - while (end >= 0 && isWhiteSpace(str.charAt(end))) { - end--; - } - return str.substring(start, end + 1); - } - - public void setRemoveWhiteSpace(boolean removeWhiteSpace) { - fRemoveWhiteSpace= removeWhiteSpace; - } - - public boolean getRemoveWhiteSpace() { - return fRemoveWhiteSpace; - } + return null; + } + + static String readString(IStreamContentAccessor sa) throws CoreException { + InputStream is= sa.getContents(); + String encoding= null; + if (sa instanceof IEncodedStreamContentAccessor) + encoding= ((IEncodedStreamContentAccessor) sa).getCharset(); + if (encoding == null) + encoding= "UTF-8"; //$NON-NLS-1$ + return readString(is, encoding); + } + + /* + * Returns null if an error occurred. + */ + private static String readString(InputStream is, String encoding) { + if (is == null) + return null; + BufferedReader reader= null; + try { + StringBuilder buffer= new StringBuilder(); + char[] part= new char[2048]; + int read= 0; + reader= new BufferedReader(new InputStreamReader(is, encoding)); + + while ((read= reader.read(part)) != -1) + buffer.append(part, 0, read); + + return buffer.toString(); + + } catch (IOException ex) { + // NeedWork + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ex) { + // silently ignored + } + } + } + return null; + } + + /* Returns a sorted list of attributes. + */ + protected Attributes sortAttributes(Attributes attrs) { + + AttributesImpl attributes= new AttributesImpl(); + int len= (attrs != null) ? attrs.getLength() : 0; + for (int i= 0; i < len; i++) { + String name= attrs.getQName(i); + int count= attributes.getLength(); + int j= 0; + while (j < count) { + if (name.compareTo(attributes.getQName(j)) < 0) + break; + j++; + } + attributes.insertAttributeAt(j, name, attrs.getType(i), attrs.getValue(i)); + } + + return attributes; + + } + + public void setIdMap(String idmap_name) { + fIdMapToUse= idmap_name; + } + + /* + * Returns the name of the IdMap Scheme that will be used to set ids. + */ + public String getIdMap() { + return fIdMapToUse; + } + + public void setUseIdMap() { + if (fIdMaps != null && fIdMapsInternal != null) + fUseIdMap= fIdMaps.containsKey(fIdMapToUse) || fIdMapsInternal.containsKey(fIdMapToUse); + } + + public boolean isUseIdMap() { + return fUseIdMap; + } + + public void updateIdMaps() { + fIdMaps= XMLPlugin.getDefault().getIdMaps(); + fOrderedElements= XMLPlugin.getDefault().getOrderedElements(); + } + + protected boolean isWhiteSpace(char c) { + return c == '\t' || c == '\n' || c == '\r' || c == ' '; + } + + protected String removeWhiteSpace(String str) { + str= trimWhiteSpace(str); + StringBuilder retStr= new StringBuilder(); + int start= 0, end= 0; + outer_while: while (true) { + while (end < str.length() && !isWhiteSpace(str.charAt(end))) { + end++; + } + if (end > str.length()) + break outer_while; + if (start != 0) + retStr.append(' '); + retStr.append(str.substring(start, end)); + end++; + while (end < str.length() && isWhiteSpace(str.charAt(end))) { + end++; + } + start= end; + } + return retStr.toString(); + } + + protected String trimWhiteSpace(String str) { + int start= 0, end= str.length() - 1; + while (start < str.length() && isWhiteSpace(str.charAt(start))) { + start++; + } + if (start == str.length()) + return ""; //$NON-NLS-1$ + while (end >= 0 && isWhiteSpace(str.charAt(end))) { + end--; + } + return str.substring(start, end + 1); + } + + public void setRemoveWhiteSpace(boolean removeWhiteSpace) { + fRemoveWhiteSpace= removeWhiteSpace; + } + + public boolean getRemoveWhiteSpace() { + return fRemoveWhiteSpace; + } } diff --git a/examples/org.eclipse.compare.examples.xml/tests/org/eclipse/compare/examples/xml/AllXMLCompareTests.java b/examples/org.eclipse.compare.examples.xml/tests/org/eclipse/compare/examples/xml/AllXMLCompareTests.java index fc3a9e8a2..c3d2002ee 100644 --- a/examples/org.eclipse.compare.examples.xml/tests/org/eclipse/compare/examples/xml/AllXMLCompareTests.java +++ b/examples/org.eclipse.compare.examples.xml/tests/org/eclipse/compare/examples/xml/AllXMLCompareTests.java @@ -27,7 +27,7 @@ public class AllXMLCompareTests { public static Test suite ( ) { TestSuite suite= new TestSuite("All XML Compare Tests"); //$NON-NLS-1$ suite.addTest(TestXMLStructureCreator.suite()); - return suite; + return suite; } } diff --git a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/FileSystemProvider.java b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/FileSystemProvider.java index a15f0446a..ea1fe81b7 100644 --- a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/FileSystemProvider.java +++ b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/FileSystemProvider.java @@ -235,10 +235,10 @@ public class FileSystemProvider extends RepositoryProvider { @Override public IFileHistoryProvider getFileHistoryProvider() { - if (FileSystemProvider.fileHistoryProvider == null) { - FileSystemProvider.fileHistoryProvider = new FileSystemHistoryProvider(); - } - return FileSystemProvider.fileHistoryProvider; + if (FileSystemProvider.fileHistoryProvider == null) { + FileSystemProvider.fileHistoryProvider = new FileSystemHistoryProvider(); + } + return FileSystemProvider.fileHistoryProvider; } } diff --git a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/ui/FileSystemTableProvider.java b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/ui/FileSystemTableProvider.java index 70c17f75f..fbb9e5e13 100644 --- a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/ui/FileSystemTableProvider.java +++ b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/filesystem/ui/FileSystemTableProvider.java @@ -154,7 +154,7 @@ public class FileSystemTableProvider { */ public int compare(Viewer compareViewer, Object o1, Object o2) { /*if (o1 instanceof AbstractCVSHistoryCategory || o2 instanceof AbstractCVSHistoryCategory) - return 0;*/ + return 0;*/ IFileRevision e1 = adaptToFileRevision(o1); IFileRevision e2 = adaptToFileRevision(o2); diff --git a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/localhistory/LocalHistoryParticipant.java b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/localhistory/LocalHistoryParticipant.java index 7caa66459..2b041eb7c 100644 --- a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/localhistory/LocalHistoryParticipant.java +++ b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/localhistory/LocalHistoryParticipant.java @@ -98,10 +98,10 @@ public class LocalHistoryParticipant extends SubscriberParticipant { } protected static SyncInfo getSyncInfo(ISynchronizeModelElement element) { - if (element instanceof IAdaptable) { - return ((IAdaptable)element).getAdapter(SyncInfo.class); - } - return null; + if (element instanceof IAdaptable) { + return ((IAdaptable)element).getAdapter(SyncInfo.class); + } + return null; } public void prepareCompareInput(ISynchronizeModelElement element, diff --git a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/model/ui/NewModelProjectWizard.java b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/model/ui/NewModelProjectWizard.java index 9fe53ff31..8fc7b5ac9 100644 --- a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/model/ui/NewModelProjectWizard.java +++ b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/model/ui/NewModelProjectWizard.java @@ -31,8 +31,8 @@ import org.eclipse.ui.internal.wizards.newresource.ResourceMessages; public class NewModelProjectWizard extends Wizard implements INewWizard { - private WizardNewProjectCreationPage mainPage; - + private WizardNewProjectCreationPage mainPage; + public NewModelProjectWizard() { super(); } @@ -40,94 +40,94 @@ public class NewModelProjectWizard extends Wizard implements INewWizard { public void addPages() { super.addPages(); - mainPage = new WizardNewProjectCreationPage("basicNewProjectPage");//$NON-NLS-1$ - mainPage.setTitle(ResourceMessages.NewProject_title); - mainPage.setDescription(ResourceMessages.NewProject_description); - this.addPage(mainPage); + mainPage = new WizardNewProjectCreationPage("basicNewProjectPage");//$NON-NLS-1$ + mainPage.setTitle(ResourceMessages.NewProject_title); + mainPage.setDescription(ResourceMessages.NewProject_description); + this.addPage(mainPage); } public boolean performFinish() { - // get a project handle - final IProject newProjectHandle = mainPage.getProjectHandle(); + // get a project handle + final IProject newProjectHandle = mainPage.getProjectHandle(); - // get a project descriptor - URI location = null; - if (!mainPage.useDefaults()) { + // get a project descriptor + URI location = null; + if (!mainPage.useDefaults()) { location = mainPage.getLocationURI(); } - IWorkspace workspace = ResourcesPlugin.getWorkspace(); - final IProjectDescription description = workspace - .newProjectDescription(newProjectHandle.getName()); - description.setLocationURI(location); - description.setNatureIds(new String[] {ModelNature.NATURE_ID}); + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + final IProjectDescription description = workspace + .newProjectDescription(newProjectHandle.getName()); + description.setLocationURI(location); + description.setNatureIds(new String[] {ModelNature.NATURE_ID}); - // create the new project operation - WorkspaceModifyOperation op = new WorkspaceModifyOperation() { - protected void execute(IProgressMonitor monitor) - throws CoreException { - createProject(description, newProjectHandle, monitor); - } - }; + // create the new project operation + WorkspaceModifyOperation op = new WorkspaceModifyOperation() { + protected void execute(IProgressMonitor monitor) + throws CoreException { + createProject(description, newProjectHandle, monitor); + } + }; - // run the new project creation operation - try { - getContainer().run(true, true, op); - } catch (InterruptedException e) { - return false; - } catch (InvocationTargetException e) { - // ie.- one of the steps resulted in a core exception - Throwable t = e.getTargetException(); - if (t instanceof CoreException) { - ErrorDialog.openError(getShell(), null, null, - ((CoreException) t).getStatus()); - } else { - MessageDialog - .openError( - getShell(), - "Error occurred", - t.getMessage()); - } - return false; - } + // run the new project creation operation + try { + getContainer().run(true, true, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + // ie.- one of the steps resulted in a core exception + Throwable t = e.getTargetException(); + if (t instanceof CoreException) { + ErrorDialog.openError(getShell(), null, null, + ((CoreException) t).getStatus()); + } else { + MessageDialog + .openError( + getShell(), + "Error occurred", + t.getMessage()); + } + return false; + } return true; } - /** - * Creates a project resource given the project handle and description. - * - * @param description - * the project description to create a project resource for - * @param projectHandle - * the project handle to create a project resource for - * @param monitor - * the progress monitor to show visual progress with - * - * @exception CoreException - * if the operation fails - * @exception OperationCanceledException - * if the operation is canceled - */ - void createProject(IProjectDescription description, IProject projectHandle, - IProgressMonitor monitor) throws CoreException, - OperationCanceledException { - try { - monitor.beginTask("", 2000);//$NON-NLS-1$ + /** + * Creates a project resource given the project handle and description. + * + * @param description + * the project description to create a project resource for + * @param projectHandle + * the project handle to create a project resource for + * @param monitor + * the progress monitor to show visual progress with + * + * @exception CoreException + * if the operation fails + * @exception OperationCanceledException + * if the operation is canceled + */ + void createProject(IProjectDescription description, IProject projectHandle, + IProgressMonitor monitor) throws CoreException, + OperationCanceledException { + try { + monitor.beginTask("", 2000);//$NON-NLS-1$ - projectHandle.create(description, SubMonitor.convert(monitor, - 1000)); + projectHandle.create(description, SubMonitor.convert(monitor, + 1000)); - if (monitor.isCanceled()) { + if (monitor.isCanceled()) { throw new OperationCanceledException(); } - projectHandle.open(IResource.BACKGROUND_REFRESH, SubMonitor.convert(monitor, 1000)); + projectHandle.open(IResource.BACKGROUND_REFRESH, SubMonitor.convert(monitor, 1000)); - } finally { - monitor.done(); - } - } - + } finally { + monitor.done(); + } + } + public void init(IWorkbench workbench, IStructuredSelection selection) { // Nothing to do } diff --git a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/pessimistic/ui/PessimisticPreferencesPage.java b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/pessimistic/ui/PessimisticPreferencesPage.java index 322a13705..d11067e20 100644 --- a/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/pessimistic/ui/PessimisticPreferencesPage.java +++ b/examples/org.eclipse.team.examples.filesystem/src/org/eclipse/team/examples/pessimistic/ui/PessimisticPreferencesPage.java @@ -267,7 +267,7 @@ public class PessimisticPreferencesPage int selectionIndex = filesAreEditedCombo.getSelectionIndex(); if (selectionIndex != -1) - store.setValue( + store.setValue( IPessimisticFilesystemConstants.PREF_CHECKED_IN_FILES_EDITED, EDIT_OPTION_KEYS[selectionIndex]); selectionIndex = filesAreEditedNoPromptCombo.getSelectionIndex(); diff --git a/tests/org.eclipse.compare.tests/META-INF/MANIFEST.MF b/tests/org.eclipse.compare.tests/META-INF/MANIFEST.MF index a69a1a49e..672694446 100644 --- a/tests/org.eclipse.compare.tests/META-INF/MANIFEST.MF +++ b/tests/org.eclipse.compare.tests/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.compare.tests;singleton:=true -Bundle-Version: 3.6.400.qualifier +Bundle-Version: 3.6.500.qualifier Require-Bundle: org.junit, org.eclipse.compare, org.eclipse.jface.text, diff --git a/tests/org.eclipse.compare.tests/pom.xml b/tests/org.eclipse.compare.tests/pom.xml index d9c81e34e..765a756a4 100644 --- a/tests/org.eclipse.compare.tests/pom.xml +++ b/tests/org.eclipse.compare.tests/pom.xml @@ -19,7 +19,7 @@ </parent> <groupId>org.eclipse.compare</groupId> <artifactId>org.eclipse.compare.tests</artifactId> - <version>3.6.400-SNAPSHOT</version> + <version>3.6.500-SNAPSHOT</version> <packaging>eclipse-test-plugin</packaging> <properties> diff --git a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/PatchTest.java b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/PatchTest.java index 60fbf1172..026e8e433 100644 --- a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/PatchTest.java +++ b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/PatchTest.java @@ -292,12 +292,12 @@ public class PatchTest extends TestCase { if (patchConf != null) { JarEntryStorage jes = new JarEntryStorage(entry,jarFile); Properties properties = new Properties(); - try { - properties.load(jes.getContents()); - } catch (IOException e) { - fail("IOException occured while loading the Patch Configuration file for "+entryName.toString()); - } - processProperties(result, properties, entryName); + try { + properties.load(jes.getContents()); + } catch (IOException e) { + fail("IOException occured while loading the Patch Configuration file for "+entryName.toString()); + } + processProperties(result, properties, entryName); } else { processProperties(result, defaultPatchProperties, entryName); } @@ -325,13 +325,13 @@ public class PatchTest extends TestCase { continue; if (pcFile.exists()) { Properties properties = new Properties(); - try { - properties.load(new FileInputStream(pcFile)); - } catch (IOException e) { - fail("IOException occured while loading the Patch Configuration file for " + try { + properties.load(new FileInputStream(pcFile)); + } catch (IOException e) { + fail("IOException occured while loading the Patch Configuration file for " + subfolder.toString()); - } - processProperties(result, properties, subfolder.getName()); + } + processProperties(result, properties, subfolder.getName()); } else { processProperties(result, defaultPatchProperties, subfolder.getName()); } diff --git a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/RangeDifferencerThreeWayDiffTest.java b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/RangeDifferencerThreeWayDiffTest.java index bbf28666f..59d990d75 100644 --- a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/RangeDifferencerThreeWayDiffTest.java +++ b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/RangeDifferencerThreeWayDiffTest.java @@ -28,8 +28,8 @@ public class RangeDifferencerThreeWayDiffTest extends TestCase { static final String S= System.getProperty("line.separator"); //$NON-NLS-1$ public RangeDifferencerThreeWayDiffTest(String name) { - super(name); - } + super(name); + } public void testInsertConflict() { String a = "A" + S + "B" + S + "C" + S + "D"; //$NON-NLS-1$ diff --git a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/WorkspaceTest.java b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/WorkspaceTest.java index 433857e3d..cb46514c6 100644 --- a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/WorkspaceTest.java +++ b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/WorkspaceTest.java @@ -101,7 +101,7 @@ public class WorkspaceTest extends ResourceTest { ensureExistsInWorkspace(result, true); for (int i = 0; i < result.length; i++) { if (result[i].getType() == IResource.FILE) // 3786 bytes is the average size of Eclipse Java files! - ((IFile) result[i]).setContents(getRandomContents(100), true, false, null); + ((IFile) result[i]).setContents(getRandomContents(100), true, false, null); } return result; } diff --git a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/performance/RangeDifferencerTest.java b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/performance/RangeDifferencerTest.java index 315601e8a..daa5bfa6d 100644 --- a/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/performance/RangeDifferencerTest.java +++ b/tests/org.eclipse.compare.tests/src/org/eclipse/compare/tests/performance/RangeDifferencerTest.java @@ -29,8 +29,8 @@ public class RangeDifferencerTest extends PerformanceTestCase { // static private final String EXPLANATION = "Performance decrease caused by changes in the compare framework, see bug 210688"; public RangeDifferencerTest(String name) { - super(name); - } + super(name); + } /* * Creates document with 5000 lines. diff --git a/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/mapping/ScopeBuildingTests.java b/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/mapping/ScopeBuildingTests.java index edc8dc6a0..3791b47dc 100644 --- a/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/mapping/ScopeBuildingTests.java +++ b/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/mapping/ScopeBuildingTests.java @@ -107,9 +107,9 @@ public class ScopeBuildingTests extends TeamTest { public String getModelProviderId() { return TEST_MODEL_PROVIDER_ID; } - public boolean contains(ResourceMapping mapping) { - return false; - } + public boolean contains(ResourceMapping mapping) { + return false; + } }; } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSClientException.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSClientException.java index 59bcb3340..fd5f21920 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSClientException.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSClientException.java @@ -17,11 +17,11 @@ import org.eclipse.team.internal.ccvs.core.CVSException; public class CVSClientException extends CVSException { /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; + * Comment for <code>serialVersionUID</code> + */ + private static final long serialVersionUID = 1L; - public CVSClientException(String message) { + public CVSClientException(String message) { super(message); } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java index d7ef72b33..bc3180255 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/CVSTestSetup.java @@ -33,10 +33,10 @@ public class CVSTestSetup extends TestSetup { public static final int WAIT_FACTOR; public static final int COMPRESSION_LEVEL; public static final boolean FAIL_IF_EXCEPTION_LOGGED; - public static final boolean RECORD_PROTOCOL_TRAFFIC; - public static final boolean ENSURE_SEQUENTIAL_ACCESS; - public static final boolean FAIL_ON_BAD_DIFF; - public static final int TIMEOUT = 600; + public static final boolean RECORD_PROTOCOL_TRAFFIC; + public static final boolean ENSURE_SEQUENTIAL_ACCESS; + public static final boolean FAIL_ON_BAD_DIFF; + public static final int TIMEOUT = 600; public static CVSRepositoryLocation repository; public static CVSTestLogListener logListener; @@ -52,9 +52,9 @@ public class CVSTestSetup extends TestSetup { WAIT_FACTOR = Integer.parseInt(System.getProperty("eclipse.cvs.waitFactor", "1")); COMPRESSION_LEVEL = Integer.parseInt(System.getProperty("eclipse.cvs.compressionLevel", "0")); FAIL_IF_EXCEPTION_LOGGED = Boolean.valueOf(System.getProperty("eclipse.cvs.failLog", "true")).booleanValue(); - RECORD_PROTOCOL_TRAFFIC = Boolean.valueOf(System.getProperty("eclipse.cvs.recordProtocolTraffic", "false")).booleanValue(); - ENSURE_SEQUENTIAL_ACCESS = Boolean.valueOf(System.getProperty("eclipse.cvs.sequentialAccess", "false")).booleanValue(); - FAIL_ON_BAD_DIFF = Boolean.valueOf(System.getProperty("eclipse.cvs.failOnBadDiff", "false")).booleanValue(); + RECORD_PROTOCOL_TRAFFIC = Boolean.valueOf(System.getProperty("eclipse.cvs.recordProtocolTraffic", "false")).booleanValue(); + ENSURE_SEQUENTIAL_ACCESS = Boolean.valueOf(System.getProperty("eclipse.cvs.sequentialAccess", "false")).booleanValue(); + FAIL_ON_BAD_DIFF = Boolean.valueOf(System.getProperty("eclipse.cvs.failOnBadDiff", "false")).booleanValue(); } public static void loadProperties() { diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/EclipseTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/EclipseTest.java index 4e9a3bf89..89a823af7 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/EclipseTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/EclipseTest.java @@ -107,9 +107,9 @@ import org.eclipse.ui.internal.decorators.DecoratorManager; public class EclipseTest extends ResourceTest { private static final int LOCK_WAIT_TIME = 1000; - private static final String CVS_TEST_LOCK_FILE = ".lock"; - private static final String CVS_TEST_LOCK_PROJECT = "cvsTestLock"; - protected static IProgressMonitor DEFAULT_MONITOR = new NullProgressMonitor(); + private static final String CVS_TEST_LOCK_FILE = ".lock"; + private static final String CVS_TEST_LOCK_PROJECT = "cvsTestLock"; + protected static IProgressMonitor DEFAULT_MONITOR = new NullProgressMonitor(); protected static final int RANDOM_CONTENT_SIZE = 3876; protected static String eol = System.getProperty("line.separator"); private static boolean modelSync = true; @@ -220,12 +220,12 @@ public class EclipseTest extends ResourceTest { protected void addResources(IResource[] newResources) throws CoreException { if (newResources.length == 0) return; ResourceMapping[] mappings = asResourceMappers(newResources, IResource.DEPTH_INFINITE); - add(mappings); + add(mappings); } - protected void add(ResourceMapping[] mappings) throws CVSException { - executeHeadless(new AddOperation(null, mappings)); - } + protected void add(ResourceMapping[] mappings) throws CVSException { + executeHeadless(new AddOperation(null, mappings)); + } /** * Perform a CVS edit of the given resources @@ -346,49 +346,49 @@ public class EclipseTest extends ResourceTest { /** * Update the resources from an existing container with the changes from the CVS repository */ - protected IResource[] updateResources(IResource[] resources, boolean ignoreLocalChanges) throws CVSException { - LocalOption[] options = Command.NO_LOCAL_OPTIONS; + protected IResource[] updateResources(IResource[] resources, boolean ignoreLocalChanges) throws CVSException { + LocalOption[] options = Command.NO_LOCAL_OPTIONS; if(ignoreLocalChanges) { options = new LocalOption[] {Update.IGNORE_LOCAL_CHANGES}; } - ResourceMapping[] mappers = asResourceMappers(resources, IResource.DEPTH_INFINITE); + ResourceMapping[] mappers = asResourceMappers(resources, IResource.DEPTH_INFINITE); update(mappers, options); return resources; - } + } - /** - * Update the resources contained in the given mappers. - */ - protected void update(ResourceMapping[] mappings, LocalOption[] options) throws CVSException { - if (options == null) - options = Command.NO_LOCAL_OPTIONS; - if (isModelSyncEnabled() && options == Command.NO_LOCAL_OPTIONS) { - executeHeadless(new ModelUpdateOperation(null, mappings, false) { - @Override + /** + * Update the resources contained in the given mappers. + */ + protected void update(ResourceMapping[] mappings, LocalOption[] options) throws CVSException { + if (options == null) + options = Command.NO_LOCAL_OPTIONS; + if (isModelSyncEnabled() && options == Command.NO_LOCAL_OPTIONS) { + executeHeadless(new ModelUpdateOperation(null, mappings, false) { + @Override protected boolean isAttemptHeadlessMerge() { - return true; - } - @Override + return true; + } + @Override protected void handlePreviewRequest() { - // Don't preview anything - } - @Override + // Don't preview anything + } + @Override protected void handleNoChanges() { - // Do nothing - } - @Override + // Do nothing + } + @Override protected void handleValidationFailure(IStatus status) { - // Do nothing - } - @Override + // Do nothing + } + @Override protected void handleMergeFailure(IStatus status) { - // Do nothing - } - }); - } else { - executeHeadless(new UpdateOperation(null, mappings, options, null)); - } - } + // Do nothing + } + }); + } else { + executeHeadless(new UpdateOperation(null, mappings, options, null)); + } + } protected void replace(IContainer container, String[] hierarchy, CVSTag tag, boolean recurse) throws CoreException { IResource[] resources = getResources(container, hierarchy); @@ -400,31 +400,31 @@ public class EclipseTest extends ResourceTest { executeHeadless(op); } - protected void replace(ResourceMapping[] mappings) throws CVSException { - if (isModelSyncEnabled()) { - executeHeadless(new ModelReplaceOperation(null, mappings, false) { - @Override + protected void replace(ResourceMapping[] mappings) throws CVSException { + if (isModelSyncEnabled()) { + executeHeadless(new ModelReplaceOperation(null, mappings, false) { + @Override protected boolean promptForOverwrite() { - return true; - } - @Override + return true; + } + @Override protected void handlePreviewRequest() { - // Don't prompt - } - @Override + // Don't prompt + } + @Override protected void handleMergeFailure(IStatus status) { - // Don't prompt - } - @Override + // Don't prompt + } + @Override protected void handleValidationFailure(IStatus status) { - // Don't prompt - } - }); - } else { - executeHeadless(new ReplaceOperation(null, mappings, null)); - } - } - + // Don't prompt + } + }); + } else { + executeHeadless(new ReplaceOperation(null, mappings, null)); + } + } + public void updateProject(IProject project, CVSTag tag, boolean ignoreLocalChanges) throws TeamException { if (tag == null) { ResourceMapping[] mappings = asResourceMappers(new IResource[] { project }, IResource.DEPTH_INFINITE); @@ -468,51 +468,51 @@ public class EclipseTest extends ResourceTest { protected void commitResources(IResource[] resources, int depth, String message) throws TeamException, CoreException { if (resources.length == 0) return; ResourceMapping[] resourceMappers = asResourceMappers(resources, depth); - commit(resourceMappers, message); + commit(resourceMappers, message); } - /** - * Commit the resources contained by the mappers. - */ - protected void commit(ResourceMapping[] mappers, String message) throws CVSException { - executeHeadless(new CommitOperation(null, mappers, new Command.LocalOption[0], message)); - } + /** + * Commit the resources contained by the mappers. + */ + protected void commit(ResourceMapping[] mappers, String message) throws CVSException { + executeHeadless(new CommitOperation(null, mappers, new Command.LocalOption[0], message)); + } - /** - * Convert the resources to a resource mapper that traverses the resources - * to the specified depth. - * @param resources the resource - * @return a resource mapper for traversing the resources to the depth specified - */ - protected ResourceMapping[] asResourceMappers(IResource[] resources, int depth) { - return WorkspaceResourceMapper.asResourceMappers(resources, depth); - } - - protected ICVSResource asCVSResource(IResource resource) { - return CVSWorkspaceRoot.getCVSResourceFor(resource); - } - + /** + * Convert the resources to a resource mapper that traverses the resources + * to the specified depth. + * @param resources the resource + * @return a resource mapper for traversing the resources to the depth specified + */ + protected ResourceMapping[] asResourceMappers(IResource[] resources, int depth) { + return WorkspaceResourceMapper.asResourceMappers(resources, depth); + } + + protected ICVSResource asCVSResource(IResource resource) { + return CVSWorkspaceRoot.getCVSResourceFor(resource); + } + /** * Commit the resources from an existing container to the CVS repository */ public void tagProject(IProject project, CVSTag tag, boolean force) throws TeamException { ResourceMapping[] mappings = RepositoryProviderOperation.asResourceMappers(new IResource[] {project}); - tag(mappings, tag, force); + tag(mappings, tag, force); } - /** - * Tag the resources contained in the given mappings - */ - protected void tag(ResourceMapping[] mappings, CVSTag tag, boolean force) throws TeamException { - ITagOperation op = new TagOperation((IWorkbenchPart)null, mappings); - runTag(op, tag, force); - } + /** + * Tag the resources contained in the given mappings + */ + protected void tag(ResourceMapping[] mappings, CVSTag tag, boolean force) throws TeamException { + ITagOperation op = new TagOperation((IWorkbenchPart)null, mappings); + runTag(op, tag, force); + } public void tagRemoteResource(ICVSRemoteResource resource, CVSTag tag, boolean force) throws TeamException { ITagOperation op = new TagInRepositoryOperation(null, new ICVSRemoteResource[] {resource}); runTag(op, tag, force); } - + protected void runTag(ITagOperation op, CVSTag tag, boolean force) throws TeamException { op.setTag(tag); if (force) op.moveTag(); @@ -531,15 +531,15 @@ public class EclipseTest extends ResourceTest { } public void makeBranch(IResource[] resources, CVSTag version, CVSTag branch, boolean update) throws CVSException { ResourceMapping[] mappings = asResourceMappers(resources, IResource.DEPTH_INFINITE); - branch(mappings, version, branch, update); + branch(mappings, version, branch, update); } - protected void branch(ResourceMapping[] mappings, CVSTag version, CVSTag branch, boolean update) throws CVSException { - BranchOperation op = new BranchOperation(null, mappings); - op.setTags(version, branch, update); - executeHeadless(op); - } - + protected void branch(ResourceMapping[] mappings, CVSTag version, CVSTag branch, boolean update) throws CVSException { + BranchOperation op = new BranchOperation(null, mappings); + op.setTags(version, branch, update); + executeHeadless(op); + } + /** * Return a collection of resources defined by hierarchy. The resources * are added to the workspace and to the file system. If the manage flag is true, the @@ -555,7 +555,7 @@ public class EclipseTest extends ResourceTest { for (int i = 0; i < result.length; i++) { if (result[i].getType() == IResource.FILE) // 3786 bytes is the average size of Eclipse Java files! - ((IFile) result[i]).setContents(getRandomContents(RANDOM_CONTENT_SIZE), true, false, null); + ((IFile) result[i]).setContents(getRandomContents(RANDOM_CONTENT_SIZE), true, false, null); } return result; } @@ -596,8 +596,8 @@ public class EclipseTest extends ResourceTest { } protected IProject checkoutProject(IProject project, String moduleName, CVSTag tag) throws TeamException { - if (project == null) - project = getWorkspace().getRoot().getProject(new Path(moduleName).lastSegment()); + if (project == null) + project = getWorkspace().getRoot().getProject(new Path(moduleName).lastSegment()); checkout(getRepository(), project, moduleName, tag, DEFAULT_MONITOR); return project; } @@ -670,16 +670,16 @@ public class EclipseTest extends ResourceTest { * Compare resources by casting them to their prpoer type */ protected void assertEquals(IPath parent, ICVSResource resource1, ICVSResource resource2, boolean includeTimestamps, boolean includeTags) throws CoreException, CVSException, IOException { - if ((resource1 == null && resource2 == null) - || (resource1 == null && ! resource2.exists()) - || (resource2 == null && ! resource1.exists())) - return; - if (resource1 == null && resource2 != null) { - fail("Expected no resource for " + resource2.getRepositoryRelativePath() + " but there was one"); - } - if (resource2 == null && resource1 != null) { - fail("Expected resource " + resource1.getRepositoryRelativePath() + " was missing"); - } + if ((resource1 == null && resource2 == null) + || (resource1 == null && ! resource2.exists()) + || (resource2 == null && ! resource1.exists())) + return; + if (resource1 == null && resource2 != null) { + fail("Expected no resource for " + resource2.getRepositoryRelativePath() + " but there was one"); + } + if (resource2 == null && resource1 != null) { + fail("Expected resource " + resource1.getRepositoryRelativePath() + " was missing"); + } assertEquals("Resource types do not match for " + parent.append(resource1.getName()), resource1.isFolder(), resource2.isFolder()); if (!resource1.isFolder()) assertEquals(parent, (ICVSFile)resource1, (ICVSFile)resource2, includeTimestamps, includeTags); @@ -1076,17 +1076,17 @@ public class EclipseTest extends ResourceTest { public static void waitForIgnoreFileHandling() { waitForJobCompletion(SyncFileChangeListener.getDeferredHandler().getEventHandlerJob()); - waitForDecorator(); + waitForDecorator(); } - protected static void waitForDecorator() { - // Wait for the decorator job - Job[] decorators = Job.getJobManager().find(DecoratorManager.FAMILY_DECORATE); - for (int i = 0; i < decorators.length; i++) { - Job job = decorators[i]; - waitForJobCompletion(job); - } - } + protected static void waitForDecorator() { + // Wait for the decorator job + Job[] decorators = Job.getJobManager().find(DecoratorManager.FAMILY_DECORATE); + for (int i = 0; i < decorators.length; i++) { + Job job = decorators[i]; + waitForJobCompletion(job); + } + } public static void waitForSubscriberInputHandling(SubscriberSyncInfoCollector input) { input.waitForCollector(new IProgressMonitor() { @@ -1136,14 +1136,14 @@ public class EclipseTest extends ResourceTest { if (ex instanceof InvocationTargetException) throw CVSException.wrapException(ex); } - - @Override + + @Override protected void setUp() throws Exception { - RepositoryProviderOperation.consultModelsWhenBuildingScope = false; - if (CVSTestSetup.ENSURE_SEQUENTIAL_ACCESS) - obtainCVSServerLock(); - super.setUp(); - } + RepositoryProviderOperation.consultModelsWhenBuildingScope = false; + if (CVSTestSetup.ENSURE_SEQUENTIAL_ACCESS) + obtainCVSServerLock(); + super.setUp(); + } @Override protected void tearDown() throws Exception { @@ -1165,153 +1165,153 @@ public class EclipseTest extends ResourceTest { } TestUtil.cleanUp(); } - - private void obtainCVSServerLock() { - IProject project = null; - boolean firstTry = true; - while (project == null) { - try { - project = checkoutProject(null, CVS_TEST_LOCK_PROJECT , null); - } catch (TeamException e) { - // The checkout of the lock project failed so lets create it if it doesn't exist - if (firstTry) { - try { - createTestLockProject(DEFAULT_MONITOR); - } catch (TeamException e1) { - // We couldn't check out the project or create it - // It's possible someone beat us to it so we'll try the checkout again. - } - } else { - // We tried twice to check out the project and failed. - // Lets just go ahead and run but we'll log the fact that we couldn't get the lock - write(new CVSStatus(IStatus.ERROR, "Could not obtain the CVS server lock. The test will containue but any performance timings may be affected", e), 0); - return; - } - firstTry = false; - } - } - if (project != null) { - IFile lockFile = project.getFile(CVS_TEST_LOCK_FILE); - boolean obtained = false; - int attempts = 0; - while (!obtained) { - attempts++; - if (lockFile.exists()) { - // If the file exists, check if the lock has expired - if (hasExpired(lockFile)) { - try { - overwriteLock(lockFile); - return; - } catch (CoreException e) { - // Ignore the error and continue - } - } - } else { - try { - writeLock(lockFile); - return; - } catch (CoreException e) { - // Ignore the error, since it probably means someone beat us to it. - } - } - // Wait for a while before testing the lock again - try { - Thread.sleep(LOCK_WAIT_TIME); - } catch (InterruptedException e) { - // Ignore - } - try { - // Update the lockfile in case someone else got to it first - replace(new IResource[] { lockFile }, null, true); - } catch (CoreException e) { - // An error updated is not recoverable so just continue - write(new CVSStatus(IStatus.ERROR, "Could not obtain the CVS server lock. The test will continue but any performance timings may be affected", e), 0); - return; - } - if (attempts > MAX_LOCK_ATTEMPTS) { - write(new CVSStatus(IStatus.ERROR, "Could not obtain the CVS server lock. The test will continue but any performance timings may be affected", new Exception()), 0); - return; - } - } - } - } - - private boolean hasExpired(IFile lockFile) { - long timestamp = lockFile.getLocalTimeStamp(); - return System.currentTimeMillis() - timestamp > LOCK_EXPIRATION_THRESHOLD; - } + + private void obtainCVSServerLock() { + IProject project = null; + boolean firstTry = true; + while (project == null) { + try { + project = checkoutProject(null, CVS_TEST_LOCK_PROJECT , null); + } catch (TeamException e) { + // The checkout of the lock project failed so lets create it if it doesn't exist + if (firstTry) { + try { + createTestLockProject(DEFAULT_MONITOR); + } catch (TeamException e1) { + // We couldn't check out the project or create it + // It's possible someone beat us to it so we'll try the checkout again. + } + } else { + // We tried twice to check out the project and failed. + // Lets just go ahead and run but we'll log the fact that we couldn't get the lock + write(new CVSStatus(IStatus.ERROR, "Could not obtain the CVS server lock. The test will containue but any performance timings may be affected", e), 0); + return; + } + firstTry = false; + } + } + if (project != null) { + IFile lockFile = project.getFile(CVS_TEST_LOCK_FILE); + boolean obtained = false; + int attempts = 0; + while (!obtained) { + attempts++; + if (lockFile.exists()) { + // If the file exists, check if the lock has expired + if (hasExpired(lockFile)) { + try { + overwriteLock(lockFile); + return; + } catch (CoreException e) { + // Ignore the error and continue + } + } + } else { + try { + writeLock(lockFile); + return; + } catch (CoreException e) { + // Ignore the error, since it probably means someone beat us to it. + } + } + // Wait for a while before testing the lock again + try { + Thread.sleep(LOCK_WAIT_TIME); + } catch (InterruptedException e) { + // Ignore + } + try { + // Update the lockfile in case someone else got to it first + replace(new IResource[] { lockFile }, null, true); + } catch (CoreException e) { + // An error updated is not recoverable so just continue + write(new CVSStatus(IStatus.ERROR, "Could not obtain the CVS server lock. The test will continue but any performance timings may be affected", e), 0); + return; + } + if (attempts > MAX_LOCK_ATTEMPTS) { + write(new CVSStatus(IStatus.ERROR, "Could not obtain the CVS server lock. The test will continue but any performance timings may be affected", new Exception()), 0); + return; + } + } + } + } + + private boolean hasExpired(IFile lockFile) { + long timestamp = lockFile.getLocalTimeStamp(); + return System.currentTimeMillis() - timestamp > LOCK_EXPIRATION_THRESHOLD; + } - private void overwriteLock(IFile lockFile) throws CoreException { - lockFile.setContents(getLockContents(), true, true, null); - commitResources(new IResource[] { lockFile }, IResource.DEPTH_ZERO); - } + private void overwriteLock(IFile lockFile) throws CoreException { + lockFile.setContents(getLockContents(), true, true, null); + commitResources(new IResource[] { lockFile }, IResource.DEPTH_ZERO); + } - private void writeLock(IFile lockFile) throws CoreException { - lockFile.create(getLockContents(), false, null); - addResources(new IResource[] { lockFile }); - commitResources(new IResource[] { lockFile }, IResource.DEPTH_ZERO); - } + private void writeLock(IFile lockFile) throws CoreException { + lockFile.create(getLockContents(), false, null); + addResources(new IResource[] { lockFile }); + commitResources(new IResource[] { lockFile }, IResource.DEPTH_ZERO); + } - private InputStream getLockContents() { - lockId = Long.toString(System.currentTimeMillis()); - return new ByteArrayInputStream(lockId.getBytes()); - } + private InputStream getLockContents() { + lockId = Long.toString(System.currentTimeMillis()); + return new ByteArrayInputStream(lockId.getBytes()); + } - private void createTestLockProject(IProgressMonitor monitor) throws TeamException { - CVSRepositoryLocation repository = getRepository(); - RemoteFolderTree root = new RemoteFolderTree(null, repository, Path.EMPTY.toString(), null); - RemoteFolderTree child = new RemoteFolderTree(root, CVS_TEST_LOCK_PROJECT, repository, new Path(null, root.getRepositoryRelativePath()).append(CVS_TEST_LOCK_PROJECT).toString(), null); - root.setChildren(new ICVSRemoteResource[] { child }); - Session s = new Session(repository, root); - s.open(monitor, true /* open for modification */); - try { - IStatus status = Command.ADD.execute(s, - Command.NO_GLOBAL_OPTIONS, - Command.NO_LOCAL_OPTIONS, - new String[] { CVS_TEST_LOCK_PROJECT }, - null, - monitor); - // If we get a warning, the operation most likely failed so check that the status is OK - if (status.getCode() == CVSStatus.SERVER_ERROR || ! status.isOK()) { - throw new CVSServerException(status); - } - } finally { - s.close(); - } - } - + private void createTestLockProject(IProgressMonitor monitor) throws TeamException { + CVSRepositoryLocation repository = getRepository(); + RemoteFolderTree root = new RemoteFolderTree(null, repository, Path.EMPTY.toString(), null); + RemoteFolderTree child = new RemoteFolderTree(root, CVS_TEST_LOCK_PROJECT, repository, new Path(null, root.getRepositoryRelativePath()).append(CVS_TEST_LOCK_PROJECT).toString(), null); + root.setChildren(new ICVSRemoteResource[] { child }); + Session s = new Session(repository, root); + s.open(monitor, true /* open for modification */); + try { + IStatus status = Command.ADD.execute(s, + Command.NO_GLOBAL_OPTIONS, + Command.NO_LOCAL_OPTIONS, + new String[] { CVS_TEST_LOCK_PROJECT }, + null, + monitor); + // If we get a warning, the operation most likely failed so check that the status is OK + if (status.getCode() == CVSStatus.SERVER_ERROR || ! status.isOK()) { + throw new CVSServerException(status); + } + } finally { + s.close(); + } + } + private void releaseCVSServerLock() { - if (lockId != null) { - try { - IProject project = getWorkspace().getRoot().getProject(CVS_TEST_LOCK_PROJECT); - // Update the project and verify we still have the lock - IFile file = project.getFile(CVS_TEST_LOCK_FILE); - String id = getFileContents(file); - if (id.equals(lockId)) { - // We have the lock so let's free it (but first check if someone preempted us) - ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file); - byte[] bytes = cvsFile.getSyncBytes(); - if (bytes != null) { - String revision = ResourceSyncInfo.getRevision(bytes); - updateResources(new IResource[] { file }, true); - bytes = cvsFile.getSyncBytes(); - if (bytes == null || !ResourceSyncInfo.getRevision(bytes).equals(revision)) { - write(new CVSStatus(IStatus.ERROR, "The CVS server lock expired while this test was running. Any performance timings may be affected", new Exception()), 0); - return; - } - } - // Delete the lock file and commit - deleteResources(project, new String[] { CVS_TEST_LOCK_FILE }, true); - } - } catch (CoreException e) { - write(e.getStatus(), 0); - } catch (IOException e) { - write(new CVSStatus(IStatus.ERROR, "An error occurred while reading the lock file", e), 0); - } - } - } + if (lockId != null) { + try { + IProject project = getWorkspace().getRoot().getProject(CVS_TEST_LOCK_PROJECT); + // Update the project and verify we still have the lock + IFile file = project.getFile(CVS_TEST_LOCK_FILE); + String id = getFileContents(file); + if (id.equals(lockId)) { + // We have the lock so let's free it (but first check if someone preempted us) + ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(file); + byte[] bytes = cvsFile.getSyncBytes(); + if (bytes != null) { + String revision = ResourceSyncInfo.getRevision(bytes); + updateResources(new IResource[] { file }, true); + bytes = cvsFile.getSyncBytes(); + if (bytes == null || !ResourceSyncInfo.getRevision(bytes).equals(revision)) { + write(new CVSStatus(IStatus.ERROR, "The CVS server lock expired while this test was running. Any performance timings may be affected", new Exception()), 0); + return; + } + } + // Delete the lock file and commit + deleteResources(project, new String[] { CVS_TEST_LOCK_FILE }, true); + } + } catch (CoreException e) { + write(e.getStatus(), 0); + } catch (IOException e) { + write(new CVSStatus(IStatus.ERROR, "An error occurred while reading the lock file", e), 0); + } + } + } - protected void write(IStatus status, int indent) { + protected void write(IStatus status, int indent) { PrintStream output = System.out; indent(output, indent); output.println("Severity: " + status.getSeverity()); @@ -1471,54 +1471,54 @@ public class EclipseTest extends ResourceTest { } } - protected void assertStatusContainsCode(IStatus status, int code) { - if (status.isMultiStatus()) { - IStatus[] children = status.getChildren(); - for (int i = 0; i < children.length; i++) { - IStatus child = children[i]; - if (child.getCode() == code) - return; - } - fail("Expected status code was not present"); - } else { - assertEquals("Status code is not what is expected", status.getCode(), code); - } - } + protected void assertStatusContainsCode(IStatus status, int code) { + if (status.isMultiStatus()) { + IStatus[] children = status.getChildren(); + for (int i = 0; i < children.length; i++) { + IStatus child = children[i]; + if (child.getCode() == code) + return; + } + fail("Expected status code was not present"); + } else { + assertEquals("Status code is not what is expected", status.getCode(), code); + } + } - @Override + @Override protected void runTest() throws Throwable { - if (!CVSTestSetup.RECORD_PROTOCOL_TRAFFIC) { - super.runTest(); - return; - } - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Policy.recorder = new PrintStream(os); - try { - try { - // Override the runTest method in order to print the entire trace of a - // test that failed due to a CoreException including nested exceptions - super.runTest(); - } catch (CoreException e) { - e.printStackTrace(); - write(e.getStatus(), 0); - throw e; - } - } catch (Throwable e) { - // Transfer the recorded debug info to stdout - Policy.recorder.close(); - System.out.println(new String(os.toByteArray())); - throw e; - } finally { - Policy.recorder.close(); - Policy.recorder = null; - } - } - - @Override + if (!CVSTestSetup.RECORD_PROTOCOL_TRAFFIC) { + super.runTest(); + return; + } + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Policy.recorder = new PrintStream(os); + try { + try { + // Override the runTest method in order to print the entire trace of a + // test that failed due to a CoreException including nested exceptions + super.runTest(); + } catch (CoreException e) { + e.printStackTrace(); + write(e.getStatus(), 0); + throw e; + } + } catch (Throwable e) { + // Transfer the recorded debug info to stdout + Policy.recorder.close(); + System.out.println(new String(os.toByteArray())); + throw e; + } finally { + Policy.recorder.close(); + Policy.recorder = null; + } + } + + @Override protected void cleanup() throws CoreException { ensureDoesNotExistInWorkspace(getWorkspace().getRoot()); getWorkspace().save(true, null); //don't leak builder jobs, since they may affect subsequent tests waitForBuild(); - } + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/TestsUserAuthenticator.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/TestsUserAuthenticator.java index 5fe096cbd..56f048de5 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/TestsUserAuthenticator.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/TestsUserAuthenticator.java @@ -39,10 +39,10 @@ public class TestsUserAuthenticator implements IUserAuthenticator { return prompt; } - @Override + @Override public boolean promptForHostKeyChange(ICVSRepositoryLocation location) { - return false; - } + return false; + } @Override public Map<ICVSRepositoryLocation, List<String>> promptToConfigureRepositoryLocations(Map<ICVSRepositoryLocation, List<String>> alternativeMap) { diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/compatible/AllTestsCompatibility.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/compatible/AllTestsCompatibility.java index 9e8a9592b..75ba49ab2 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/compatible/AllTestsCompatibility.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/compatible/AllTestsCompatibility.java @@ -22,7 +22,7 @@ public class AllTestsCompatibility extends TestSuite { suite.addTest(BasicTest.suite()); suite.addTest(ConflictTest.suite()); suite.addTest(ModuleTest.suite()); - return new CompatibleTestSetup(suite); + return new CompatibleTestSetup(suite); } public AllTestsCompatibility(String name) { diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/AllTestsCVSResources.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/AllTestsCVSResources.java index 8490b1c76..c1d76e126 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/AllTestsCVSResources.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/AllTestsCVSResources.java @@ -24,7 +24,7 @@ public class AllTestsCVSResources extends EclipseTest { suite.addTest(EclipseFolderTest.suite()); suite.addTest(ResourceSyncBytesTest.suite()); suite.addTest(CVSURITest.suite()); - return suite; + return suite; } public AllTestsCVSResources(String name) { diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/ResourceSyncInfoTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/ResourceSyncInfoTest.java index 2104dfcc8..7fe12176f 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/ResourceSyncInfoTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/cvsresources/ResourceSyncInfoTest.java @@ -183,22 +183,22 @@ public class ResourceSyncInfoTest extends EclipseTest { } public void testRepositoryLocationFormats() throws CVSException { - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@host:/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user:password@host:/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:host:/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@host:1234/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user:password@host:1234/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:host:1234/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@host/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user:password@host/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:host/home/path"), "/home/path"); - assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@domain:password@host/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@host:/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user:password@host:/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:host:/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@host:1234/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user:password@host:1234/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:host:1234/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@host/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user:password@host/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:host/home/path"), "/home/path"); + assertPathCorrect(CVSRepositoryLocation.fromString(":pserver:user@domain:password@host/home/path"), "/home/path"); } - private void assertPathCorrect(CVSRepositoryLocation location, String string) throws CVSException { - assertEquals(location.getRootDirectory(), string); - FolderSyncInfo info = new FolderSyncInfo("childPath", location.getLocation(), null, false); - assertEquals(info.getRemoteLocation(), string + '/' + "childPath"); - - } + private void assertPathCorrect(CVSRepositoryLocation location, String string) throws CVSException { + assertEquals(location.getRootDirectory(), string); + FolderSyncInfo info = new FolderSyncInfo("childPath", location.getLocation(), null, false); + assertEquals(info.getRemoteLocation(), string + '/' + "childPath"); + + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/ResourceMapperTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/ResourceMapperTests.java index 433c56932..6194cc4b6 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/ResourceMapperTests.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/ResourceMapperTests.java @@ -79,369 +79,369 @@ import junit.framework.Test; public class ResourceMapperTests extends EclipseTest { - public ResourceMapperTests() { - super(); - } - - public ResourceMapperTests(String name) { - super(name); - } - - public static Test suite() { - return suite(ResourceMapperTests.class); - } - - /** - * Update the resources contained in the given mappers and ensure that the - * update was performed properly by comparing the result with the reference projects. - * @throws Exception - */ - protected void update(ResourceMapping mapper, LocalOption[] options) throws Exception { - SyncInfoTree incomingSet = getIncoming(mapper.getProjects()); - update(new ResourceMapping[] { mapper }, options); - assertUpdate(mapper, incomingSet); - } - - /** - * Replace the resources contained in the given mappers and ensure that the - * update was performed properly by comparing the result with the reference projects. - * @throws Exception - */ - protected void replace(ResourceMapping mapper) throws Exception { - SyncInfoTree incomingSet = getIncoming(mapper.getProjects()); - replace(new ResourceMapping[] { mapper }); - assertUpdate(mapper, incomingSet); - } - - /** - * Commit and check that all resources in containing project that should have been committed were and - * that any not contained by the mappers were not. - * @throws CoreException - * @see org.eclipse.team.tests.ccvs.core.EclipseTest#commit(org.eclipse.core.resources.mapping.IResourceMapper[], java.lang.String) - */ - protected void commit(ResourceMapping mapper, String message) throws CoreException { - SyncInfoTree set = getOutgoing(mapper.getProjects()); - commit(new ResourceMapping[] { mapper }, message); - assertCommit(mapper, set); - } - - /** - * Tag the given resource mappings and assert that only the resources - * within the mapping were tagged. - * @throws CoreException - */ - protected void tag(ResourceMapping mapping, CVSTag tag) throws CoreException { - tag(new ResourceMapping[] { mapping }, tag, false); - assertTagged(mapping, tag); - } - - /** - * Branch the resources in the given mapping. - * @throws CoreException - * @throws IOException - */ - protected void branch(ResourceMapping mapping, CVSTag branch) throws CoreException, IOException { - CVSTag version = new CVSTag("Root_" + branch.getName(), CVSTag.VERSION); - branch(new ResourceMapping[] { mapping }, version, branch, true /* update */); - assertTagged(mapping, version); - assertBranched(mapping, branch); - } - - /** - * Add any resources contained by the mapping - * @param mapping - * @throws CoreException - */ - protected void add(ResourceMapping mapping) throws CoreException { - SyncInfoTree set = getUnaddedResource(mapping); - add(new ResourceMapping[] { mapping }); - assertAdded(mapping, set); - } - - private void assertAdded(ResourceMapping mapping, final SyncInfoTree set) throws CoreException { - // Assert that all resources covered by the mapping are now under version control (i.e. are in-sync) - // Remove the resources contained in the mapping from the set of unadded resources. - visit(mapping, ResourceMappingContext.LOCAL_CONTEXT, (IResourceVisitor) resource -> { - ICVSResource cvsResource = getCVSResource(resource); - assertTrue("Resource was not added but should have been: " + resource.getFullPath(), - (cvsResource.isManaged() - || (cvsResource.isFolder() - && ((ICVSFolder)cvsResource).isCVSFolder()))); - set.remove(resource); - return true; + public ResourceMapperTests() { + super(); + } + + public ResourceMapperTests(String name) { + super(name); + } + + public static Test suite() { + return suite(ResourceMapperTests.class); + } + + /** + * Update the resources contained in the given mappers and ensure that the + * update was performed properly by comparing the result with the reference projects. + * @throws Exception + */ + protected void update(ResourceMapping mapper, LocalOption[] options) throws Exception { + SyncInfoTree incomingSet = getIncoming(mapper.getProjects()); + update(new ResourceMapping[] { mapper }, options); + assertUpdate(mapper, incomingSet); + } + + /** + * Replace the resources contained in the given mappers and ensure that the + * update was performed properly by comparing the result with the reference projects. + * @throws Exception + */ + protected void replace(ResourceMapping mapper) throws Exception { + SyncInfoTree incomingSet = getIncoming(mapper.getProjects()); + replace(new ResourceMapping[] { mapper }); + assertUpdate(mapper, incomingSet); + } + + /** + * Commit and check that all resources in containing project that should have been committed were and + * that any not contained by the mappers were not. + * @throws CoreException + * @see org.eclipse.team.tests.ccvs.core.EclipseTest#commit(org.eclipse.core.resources.mapping.IResourceMapper[], java.lang.String) + */ + protected void commit(ResourceMapping mapper, String message) throws CoreException { + SyncInfoTree set = getOutgoing(mapper.getProjects()); + commit(new ResourceMapping[] { mapper }, message); + assertCommit(mapper, set); + } + + /** + * Tag the given resource mappings and assert that only the resources + * within the mapping were tagged. + * @throws CoreException + */ + protected void tag(ResourceMapping mapping, CVSTag tag) throws CoreException { + tag(new ResourceMapping[] { mapping }, tag, false); + assertTagged(mapping, tag); + } + + /** + * Branch the resources in the given mapping. + * @throws CoreException + * @throws IOException + */ + protected void branch(ResourceMapping mapping, CVSTag branch) throws CoreException, IOException { + CVSTag version = new CVSTag("Root_" + branch.getName(), CVSTag.VERSION); + branch(new ResourceMapping[] { mapping }, version, branch, true /* update */); + assertTagged(mapping, version); + assertBranched(mapping, branch); + } + + /** + * Add any resources contained by the mapping + * @param mapping + * @throws CoreException + */ + protected void add(ResourceMapping mapping) throws CoreException { + SyncInfoTree set = getUnaddedResource(mapping); + add(new ResourceMapping[] { mapping }); + assertAdded(mapping, set); + } + + private void assertAdded(ResourceMapping mapping, final SyncInfoTree set) throws CoreException { + // Assert that all resources covered by the mapping are now under version control (i.e. are in-sync) + // Remove the resources contained in the mapping from the set of unadded resources. + visit(mapping, ResourceMappingContext.LOCAL_CONTEXT, (IResourceVisitor) resource -> { + ICVSResource cvsResource = getCVSResource(resource); + assertTrue("Resource was not added but should have been: " + resource.getFullPath(), + (cvsResource.isManaged() + || (cvsResource.isFolder() + && ((ICVSFolder)cvsResource).isCVSFolder()))); + set.remove(resource); + return true; }); - // Assert that the remaining unadded resources are still unadded - SyncInfo[] infos = set.getSyncInfos(); - for (SyncInfo info : infos) { - ICVSResource cvsResource = getCVSResource(info.getLocal()); - assertTrue("Resource was added but should not have been: " + info.getLocal().getFullPath(), !cvsResource.isManaged()); - } - } - - /* - * Need to ensure that only the resources contained in the mapping - * have the branch tag associated with them. - */ + // Assert that the remaining unadded resources are still unadded + SyncInfo[] infos = set.getSyncInfos(); + for (SyncInfo info : infos) { + ICVSResource cvsResource = getCVSResource(info.getLocal()); + assertTrue("Resource was added but should not have been: " + info.getLocal().getFullPath(), !cvsResource.isManaged()); + } + } + + /* + * Need to ensure that only the resources contained in the mapping + * have the branch tag associated with them. + */ private void assertBranched(ResourceMapping mapping, CVSTag branch) throws CoreException { - // First, make sure the proper resources are tagged in the repo - assertTagged(mapping, branch); - // Now make sure the proper local files are tagged + // First, make sure the proper resources are tagged in the repo + assertTagged(mapping, branch); + // Now make sure the proper local files are tagged final Map<String, ICVSResource> remotes = getTaggedRemoteFilesByPath(mapping, branch); final Map<String, ICVSFile> locals = getTaggedLocalFilesByPath(mapping, branch); for (Iterator<String> iter = remotes.keySet().iterator(); iter.hasNext();) { - String key = iter.next(); - ICVSRemoteFile remote = (ICVSRemoteFile)remotes.get(key); - ICVSFile local = locals.get(key); - assertNotNull("Remotely tagged resource was not tagged locally: " + remote.getRepositoryRelativePath(), local); - assertEquals(local.getIResource().getParent().getFullPath(), remote, local, false, false /* include tags */); - assertEquals("Remotely tagged resource was not tagged locally: " + remote.getRepositoryRelativePath(), branch, local.getSyncInfo().getTag()); - locals.remove(key); - iter.remove(); - } - // The remote map should be empty after traversal - for (Object element : remotes.keySet()) { - String path = (String) element; - fail("Remote file " + path + " was tagged remotely but not locally."); - } - // The local map should be empty after traversal - for (Object element : locals.keySet()) { - String path = (String) element; - fail("Local file " + path + " was tagged locally but not remotely."); - } - } - - private void assertTagged(ResourceMapping mapping, final CVSTag tag) throws CoreException { + String key = iter.next(); + ICVSRemoteFile remote = (ICVSRemoteFile)remotes.get(key); + ICVSFile local = locals.get(key); + assertNotNull("Remotely tagged resource was not tagged locally: " + remote.getRepositoryRelativePath(), local); + assertEquals(local.getIResource().getParent().getFullPath(), remote, local, false, false /* include tags */); + assertEquals("Remotely tagged resource was not tagged locally: " + remote.getRepositoryRelativePath(), branch, local.getSyncInfo().getTag()); + locals.remove(key); + iter.remove(); + } + // The remote map should be empty after traversal + for (Object element : remotes.keySet()) { + String path = (String) element; + fail("Remote file " + path + " was tagged remotely but not locally."); + } + // The local map should be empty after traversal + for (Object element : locals.keySet()) { + String path = (String) element; + fail("Local file " + path + " was tagged locally but not remotely."); + } + } + + private void assertTagged(ResourceMapping mapping, final CVSTag tag) throws CoreException { final Map<String, ICVSResource> tagged = getTaggedRemoteFilesByPath(mapping, tag); - // Visit all the resources in the traversal and ensure that they are tagged - visit(mapping, ResourceMappingContext.LOCAL_CONTEXT, (IResourceVisitor) resource -> { - if (resource.getType() == IResource.FILE) { - ICVSRemoteFile file = popRemote(resource, tagged); - assertNotNull("Resource was not tagged: " + resource.getFullPath(), file); - } - return true; + // Visit all the resources in the traversal and ensure that they are tagged + visit(mapping, ResourceMappingContext.LOCAL_CONTEXT, (IResourceVisitor) resource -> { + if (resource.getType() == IResource.FILE) { + ICVSRemoteFile file = popRemote(resource, tagged); + assertNotNull("Resource was not tagged: " + resource.getFullPath(), file); + } + return true; }); - + for (String path : tagged.keySet()) { - fail("Remote file " + path + " was tagged but should not have been."); + fail("Remote file " + path + " was tagged but should not have been."); } - } + } private Map<String, ICVSFile> getTaggedLocalFilesByPath(ResourceMapping mapping, final CVSTag branch) throws CoreException { final Map<String, ICVSFile> tagged = new HashMap<>(); - IProject[] projects = mapping.getProjects(); - for (IProject project : projects) { - project.accept(resource -> { - if (resource.getType() == IResource.FILE) { - ICVSFile file = (ICVSFile)getCVSResource(resource); - ResourceSyncInfo info = file.getSyncInfo(); - if (info != null && info.getTag() != null && info.getTag().equals(branch)) { - tagged.put(file.getRepositoryRelativePath(), file); - } - } - return true; + IProject[] projects = mapping.getProjects(); + for (IProject project : projects) { + project.accept(resource -> { + if (resource.getType() == IResource.FILE) { + ICVSFile file = (ICVSFile)getCVSResource(resource); + ResourceSyncInfo info = file.getSyncInfo(); + if (info != null && info.getTag() != null && info.getTag().equals(branch)) { + tagged.put(file.getRepositoryRelativePath(), file); + } + } + return true; }); - } - return tagged; - } - + } + return tagged; + } + private Map<String, ICVSResource> getTaggedRemoteFilesByPath(ResourceMapping mapping, final CVSTag tag) throws CVSException { - IProject[] projects = mapping.getProjects(); - ICVSResource[] remotes = getRemoteTrees(projects, tag); + IProject[] projects = mapping.getProjects(); + ICVSResource[] remotes = getRemoteTrees(projects, tag); final Map<String, ICVSResource> tagged = getFilesByPath(remotes); - return tagged; - } + return tagged; + } - private ICVSResource[] getRemoteTrees(IProject[] projects, CVSTag tag) throws CVSException { + private ICVSResource[] getRemoteTrees(IProject[] projects, CVSTag tag) throws CVSException { List<ICVSResource> result = new ArrayList<>(); - for (IProject project : projects) { - RemoteFolderTree tree = RemoteFolderTreeBuilder.buildRemoteTree(getRepository(), project, tag, DEFAULT_MONITOR); - result.add(tree); - } - return result.toArray(new ICVSResource[result.size()]); - } + for (IProject project : projects) { + RemoteFolderTree tree = RemoteFolderTreeBuilder.buildRemoteTree(getRepository(), project, tag, DEFAULT_MONITOR); + result.add(tree); + } + return result.toArray(new ICVSResource[result.size()]); + } private Map<String, ICVSResource> getFilesByPath(ICVSResource[] remotes) throws CVSException { Map<String, ICVSResource> result = new HashMap<>(); - for (ICVSResource resource : remotes) { - collectFiles(resource, result); - } - return result; - } + for (ICVSResource resource : remotes) { + collectFiles(resource, result); + } + return result; + } private void collectFiles(ICVSResource resource, Map<String, ICVSResource> result) throws CVSException { - if (resource.isFolder()) { - ICVSResource[] members = ((ICVSFolder)resource).members(ICVSFolder.ALL_EXISTING_MEMBERS); - for (ICVSResource member : members) { - collectFiles(member, result); - } - } else { - result.put(resource.getRepositoryRelativePath(), resource); - } - } + if (resource.isFolder()) { + ICVSResource[] members = ((ICVSFolder)resource).members(ICVSFolder.ALL_EXISTING_MEMBERS); + for (ICVSResource member : members) { + collectFiles(member, result); + } + } else { + result.put(resource.getRepositoryRelativePath(), resource); + } + } private ICVSRemoteFile popRemote(IResource resource, Map<String, ICVSResource> tagged) throws CVSException { - ICVSResource cvsResource = getCVSResource(resource); - ICVSRemoteFile remote = (ICVSRemoteFile)tagged.get(cvsResource.getRepositoryRelativePath()); - if (remote != null) { - tagged.remove(remote.getRepositoryRelativePath()); - } - return remote; - } - - private ResourceMapping asResourceMapping(final IResource[] resources, final int depth) { - return new ResourceMapping() { - private Object object = new Object(); - @Override + ICVSResource cvsResource = getCVSResource(resource); + ICVSRemoteFile remote = (ICVSRemoteFile)tagged.get(cvsResource.getRepositoryRelativePath()); + if (remote != null) { + tagged.remove(remote.getRepositoryRelativePath()); + } + return remote; + } + + private ResourceMapping asResourceMapping(final IResource[] resources, final int depth) { + return new ResourceMapping() { + private Object object = new Object(); + @Override public Object getModelObject() { - return object; - } - @Override + return object; + } + @Override public IProject[] getProjects() { - return getProjects(resources); - } - private IProject[] getProjects(IResource[] resources) { + return getProjects(resources); + } + private IProject[] getProjects(IResource[] resources) { Set<IProject> projects = new HashSet<>(); - for (IResource resource : resources) { - projects.add(resource.getProject()); - } - return projects.toArray(new IProject[projects.size()]); - } - @Override + for (IResource resource : resources) { + projects.add(resource.getProject()); + } + return projects.toArray(new IProject[projects.size()]); + } + @Override public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { - return new ResourceTraversal[] { - new ResourceTraversal(resources, depth, IResource.NONE) - }; - } + return new ResourceTraversal[] { + new ResourceTraversal(resources, depth, IResource.NONE) + }; + } @Override public String getModelProviderId() { return "org.eclipse.team.tests.cvs.core.modelProvider"; } - }; - } - - private void assertUpdate(ResourceMapping mapper, final SyncInfoTree set) throws Exception { - final Exception[] exception = new Exception[] { null }; - visit(mapper, new SyncInfoSetTraveralContext(set), (IResourceVisitor) resource -> { - SyncInfo info = set.getSyncInfo(resource); - if (info != null) { - set.remove(resource); - try { - // Assert that the local sync info matches the remote info - assertEquals(resource.getParent().getFullPath(), getCVSResource(resource), (ICVSResource)info.getRemote(), false, false); - } catch (CVSException e1) { - exception[0] = e1; - } catch (CoreException e2) { - exception[0] = e2; - } catch (IOException e3) { - exception[0] = e3; - } - } - return true; + }; + } + + private void assertUpdate(ResourceMapping mapper, final SyncInfoTree set) throws Exception { + final Exception[] exception = new Exception[] { null }; + visit(mapper, new SyncInfoSetTraveralContext(set), (IResourceVisitor) resource -> { + SyncInfo info = set.getSyncInfo(resource); + if (info != null) { + set.remove(resource); + try { + // Assert that the local sync info matches the remote info + assertEquals(resource.getParent().getFullPath(), getCVSResource(resource), (ICVSResource)info.getRemote(), false, false); + } catch (CVSException e1) { + exception[0] = e1; + } catch (CoreException e2) { + exception[0] = e2; + } catch (IOException e3) { + exception[0] = e3; + } + } + return true; }); - if (exception[0] != null) throw exception[0]; - - // check the the state of the remaining resources has not changed - assertUnchanged(set); - } - - private void assertCommit(ResourceMapping mapper, final SyncInfoTree set) throws CoreException { - visit(mapper, new SyncInfoSetTraveralContext(set), (IResourceVisitor) resource -> { - SyncInfo info = set.getSyncInfo(resource); - if (info != null) { - set.remove(resource); - assertTrue("Committed resource is not in-sync: " + resource.getFullPath(), getSyncInfo(resource).getKind() == SyncInfo.IN_SYNC); - } - return true; + if (exception[0] != null) throw exception[0]; + + // check the the state of the remaining resources has not changed + assertUnchanged(set); + } + + private void assertCommit(ResourceMapping mapper, final SyncInfoTree set) throws CoreException { + visit(mapper, new SyncInfoSetTraveralContext(set), (IResourceVisitor) resource -> { + SyncInfo info = set.getSyncInfo(resource); + if (info != null) { + set.remove(resource); + assertTrue("Committed resource is not in-sync: " + resource.getFullPath(), getSyncInfo(resource).getKind() == SyncInfo.IN_SYNC); + } + return true; }); - // check the the state of the remaining resources has not changed - assertUnchanged(set); - } - - /* - * Assert that the state of the resources in the set have not changed - */ - private void assertUnchanged(SyncInfoTree set) throws TeamException { - //TODO: Need to refresh the subscriber since flush of remote state is deep - CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().refresh(set.getResources(), IResource.DEPTH_ZERO, DEFAULT_MONITOR); - SyncInfo[] infos = set.getSyncInfos(); - for (SyncInfo info : infos) { - assertUnchanged(info); - } - } - - private void assertUnchanged(SyncInfo info) throws TeamException { - SyncInfo current = getSyncInfo(info.getLocal()); - assertEquals("The sync info changed for " + info.getLocal().getFullPath(), info, current); - } - - private SyncInfo getSyncInfo(IResource local) throws TeamException { - return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().getSyncInfo(local); - } - - private SyncInfoTree getIncoming(IProject[] projects) throws TeamException { - CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().refresh(projects, IResource.DEPTH_INFINITE, DEFAULT_MONITOR); - SyncInfoTree set = getAllOutOfSync(projects); - set.removeOutgoingNodes(); - set.removeConflictingNodes(); - return set; - } - - private SyncInfoTree getOutgoing(IProject[] projects) { - SyncInfoTree set = getAllOutOfSync(projects); - set.removeIncomingNodes(); - set.removeConflictingNodes(); - return set; - } - - private SyncInfoTree getUnaddedResource(ResourceMapping mapping) { - SyncInfoTree set = getAllOutOfSync(mapping.getProjects()); - set.selectNodes(new FastSyncInfoFilter() { - @Override + // check the the state of the remaining resources has not changed + assertUnchanged(set); + } + + /* + * Assert that the state of the resources in the set have not changed + */ + private void assertUnchanged(SyncInfoTree set) throws TeamException { + //TODO: Need to refresh the subscriber since flush of remote state is deep + CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().refresh(set.getResources(), IResource.DEPTH_ZERO, DEFAULT_MONITOR); + SyncInfo[] infos = set.getSyncInfos(); + for (SyncInfo info : infos) { + assertUnchanged(info); + } + } + + private void assertUnchanged(SyncInfo info) throws TeamException { + SyncInfo current = getSyncInfo(info.getLocal()); + assertEquals("The sync info changed for " + info.getLocal().getFullPath(), info, current); + } + + private SyncInfo getSyncInfo(IResource local) throws TeamException { + return CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().getSyncInfo(local); + } + + private SyncInfoTree getIncoming(IProject[] projects) throws TeamException { + CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().refresh(projects, IResource.DEPTH_INFINITE, DEFAULT_MONITOR); + SyncInfoTree set = getAllOutOfSync(projects); + set.removeOutgoingNodes(); + set.removeConflictingNodes(); + return set; + } + + private SyncInfoTree getOutgoing(IProject[] projects) { + SyncInfoTree set = getAllOutOfSync(projects); + set.removeIncomingNodes(); + set.removeConflictingNodes(); + return set; + } + + private SyncInfoTree getUnaddedResource(ResourceMapping mapping) { + SyncInfoTree set = getAllOutOfSync(mapping.getProjects()); + set.selectNodes(new FastSyncInfoFilter() { + @Override public boolean select(SyncInfo info) { - try { - if (info.getLocal().getType() != IResource.PROJECT && info.getRemote() == null && info.getBase() == null) { - ICVSResource resource = getCVSResource(info.getLocal()); - return !resource.isManaged(); - } - } catch (CVSException e) { - fail(e.getMessage()); - } - return false; - } - }); - return set; - } - - private SyncInfoTree getAllOutOfSync(IProject[] projects) { - SyncInfoTree set = new SyncInfoTree(); - CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().collectOutOfSync(projects, IResource.DEPTH_INFINITE, set, DEFAULT_MONITOR); - return set; - } - - private IResourceDiffTree getAllDiffs(IProject[] projects) throws CoreException { - final ResourceDiffTree tree = new ResourceDiffTree(); - CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().accept(projects, IResource.DEPTH_INFINITE, delta -> { + try { + if (info.getLocal().getType() != IResource.PROJECT && info.getRemote() == null && info.getBase() == null) { + ICVSResource resource = getCVSResource(info.getLocal()); + return !resource.isManaged(); + } + } catch (CVSException e) { + fail(e.getMessage()); + } + return false; + } + }); + return set; + } + + private SyncInfoTree getAllOutOfSync(IProject[] projects) { + SyncInfoTree set = new SyncInfoTree(); + CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().collectOutOfSync(projects, IResource.DEPTH_INFINITE, set, DEFAULT_MONITOR); + return set; + } + + private IResourceDiffTree getAllDiffs(IProject[] projects) throws CoreException { + final ResourceDiffTree tree = new ResourceDiffTree(); + CVSProviderPlugin.getPlugin().getCVSWorkspaceSubscriber().accept(projects, IResource.DEPTH_INFINITE, delta -> { tree.add(delta); return true; }); - return tree; - } - - private void visit(ResourceMapping mapper, ResourceMappingContext context, IResourceVisitor visitor) throws CoreException { - ResourceTraversal[] traversals = mapper.getTraversals(context, null); - for (ResourceTraversal traversal : traversals) { - visit(traversal, context, visitor); - } - } - - private void visit(ResourceTraversal traversal, ResourceMappingContext context, IResourceVisitor visitor) throws CoreException { - IResource[] resources = traversal.getResources(); - for (IResource resource : resources) { - visit(resource, visitor, context, traversal.getDepth()); - } - } + return tree; + } + + private void visit(ResourceMapping mapper, ResourceMappingContext context, IResourceVisitor visitor) throws CoreException { + ResourceTraversal[] traversals = mapper.getTraversals(context, null); + for (ResourceTraversal traversal : traversals) { + visit(traversal, context, visitor); + } + } + + private void visit(ResourceTraversal traversal, ResourceMappingContext context, IResourceVisitor visitor) throws CoreException { + IResource[] resources = traversal.getResources(); + for (IResource resource : resources) { + visit(resource, visitor, context, traversal.getDepth()); + } + } private void visit(IResource resource, IResourceVisitor visitor, ResourceMappingContext context, int depth) throws CoreException { @@ -458,7 +458,7 @@ public class ResourceMapperTests extends EclipseTest { depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : IResource.DEPTH_INFINITE); } } - + private boolean isTimeout(Throwable e) { if (e == null) { return false; @@ -487,34 +487,34 @@ public class ResourceMapperTests extends EclipseTest { return isTimeout(e.getCause()); } - public void testUpdate() throws Exception { - try{ - // Create a test project, import it into cvs and check it out - IProject project = createProject("testUpdate", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + public void testUpdate() throws Exception { + try{ + // Create a test project, import it into cvs and check it out + IProject project = createProject("testUpdate", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - // Check the project out under a different name - IProject copy = checkoutCopy(project, "-copy"); - - // Perform some operations on the copy and commit them all - addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false); - setContentsAndEnsureModified(copy.getFile("changed.txt")); - deleteResources(new IResource[] {copy.getFile("deleted.txt")}); - setContentsAndEnsureModified(copy.getFile("folder1/a.txt")); - setContentsAndEnsureModified(copy.getFile("folder1/subfolder1/c.txt")); - commit(asResourceMapping(new IResource[] { copy }, IResource.DEPTH_INFINITE), "A commit message"); - - // Update the project using depth one and ensure we got only what was asked for - update(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), null); - - // Update a subfolder using depth one and ensure we got only what was asked for - update(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), null); - - // Update the specific file - update(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), null); - - // Update the remaining resources - update(asResourceMapping(new IResource[] { project.getFolder("folder2") }, IResource.DEPTH_INFINITE), null); - assertEquals(project, copy); + // Check the project out under a different name + IProject copy = checkoutCopy(project, "-copy"); + + // Perform some operations on the copy and commit them all + addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false); + setContentsAndEnsureModified(copy.getFile("changed.txt")); + deleteResources(new IResource[] {copy.getFile("deleted.txt")}); + setContentsAndEnsureModified(copy.getFile("folder1/a.txt")); + setContentsAndEnsureModified(copy.getFile("folder1/subfolder1/c.txt")); + commit(asResourceMapping(new IResource[] { copy }, IResource.DEPTH_INFINITE), "A commit message"); + + // Update the project using depth one and ensure we got only what was asked for + update(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), null); + + // Update a subfolder using depth one and ensure we got only what was asked for + update(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), null); + + // Update the specific file + update(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), null); + + // Update the remaining resources + update(asResourceMapping(new IResource[] { project.getFolder("folder2") }, IResource.DEPTH_INFINITE), null); + assertEquals(project, copy); } catch (Exception e) { if (isTimeout(e)) { //TODO see Bug 399375 @@ -524,37 +524,37 @@ public class ResourceMapperTests extends EclipseTest { } throw e; } - } - - public void testReplace() throws Exception { - try{ - // Create a test project, import it into cvs and check it out - IProject project = createProject("testReplace", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + } + + public void testReplace() throws Exception { + try{ + // Create a test project, import it into cvs and check it out + IProject project = createProject("testReplace", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - // Check the project out under a different name - IProject copy = checkoutCopy(project, "-copy"); - - // Perform some operations on the copy and commit them all - addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false); - setContentsAndEnsureModified(copy.getFile("changed.txt")); - deleteResources(new IResource[] {copy.getFile("deleted.txt")}); - setContentsAndEnsureModified(copy.getFile("folder1/a.txt")); - setContentsAndEnsureModified(copy.getFile("folder1/subfolder1/c.txt")); - commit(asResourceMapping(new IResource[] { copy }, IResource.DEPTH_INFINITE), "A commit message"); - - // Update the project using depth one and ensure we got only what was asked for - replace(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE)); - - // Update a subfolder using depth one and ensure we got only what was asked for - deleteResources(new IResource[] {project.getFile("folder1/b.txt")}); - replace(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE)); - - // Update the specific file - replace(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO)); - - // Update the remaining resources - replace(asResourceMapping(new IResource[] { project.getFolder("folder2") }, IResource.DEPTH_INFINITE)); - assertEquals(project, copy); + // Check the project out under a different name + IProject copy = checkoutCopy(project, "-copy"); + + // Perform some operations on the copy and commit them all + addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false); + setContentsAndEnsureModified(copy.getFile("changed.txt")); + deleteResources(new IResource[] {copy.getFile("deleted.txt")}); + setContentsAndEnsureModified(copy.getFile("folder1/a.txt")); + setContentsAndEnsureModified(copy.getFile("folder1/subfolder1/c.txt")); + commit(asResourceMapping(new IResource[] { copy }, IResource.DEPTH_INFINITE), "A commit message"); + + // Update the project using depth one and ensure we got only what was asked for + replace(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE)); + + // Update a subfolder using depth one and ensure we got only what was asked for + deleteResources(new IResource[] {project.getFile("folder1/b.txt")}); + replace(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE)); + + // Update the specific file + replace(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO)); + + // Update the remaining resources + replace(asResourceMapping(new IResource[] { project.getFolder("folder2") }, IResource.DEPTH_INFINITE)); + assertEquals(project, copy); } catch (Exception e) { if (isTimeout(e)) { //TODO see Bug 399375 @@ -564,100 +564,100 @@ public class ResourceMapperTests extends EclipseTest { } throw e; } - } + } - public void testCommit() throws Exception { + public void testCommit() throws Exception { if (TeamCVSTestPlugin.IS_UNSTABLE_TEST && Util.isMac()) return; - // Create a test project, import it into cvs and check it out - IProject project = createProject("testCommit", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - - // Perform some operations on the copy and commit only the top level - addResources(project, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false); - setContentsAndEnsureModified(project.getFile("changed.txt")); - deleteResources(new IResource[] {project.getFile("deleted.txt")}); - setContentsAndEnsureModified(project.getFile("folder1/a.txt")); - setContentsAndEnsureModified(project.getFile("folder1/subfolder1/c.txt")); - - // Commit the project shallow - commit(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), "A commit message"); - - // Commit a subfolder shallow - commit(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), "A commit message"); - - // Now commit the file specifically - commit(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), "A commit message"); - - // Now commit the rest - commit(asResourceMapping(new IResource[] { project.getFolder("folder2") }, IResource.DEPTH_INFINITE), "A commit message"); - - // Check the project out under a different name - IProject copy = checkoutCopy(project, "-copy"); - assertEquals(project, copy); - } - - public void testTag() throws Exception { - // Create a test project, import it into cvs and check it out - IProject project = createProject("testTag", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - - tag(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), new CVSTag("v1", CVSTag.VERSION)); - tag(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), new CVSTag("v2", CVSTag.VERSION)); - tag(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), new CVSTag("v3", CVSTag.VERSION)); - tag(asResourceMapping(new IResource[] { project}, IResource.DEPTH_INFINITE), new CVSTag("v4", CVSTag.VERSION)); - } - - public void testBranch() throws Exception { + // Create a test project, import it into cvs and check it out + IProject project = createProject("testCommit", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + + // Perform some operations on the copy and commit only the top level + addResources(project, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, false); + setContentsAndEnsureModified(project.getFile("changed.txt")); + deleteResources(new IResource[] {project.getFile("deleted.txt")}); + setContentsAndEnsureModified(project.getFile("folder1/a.txt")); + setContentsAndEnsureModified(project.getFile("folder1/subfolder1/c.txt")); + + // Commit the project shallow + commit(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), "A commit message"); + + // Commit a subfolder shallow + commit(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), "A commit message"); + + // Now commit the file specifically + commit(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), "A commit message"); + + // Now commit the rest + commit(asResourceMapping(new IResource[] { project.getFolder("folder2") }, IResource.DEPTH_INFINITE), "A commit message"); + + // Check the project out under a different name + IProject copy = checkoutCopy(project, "-copy"); + assertEquals(project, copy); + } + + public void testTag() throws Exception { + // Create a test project, import it into cvs and check it out + IProject project = createProject("testTag", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + + tag(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), new CVSTag("v1", CVSTag.VERSION)); + tag(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), new CVSTag("v2", CVSTag.VERSION)); + tag(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), new CVSTag("v3", CVSTag.VERSION)); + tag(asResourceMapping(new IResource[] { project}, IResource.DEPTH_INFINITE), new CVSTag("v4", CVSTag.VERSION)); + } + + public void testBranch() throws Exception { if (TeamCVSTestPlugin.IS_UNSTABLE_TEST) return; - // Create a test project, import it into cvs and check it out - IProject project = createProject("testBranch", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - - branch(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), new CVSTag("b1", CVSTag.BRANCH)); - branch(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), new CVSTag("b2", CVSTag.BRANCH)); - branch(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), new CVSTag("b3", CVSTag.BRANCH)); - branch(asResourceMapping(new IResource[] { project }, IResource.DEPTH_INFINITE), new CVSTag("b4", CVSTag.BRANCH)); - } - - public void testAdd() throws TeamException, CoreException { - // Create an empty project - IProject project = createProject("testAdd", new String[] { }); - // add some resources - buildResources(project, new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }, false); - // add them to CVS - add(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE)); - add(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE)); - add(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO)); - add(asResourceMapping(new IResource[] { project }, IResource.DEPTH_INFINITE)); - } - - public void testCacheBase() throws TeamException, CoreException { + // Create a test project, import it into cvs and check it out + IProject project = createProject("testBranch", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + + branch(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE), new CVSTag("b1", CVSTag.BRANCH)); + branch(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE), new CVSTag("b2", CVSTag.BRANCH)); + branch(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO), new CVSTag("b3", CVSTag.BRANCH)); + branch(asResourceMapping(new IResource[] { project }, IResource.DEPTH_INFINITE), new CVSTag("b4", CVSTag.BRANCH)); + } + + public void testAdd() throws TeamException, CoreException { + // Create an empty project + IProject project = createProject("testAdd", new String[] { }); + // add some resources + buildResources(project, new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }, false); + // add them to CVS + add(asResourceMapping(new IResource[] { project }, IResource.DEPTH_ONE)); + add(asResourceMapping(new IResource[] { project.getFolder("folder1") }, IResource.DEPTH_ONE)); + add(asResourceMapping(new IResource[] { project.getFile("folder1/subfolder1/c.txt") }, IResource.DEPTH_ZERO)); + add(asResourceMapping(new IResource[] { project }, IResource.DEPTH_INFINITE)); + } + + public void testCacheBase() throws TeamException, CoreException { if (TeamCVSTestPlugin.IS_UNSTABLE_TEST && Util.isMac()) return; - IProject project = createProject("testCacheBase", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - IProject copy = checkoutCopy(project, "-copy"); - - // First, make some local changes and then cache the bases - setContentsAndEnsureModified(project.getFile("changed.txt"), "Uncommitted text"); - setContentsAndEnsureModified(project.getFile("folder1/b.txt")); - project.getFile("deleted.txt").delete(false, true, null); - try { - cacheBase(project, true /* cache for outgoing and conflicting */); - cacheBase(project, false /* cache for conflicting only*/); - - // Next, retry after releasing some changes (to ensure proper contents are fetched) - setContentsAndEnsureModified(copy.getFile("changed.txt"), "Text comited from the copy"); - commitProject(copy); - cacheBase(project, true /* cache for outgoing and conflicting */); - cacheBase(project, false /* cache for conflicting only */); - } catch (TeamException e) { - // see bug 325553 - logIfCausedByInterruptedIOException(e); - } - } + IProject project = createProject("testCacheBase", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + IProject copy = checkoutCopy(project, "-copy"); + + // First, make some local changes and then cache the bases + setContentsAndEnsureModified(project.getFile("changed.txt"), "Uncommitted text"); + setContentsAndEnsureModified(project.getFile("folder1/b.txt")); + project.getFile("deleted.txt").delete(false, true, null); + try { + cacheBase(project, true /* cache for outgoing and conflicting */); + cacheBase(project, false /* cache for conflicting only*/); + + // Next, retry after releasing some changes (to ensure proper contents are fetched) + setContentsAndEnsureModified(copy.getFile("changed.txt"), "Text comited from the copy"); + commitProject(copy); + cacheBase(project, true /* cache for outgoing and conflicting */); + cacheBase(project, false /* cache for conflicting only */); + } catch (TeamException e) { + // see bug 325553 + logIfCausedByInterruptedIOException(e); + } + } private void logIfCausedByInterruptedIOException(TeamException e) throws TeamException { @@ -683,18 +683,18 @@ public class ResourceMapperTests extends EclipseTest { throw e; } - public void testCacheRemote() throws TeamException, CoreException { - IProject project = createProject("testCacheRemote", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); - IProject copy = checkoutCopy(project, "-copy"); - - // Make some remote changes - setContentsAndEnsureModified(copy.getFile("changed.txt"), "Uncommitted text"); - setContentsAndEnsureModified(copy.getFile("folder1/b.txt")); - commitProject(copy); - // Delete a local file - project.getFile("deleted.txt").delete(false, true, null); - cacheRemote(project); - } + public void testCacheRemote() throws TeamException, CoreException { + IProject project = createProject("testCacheRemote", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder1/subfolder1/c.txt" }); + IProject copy = checkoutCopy(project, "-copy"); + + // Make some remote changes + setContentsAndEnsureModified(copy.getFile("changed.txt"), "Uncommitted text"); + setContentsAndEnsureModified(copy.getFile("folder1/b.txt")); + commitProject(copy); + // Delete a local file + project.getFile("deleted.txt").delete(false, true, null); + cacheRemote(project); + } private void cacheRemote(IProject project) throws CoreException { clearCache(project); @@ -779,35 +779,35 @@ public class ResourceMapperTests extends EclipseTest { } } } - + public void testBug134517() throws Exception { - IProject project = createProject("testBug134517", new String[] { "file1.txt", "file2.txt"}); - IProject copy = checkoutCopy(project, "-copy"); - addResources(copy, new String[] { "file0.txt", - "new_folder1/", "new_folder1/file2.txt", "new_folder1/new_folder2/", - "new_folder1/new_folder2/new_folder3/", "new_folder1/new_folder2/new_folder3/file3.txt" }, true); - IResource[] resources = new IResource[] { - project.getFile("file0.txt"), - project.getFile("file1.txt"), - project.getFile("new_folder1/file2.txt"), - project.getFile("new_folder1/new_folder2/new_folder3/file3.txt") - }; - update(asResourceMapping(resources, IResource.DEPTH_ZERO), null); - assertEquals(project, copy); + IProject project = createProject("testBug134517", new String[] { "file1.txt", "file2.txt"}); + IProject copy = checkoutCopy(project, "-copy"); + addResources(copy, new String[] { "file0.txt", + "new_folder1/", "new_folder1/file2.txt", "new_folder1/new_folder2/", + "new_folder1/new_folder2/new_folder3/", "new_folder1/new_folder2/new_folder3/file3.txt" }, true); + IResource[] resources = new IResource[] { + project.getFile("file0.txt"), + project.getFile("file1.txt"), + project.getFile("new_folder1/file2.txt"), + project.getFile("new_folder1/new_folder2/new_folder3/file3.txt") + }; + update(asResourceMapping(resources, IResource.DEPTH_ZERO), null); + assertEquals(project, copy); } public void testDeepNewFolder() throws Exception { - IProject project = createProject("testBug134517", new String[] { "file1.txt", "file2.txt"}); - IProject copy = checkoutCopy(project, "-copy"); - addResources(copy, new String[] { - "new_folder1/", - "new_folder1/new_folder2/", - "new_folder1/new_folder2/new_folder3/", - "new_folder1/new_folder2/new_folder3/file3.txt" }, true); - IResource[] resources = new IResource[] { - project.getFolder("new_folder1/new_folder2/new_folder3/") - }; - update(asResourceMapping(resources, IResource.DEPTH_INFINITE), null); - assertEquals(project, copy); + IProject project = createProject("testBug134517", new String[] { "file1.txt", "file2.txt"}); + IProject copy = checkoutCopy(project, "-copy"); + addResources(copy, new String[] { + "new_folder1/", + "new_folder1/new_folder2/", + "new_folder1/new_folder2/new_folder3/", + "new_folder1/new_folder2/new_folder3/file3.txt" }, true); + IResource[] resources = new IResource[] { + project.getFolder("new_folder1/new_folder2/new_folder3/") + }; + update(asResourceMapping(resources, IResource.DEPTH_INFINITE), null); + assertEquals(project, copy); } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/SyncInfoSetTraveralContext.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/SyncInfoSetTraveralContext.java index 2345e6638..8ca792e84 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/SyncInfoSetTraveralContext.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/mappings/SyncInfoSetTraveralContext.java @@ -39,45 +39,45 @@ import org.eclipse.team.core.variants.IResourceVariant; * locally. */ public class SyncInfoSetTraveralContext extends RemoteResourceMappingContext { - - SyncInfoTree set; - - public SyncInfoSetTraveralContext(SyncInfoSet set) { - this.set = new SyncInfoTree(); - this.set.addAll(set); - } + + SyncInfoTree set; + + public SyncInfoSetTraveralContext(SyncInfoSet set) { + this.set = new SyncInfoTree(); + this.set.addAll(set); + } - protected SyncInfo getSyncInfo(IFile file) { - return set.getSyncInfo(file); - } - - public boolean contentDiffers(IFile file, IProgressMonitor monitor) { - return getSyncInfo(file) != null; - } + protected SyncInfo getSyncInfo(IFile file) { + return set.getSyncInfo(file); + } + + public boolean contentDiffers(IFile file, IProgressMonitor monitor) { + return getSyncInfo(file) != null; + } - @Override + @Override public IStorage fetchRemoteContents(IFile file, IProgressMonitor monitor) throws CoreException { - SyncInfo info = getSyncInfo(file); - if (info == null) - return null; - IResourceVariant remote = info.getRemote(); - if (remote == null) - return null; - return remote.getStorage(monitor); - } + SyncInfo info = getSyncInfo(file); + if (info == null) + return null; + IResourceVariant remote = info.getRemote(); + if (remote == null) + return null; + return remote.getStorage(monitor); + } - @Override + @Override public IResource[] fetchMembers(IContainer container, IProgressMonitor monitor) throws CoreException { Set<IResource> members = new HashSet<>(); - members.addAll(Arrays.asList(container.members(false))); - members.addAll(Arrays.asList(set.members(container))); - return members.toArray(new IResource[members.size()]); - } + members.addAll(Arrays.asList(container.members(false))); + members.addAll(Arrays.asList(set.members(container))); + return members.toArray(new IResource[members.size()]); + } - @Override + @Override public void refresh(ResourceTraversal[] traversals, int flags, IProgressMonitor monitor) throws CoreException { - // Do nothing - } + // Do nothing + } @Override public boolean isThreeWay() { @@ -105,13 +105,13 @@ public class SyncInfoSetTraveralContext extends RemoteResourceMappingContext { @Override public IStorage fetchBaseContents(IFile file, IProgressMonitor monitor) throws CoreException { - SyncInfo info = getSyncInfo(file); - if (info == null) - return null; - IResourceVariant base = info.getBase(); - if (base == null) - return null; - return base.getStorage(monitor); + SyncInfo info = getSyncInfo(file); + if (info == null) + return null; + IResourceVariant base = info.getBase(); + if (base == null) + return null; + return base.getStorage(monitor); } @Override diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/CVSProviderTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/CVSProviderTest.java index ee22b33aa..c78911653 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/CVSProviderTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/CVSProviderTest.java @@ -513,13 +513,13 @@ public class CVSProviderTest extends EclipseTest { IProject project = createProject("test33984", new String[] { "a.txt", "b.txt" }); setContentsAndEnsureModified(project.getFile("a.txt"), "line 1"); - setContentsAndEnsureModified(project.getFile("b.txt"), ("line 1" + EOL + "line 2" + EOL + "line3")); + setContentsAndEnsureModified(project.getFile("b.txt"), ("line 1" + EOL + "line 2" + EOL + "line3")); Map<IFile, KSubstOption> kMode = new HashMap<>(); kMode.put(project.getFile("a.txt"), Command.KSUBST_TEXT); kMode.put(project.getFile("b.txt"), Command.KSUBST_TEXT); getProvider(project).setKeywordSubstitution(kMode, "", null); - + commitProject(project); @@ -531,7 +531,7 @@ public class CVSProviderTest extends EclipseTest { // TEST 1: simulate modifying same file by different users // b.txt has non-conflicting changes setContentsAndEnsureModified(copy.getFile("b.txt"), ("line 1a" + EOL + "line 2" + EOL + "line3")); - + commitProject(copy); // user updates which would cause a merge with conflict, a commit should not be allowed @@ -542,7 +542,7 @@ public class CVSProviderTest extends EclipseTest { // TEST 2: a.txt has conflicting changes setContentsAndEnsureModified(copy.getFile("a.txt"), "line 1dfgdfne3"); - + commitProject(copy); // user updates which would cause a merge with conflict, a commit should not be allowed @@ -591,7 +591,7 @@ public class CVSProviderTest extends EclipseTest { assertTrue(status.isOK()); } - private IStatus executeCommand(IProject project, Update update, LocalOption[] options) throws CVSException { + private IStatus executeCommand(IProject project, Update update, LocalOption[] options) throws CVSException { Session session = new Session(getRepository(), CVSWorkspaceRoot.getCVSFolderFor(project)); session.open(DEFAULT_MONITOR); try { @@ -607,81 +607,81 @@ public class CVSProviderTest extends EclipseTest { } } - + private void setOnlyLookAtTimestamps(boolean b) { CVSUIPlugin.getPlugin().getPreferenceStore().setValue(ICVSUIConstants.PREF_CONSIDER_CONTENTS, !b); } - public void testUpdateWithNoChange() throws TeamException, CoreException { - IProject project = createProject(new String[] { "a.txt"}); - setContentsAndEnsureModified(project.getFile("a.txt"), "contents"); - commitProject(project); - setOnlyLookAtTimestamps(true); - // set the contents to the same value but ensure the local timestamp is different - setContentsAndEnsureModified(project.getFile("a.txt"), "contents"); - // Update and ensure file timestamp is what is was before out edit - updateProject(project, null, false); - Date modDate = CVSWorkspaceRoot.getCVSFileFor(project.getFile("a.txt")).getSyncInfo().getTimeStamp(); - assertEquals("Timestamp was not properly reset", modDate, CVSWorkspaceRoot.getCVSFileFor(project.getFile("a.txt")).getTimeStamp()); - setOnlyLookAtTimestamps(false); - } - - public void testBinaryAddition() throws CoreException { - // See bug 132255 - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); - IProject copy = checkoutCopy(project, "-copy"); - create(copy.getFile("binaryFile"), true); - setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { copy.getFile("binaryFile") }); - commitProject(copy); - updateProject(project, null, false); - assertContentsEqual(copy.getFile("binaryFile"), project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } - - public void testDeletedPhantom139250() throws CoreException { - IProject project = createProject(new String[] { "a.txt"}); - // Create a phantom folder that is mapped to a remote folder - // but for which no remote exists - ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project.getFolder("phantom")); - ICVSFolder projectFolder = CVSWorkspaceRoot.getCVSFolderFor(project); - FolderSyncInfo projectInfo = projectFolder.getFolderSyncInfo(); - String repo = Util.appendPath(projectInfo.getRepository(), "phantom"); - FolderSyncInfo info = new FolderSyncInfo(repo, projectInfo.getRoot(), projectInfo.getTag(), false); - folder.setFolderSyncInfo(info); - updateProject(project, null, false); - } - - public void testUpdateOfDeletedFile140007() throws CoreException { - IProject project = createProject(new String[] { "a.txt"}); - IProject copy = checkoutCopy(project, "-copy"); - deleteResources(copy, new String[] { "a.txt"}, true); - updateResources(project, new String[] { "a.txt"}, false); - } - - public void testUpdateOfRemotelyRemovedFile() throws CoreException, IOException { - IProject project = createProject(new String[] { "a.txt"}); - IProject copy = checkoutCopy(project, "-copy"); - //Create a file and add it to version control (but don't commit) - addResources(copy, new String[] { "b.txt"}, false); - // Change the revision of the file so it appears to exist remotely - ICVSFile file = CVSWorkspaceRoot.getCVSFileFor(copy.getFile("b.txt")); - byte[] syncBytes = file.getSyncBytes(); - syncBytes = ResourceSyncInfo.setRevision(syncBytes, "1.1"); - file.setSyncBytes(syncBytes, ICVSFile.UNKNOWN); - file.checkedIn(null, true); - // Update the project and verify that the file gets removed - updateProject(copy, null, false); - assertEquals(project, copy); - - } - - public void testMergeWithTrailingLineFeeds() throws CoreException, IOException { + public void testUpdateWithNoChange() throws TeamException, CoreException { + IProject project = createProject(new String[] { "a.txt"}); + setContentsAndEnsureModified(project.getFile("a.txt"), "contents"); + commitProject(project); + setOnlyLookAtTimestamps(true); + // set the contents to the same value but ensure the local timestamp is different + setContentsAndEnsureModified(project.getFile("a.txt"), "contents"); + // Update and ensure file timestamp is what is was before out edit + updateProject(project, null, false); + Date modDate = CVSWorkspaceRoot.getCVSFileFor(project.getFile("a.txt")).getSyncInfo().getTimeStamp(); + assertEquals("Timestamp was not properly reset", modDate, CVSWorkspaceRoot.getCVSFileFor(project.getFile("a.txt")).getTimeStamp()); + setOnlyLookAtTimestamps(false); + } + + public void testBinaryAddition() throws CoreException { + // See bug 132255 + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); + IProject copy = checkoutCopy(project, "-copy"); + create(copy.getFile("binaryFile"), true); + setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { copy.getFile("binaryFile") }); + commitProject(copy); + updateProject(project, null, false); + assertContentsEqual(copy.getFile("binaryFile"), project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } + + public void testDeletedPhantom139250() throws CoreException { + IProject project = createProject(new String[] { "a.txt"}); + // Create a phantom folder that is mapped to a remote folder + // but for which no remote exists + ICVSFolder folder = CVSWorkspaceRoot.getCVSFolderFor(project.getFolder("phantom")); + ICVSFolder projectFolder = CVSWorkspaceRoot.getCVSFolderFor(project); + FolderSyncInfo projectInfo = projectFolder.getFolderSyncInfo(); + String repo = Util.appendPath(projectInfo.getRepository(), "phantom"); + FolderSyncInfo info = new FolderSyncInfo(repo, projectInfo.getRoot(), projectInfo.getTag(), false); + folder.setFolderSyncInfo(info); + updateProject(project, null, false); + } + + public void testUpdateOfDeletedFile140007() throws CoreException { + IProject project = createProject(new String[] { "a.txt"}); + IProject copy = checkoutCopy(project, "-copy"); + deleteResources(copy, new String[] { "a.txt"}, true); + updateResources(project, new String[] { "a.txt"}, false); + } + + public void testUpdateOfRemotelyRemovedFile() throws CoreException, IOException { + IProject project = createProject(new String[] { "a.txt"}); + IProject copy = checkoutCopy(project, "-copy"); + //Create a file and add it to version control (but don't commit) + addResources(copy, new String[] { "b.txt"}, false); + // Change the revision of the file so it appears to exist remotely + ICVSFile file = CVSWorkspaceRoot.getCVSFileFor(copy.getFile("b.txt")); + byte[] syncBytes = file.getSyncBytes(); + syncBytes = ResourceSyncInfo.setRevision(syncBytes, "1.1"); + file.setSyncBytes(syncBytes, ICVSFile.UNKNOWN); + file.checkedIn(null, true); + // Update the project and verify that the file gets removed + updateProject(copy, null, false); + assertEquals(project, copy); + + } + + public void testMergeWithTrailingLineFeeds() throws CoreException, IOException { IProject project = createProject("testFileConflict", new String[] { "file1.txt"}); // Set the contents of file1.txt to ensure proper merging // Ensure there is a trailing LF @@ -701,56 +701,56 @@ public class CVSProviderTest extends EclipseTest { assertTrue("File contents are not correct after merge", compareContent( new ByteArrayInputStream(("line0" + eol + "line1" + eol + "line2" + eol + "line2.5" + eol + "line3" + eol).getBytes()), project.getFile("file1.txt").getContents())); - } - - public void testRevertToBaseHeadTag() throws CoreException, IOException{ - IProject project = createProject("testRevertToBase", new String[] {"file1.txt"}); - setContentsAndEnsureModified(project.getFile("file1.txt"), "line1" + eol + "line2" + eol + "line3" + eol); - commitProject(project); - IProject copy = checkoutCopy(project, "-copy"); - appendText(project.getFile("file1.txt"), "line0" + eol, true); - updateProject(project, CVSTag.BASE, true); - assertTrue("File has changed after revert to base", - compareContent(new ByteArrayInputStream(("line1" + eol + "line2" + eol + "line3" + eol).getBytes()), - project.getFile("file1.txt").getContents())); - assertEquals(getRepositoryProvider(copy), getRepositoryProvider(project), false, true); - } - - private CVSTeamProvider getRepositoryProvider(IProject project) { + } + + public void testRevertToBaseHeadTag() throws CoreException, IOException{ + IProject project = createProject("testRevertToBase", new String[] {"file1.txt"}); + setContentsAndEnsureModified(project.getFile("file1.txt"), "line1" + eol + "line2" + eol + "line3" + eol); + commitProject(project); + IProject copy = checkoutCopy(project, "-copy"); + appendText(project.getFile("file1.txt"), "line0" + eol, true); + updateProject(project, CVSTag.BASE, true); + assertTrue("File has changed after revert to base", + compareContent(new ByteArrayInputStream(("line1" + eol + "line2" + eol + "line3" + eol).getBytes()), + project.getFile("file1.txt").getContents())); + assertEquals(getRepositoryProvider(copy), getRepositoryProvider(project), false, true); + } + + private CVSTeamProvider getRepositoryProvider(IProject project) { return (CVSTeamProvider)RepositoryProvider.getProvider(project); } public void testRevertToBaseNonHeadTag() throws CoreException, IOException{ - IProject project = createProject("testRevertToBaseNonHead", new String[] {"file1.txt"}); - setContentsAndEnsureModified(project.getFile("file1.txt"), "line1" + eol + "line2" + eol); - commitProject(project); - tagProject(project, new CVSTag("testtag", CVSTag.BRANCH), true); - appendText(project.getFile("file1.txt"), "line3" + eol, true); - commitProject(project); - IProject copy = checkoutCopy(project, "-copy"); - appendText(copy.getFile("file1.txt"), "line0" + eol, true); - updateProject(copy, CVSTag.BASE, true); - assertTrue("File has changed after revert to base", - compareContent(new ByteArrayInputStream(("line3" + eol + "line1" + eol + "line2" + eol).getBytes()), - copy.getFile("file1.txt").getContents())); - assertEquals(getRepositoryProvider(project), getRepositoryProvider(copy), false, true); - } - - public void testSwitchTagForModifiedFile()throws CoreException, IOException { - // it's a similar scenario as in https://bugs.eclipse.org/bugs/show_bug.cgi?id=192392 - // create a project - IProject project = createProject("testSwitchTagForModifiedFile", new String[] {"file"}); - commitProject(project); - // tag it - CVSTag tag = new CVSTag("A", CVSTag.BRANCH); - tagProject(project, tag, true); - // modify a file - appendText(project.getFile("file"), "changed in head" + eol, false); - // switch to the tag - updateProject(project, tag, false); - ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(project.getFile("file")); - // we expect the file to have the same tag used when switching - assertEquals(tag, cvsFile.getSyncInfo().getTag()); - } + IProject project = createProject("testRevertToBaseNonHead", new String[] {"file1.txt"}); + setContentsAndEnsureModified(project.getFile("file1.txt"), "line1" + eol + "line2" + eol); + commitProject(project); + tagProject(project, new CVSTag("testtag", CVSTag.BRANCH), true); + appendText(project.getFile("file1.txt"), "line3" + eol, true); + commitProject(project); + IProject copy = checkoutCopy(project, "-copy"); + appendText(copy.getFile("file1.txt"), "line0" + eol, true); + updateProject(copy, CVSTag.BASE, true); + assertTrue("File has changed after revert to base", + compareContent(new ByteArrayInputStream(("line3" + eol + "line1" + eol + "line2" + eol).getBytes()), + copy.getFile("file1.txt").getContents())); + assertEquals(getRepositoryProvider(project), getRepositoryProvider(copy), false, true); + } + + public void testSwitchTagForModifiedFile()throws CoreException, IOException { + // it's a similar scenario as in https://bugs.eclipse.org/bugs/show_bug.cgi?id=192392 + // create a project + IProject project = createProject("testSwitchTagForModifiedFile", new String[] {"file"}); + commitProject(project); + // tag it + CVSTag tag = new CVSTag("A", CVSTag.BRANCH); + tagProject(project, tag, true); + // modify a file + appendText(project.getFile("file"), "changed in head" + eol, false); + // switch to the tag + updateProject(project, tag, false); + ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor(project.getFile("file")); + // we expect the file to have the same tag used when switching + assertEquals(tag, cvsFile.getSyncInfo().getTag()); + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/ImportTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/ImportTest.java index ac5cbb540..1c1a3773f 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/ImportTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/ImportTest.java @@ -136,19 +136,19 @@ public class ImportTest extends EclipseTest { assertEquals(project, copy, true, true); // 1. Delete the project but not it's contents and checkout the project again - waitForDecorator(); + waitForDecorator(); project.delete(false, false, DEFAULT_MONITOR); project = checkoutProject(project, null, null); assertEquals(project, copy, true, true); // 2. Delete the project and its contents and use the module name instead of the project - waitForDecorator(); + waitForDecorator(); project.delete(true, false, DEFAULT_MONITOR); project = checkoutProject(null, project.getName(), null); assertEquals(project, copy, true, true); // 3. Create a project in a custom location and check out over it - waitForDecorator(); + waitForDecorator(); project.delete(true, false, DEFAULT_MONITOR); IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); //desc.setLocation(new Path("C:\\temp\\project")); @@ -157,7 +157,7 @@ public class ImportTest extends EclipseTest { assertEquals(project, copy, true, true); // 4. Checkout something that doesn't contain a .project - waitForDecorator(); + waitForDecorator(); project.delete(true, false, DEFAULT_MONITOR); project = checkoutProject(null, project.getName() + "/folder1", null); //assertEquals(project, copy.getFolder("folder1")); diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/RemoteResourceTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/RemoteResourceTest.java index 98ca3a9b1..691337d83 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/RemoteResourceTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/provider/RemoteResourceTest.java @@ -213,8 +213,8 @@ public class RemoteResourceTest extends EclipseTest { * Test the fetching of the contents of an empty file */ public void testEmptyFile() throws TeamException, CoreException, IOException { - - // Create a project with an empty file + + // Create a project with an empty file IProject project = createProject("testEmptyFile", new String[] { "file.txt"}); IFile file = project.getFile("file.txt"); setContentsAndEnsureModified(file, ""); @@ -227,14 +227,14 @@ public class RemoteResourceTest extends EclipseTest { count++; } assertTrue("Remote file should be empty", count==0); - } - - /* - * Test the fetching of the contents from multiple remote revisions of a file - */ - public void testFileRevisions() throws TeamException, CoreException, IOException { - - // Create a project with an empty file + } + + /* + * Test the fetching of the contents from multiple remote revisions of a file + */ + public void testFileRevisions() throws TeamException, CoreException, IOException { + + // Create a project with an empty file IProject project = createProject("testFileRevisions", new String[] { "file.txt"}); setContentsAndEnsureModified(project.getFile("file.txt"), "hi there"); commitResources(project, new String[] {"file.txt"}); @@ -268,7 +268,7 @@ public class RemoteResourceTest extends EclipseTest { assertEquals("the contents of revision 1.3 are not equal", contents, "bye there"); } } - } + } public void testFileRevisionsForBranches() throws TeamException, CoreException { // Create a project with an empty file @@ -490,21 +490,21 @@ public class RemoteResourceTest extends EclipseTest { assertEquals(CVSTag.VENDOR_REVISION, logEntry.getBranches()[0].getBranchRevision()); } - public void testExists() throws TeamException, CoreException { - IProject project = createProject("testExists", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder2/", "folder2/a.txt", "folder2/folder3/", "folder2/folder3/b.txt", "folder2/folder3/c.txt"}); - ICVSRemoteResource resource1 = CVSWorkspaceRoot.getRemoteResourceFor(project.getFile("file1.txt")); - assertTrue(resource1.exists(DEFAULT_MONITOR)); - ICVSRemoteResource resource2 = CVSWorkspaceRoot.getRemoteResourceFor(project.getFolder("folder2/folder3/")); - assertTrue(resource2.exists(DEFAULT_MONITOR)); - deleteResources(project, new String[] {"file1.txt", "folder2/folder3/b.txt", "folder2/folder3/c.txt" }, true); - assertTrue( ! resource1.exists(DEFAULT_MONITOR)); - assertTrue(resource2.exists(DEFAULT_MONITOR)); - if (CVSTestSetup.INITIALIZE_REPO) { - CVSTestSetup.executeRemoteCommand(getRepository(), "rm -rf " + ((ICVSFolder)resource2).getFolderSyncInfo().getRemoteLocation()); - assertTrue( ! resource2.exists(DEFAULT_MONITOR)); - } - } - + public void testExists() throws TeamException, CoreException { + IProject project = createProject("testExists", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder2/", "folder2/a.txt", "folder2/folder3/", "folder2/folder3/b.txt", "folder2/folder3/c.txt"}); + ICVSRemoteResource resource1 = CVSWorkspaceRoot.getRemoteResourceFor(project.getFile("file1.txt")); + assertTrue(resource1.exists(DEFAULT_MONITOR)); + ICVSRemoteResource resource2 = CVSWorkspaceRoot.getRemoteResourceFor(project.getFolder("folder2/folder3/")); + assertTrue(resource2.exists(DEFAULT_MONITOR)); + deleteResources(project, new String[] {"file1.txt", "folder2/folder3/b.txt", "folder2/folder3/c.txt" }, true); + assertTrue( ! resource1.exists(DEFAULT_MONITOR)); + assertTrue(resource2.exists(DEFAULT_MONITOR)); + if (CVSTestSetup.INITIALIZE_REPO) { + CVSTestSetup.executeRemoteCommand(getRepository(), "rm -rf " + ((ICVSFolder)resource2).getFolderSyncInfo().getRemoteLocation()); + assertTrue( ! resource2.exists(DEFAULT_MONITOR)); + } + } + // /** // * Test building a sync tree using the RemoteFolderTreeBuilder using a remote resource as the // * starting point instead of a local one. @@ -521,26 +521,26 @@ public class RemoteResourceTest extends EclipseTest { // checkoutProject(project, name, null); // assertEquals(Path.EMPTY, CVSWorkspaceRoot.getCVSResourceFor(project), tree, false, true); // } - - public void testCheckoutIntoRemoteFolder() throws CoreException, IOException, CVSException, InvocationTargetException, InterruptedException { - IProject project = createProject(new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder2/folder3/b.txt", "folder2/folder3/c.txt"}); - - ICVSRemoteFolder remote = (ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(project); - remote = checkoutRemote(remote); - assertEquals(Path.EMPTY, CVSWorkspaceRoot.getCVSResourceFor(project), remote, false, true); - - // Try a version - CVSTag tag = new CVSTag("v1", CVSTag.VERSION); - tagProject(project, tag, false); - IProject copy = checkoutCopy(project, tag); - setContentsAndEnsureModified(project.getFile("file1.txt")); - commitProject(project); - remote = (ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(project); - ((RemoteFolder)remote).setTag(tag); - remote = checkoutRemote(remote); - assertEquals(Path.EMPTY, CVSWorkspaceRoot.getCVSResourceFor(copy), remote, false, true); - } - + + public void testCheckoutIntoRemoteFolder() throws CoreException, IOException, CVSException, InvocationTargetException, InterruptedException { + IProject project = createProject(new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder2/folder3/b.txt", "folder2/folder3/c.txt"}); + + ICVSRemoteFolder remote = (ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(project); + remote = checkoutRemote(remote); + assertEquals(Path.EMPTY, CVSWorkspaceRoot.getCVSResourceFor(project), remote, false, true); + + // Try a version + CVSTag tag = new CVSTag("v1", CVSTag.VERSION); + tagProject(project, tag, false); + IProject copy = checkoutCopy(project, tag); + setContentsAndEnsureModified(project.getFile("file1.txt")); + commitProject(project); + remote = (ICVSRemoteFolder)CVSWorkspaceRoot.getRemoteResourceFor(project); + ((RemoteFolder)remote).setTag(tag); + remote = checkoutRemote(remote); + assertEquals(Path.EMPTY, CVSWorkspaceRoot.getCVSResourceFor(copy), remote, false, true); + } + public void testBug244425() throws CVSException, CoreException, IOException { IProject projectHead = createProject("test", new String[] { "a/", diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSChangeSetTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSChangeSetTests.java index 4466b2304..a682ec377 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSChangeSetTests.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSChangeSetTests.java @@ -42,7 +42,7 @@ import org.eclipse.ui.PartInitException; public class CVSChangeSetTests extends CVSSyncSubscriberTest { public static Test suite() { - return suite(CVSChangeSetTests.class); + return suite(CVSChangeSetTests.class); } public CVSChangeSetTests() { @@ -53,140 +53,140 @@ public class CVSChangeSetTests extends CVSSyncSubscriberTest { super(name); } - private void assertIncomingChangesInSets(IFile[][] files, String[] messages) throws CoreException { - // Get the workspace subscriber which also creates a participant and page in the sync view - Subscriber workspaceSubscriber = getWorkspaceSubscriber(); - refresh(workspaceSubscriber); - ISynchronizeModelElement root = getModelRoot(workspaceSubscriber); - ChangeSetDiffNode[] nodes = getCheckedInChangeSetNodes(root); - assertNodesInViewer(workspaceSubscriber, nodes); - assertEquals("The number of change sets in the sync view do not match the expected number", messages.length, nodes.length); - for (int i = 0; i < messages.length; i++) { - String message = messages[i]; - ChangeSetDiffNode node = getCommitSetFor(root, message); - assertNotNull("The commit set for '" + message + "' is not in the sync view", node); - List<IResource> filesInSet = new ArrayList<>(); - getFileChildren(node, filesInSet); - assertTrue("The number of files in the set do not match the expected number", files[i].length == filesInSet.size()); - for (int j = 0; j < files[i].length; j++) { - IFile file = files[i][j]; - assertTrue("File " + file.getFullPath() + " is not in the set", filesInSet.contains(file)); - } - } - } + private void assertIncomingChangesInSets(IFile[][] files, String[] messages) throws CoreException { + // Get the workspace subscriber which also creates a participant and page in the sync view + Subscriber workspaceSubscriber = getWorkspaceSubscriber(); + refresh(workspaceSubscriber); + ISynchronizeModelElement root = getModelRoot(workspaceSubscriber); + ChangeSetDiffNode[] nodes = getCheckedInChangeSetNodes(root); + assertNodesInViewer(workspaceSubscriber, nodes); + assertEquals("The number of change sets in the sync view do not match the expected number", messages.length, nodes.length); + for (int i = 0; i < messages.length; i++) { + String message = messages[i]; + ChangeSetDiffNode node = getCommitSetFor(root, message); + assertNotNull("The commit set for '" + message + "' is not in the sync view", node); + List<IResource> filesInSet = new ArrayList<>(); + getFileChildren(node, filesInSet); + assertTrue("The number of files in the set do not match the expected number", files[i].length == filesInSet.size()); + for (int j = 0; j < files[i].length; j++) { + IFile file = files[i][j]; + assertTrue("File " + file.getFullPath() + " is not in the set", filesInSet.contains(file)); + } + } + } - private void assertNodesInViewer(Subscriber workspaceSubscriber, ChangeSetDiffNode[] nodes) throws PartInitException { - ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); - SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); - TreeViewer viewer = (TreeViewer)page.getViewer(); - Tree tree = viewer.getTree(); - List<ChangeSetDiffNode> nodeList = new ArrayList<>(); - nodeList.addAll(Arrays.asList(nodes)); - TreeItem[] items = tree.getItems(); - removeTreeItemsFromList(nodeList, items); - assertTrue("Not all nodes are visible in the view", nodeList.isEmpty()); - } + private void assertNodesInViewer(Subscriber workspaceSubscriber, ChangeSetDiffNode[] nodes) throws PartInitException { + ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); + SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); + TreeViewer viewer = (TreeViewer)page.getViewer(); + Tree tree = viewer.getTree(); + List<ChangeSetDiffNode> nodeList = new ArrayList<>(); + nodeList.addAll(Arrays.asList(nodes)); + TreeItem[] items = tree.getItems(); + removeTreeItemsFromList(nodeList, items); + assertTrue("Not all nodes are visible in the view", nodeList.isEmpty()); + } - private void removeTreeItemsFromList(List<?> nodeList, TreeItem[] items) { - for (int i = 0; i < items.length; i++) { - TreeItem item = items[i]; - nodeList.remove(item.getData()); - TreeItem[] children = item.getItems(); - removeTreeItemsFromList(nodeList, children); - } - } + private void removeTreeItemsFromList(List<?> nodeList, TreeItem[] items) { + for (int i = 0; i < items.length; i++) { + TreeItem item = items[i]; + nodeList.remove(item.getData()); + TreeItem[] children = item.getItems(); + removeTreeItemsFromList(nodeList, children); + } + } - private ChangeSetDiffNode[] getCheckedInChangeSetNodes(ISynchronizeModelElement root) { - List<ChangeSetDiffNode> result = new ArrayList<>(); - IDiffElement[] children = root.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - if (element instanceof ChangeSetDiffNode) { - ChangeSetDiffNode node = (ChangeSetDiffNode)element; - if (node.getSet() instanceof CheckedInChangeSet) { - result.add(node); - } - } - } - return result.toArray(new ChangeSetDiffNode[result.size()]); - } - - private ChangeSetDiffNode[] getActiveChangeSetNodes(ISynchronizeModelElement root) { - List<ChangeSetDiffNode> result = new ArrayList<>(); - IDiffElement[] children = root.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - if (element instanceof ChangeSetDiffNode) { - ChangeSetDiffNode node = (ChangeSetDiffNode)element; - if (node.getSet() instanceof ActiveChangeSet) { - result.add(node); - } - } - } - return result.toArray(new ChangeSetDiffNode[result.size()]); - } + private ChangeSetDiffNode[] getCheckedInChangeSetNodes(ISynchronizeModelElement root) { + List<ChangeSetDiffNode> result = new ArrayList<>(); + IDiffElement[] children = root.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + if (element instanceof ChangeSetDiffNode) { + ChangeSetDiffNode node = (ChangeSetDiffNode)element; + if (node.getSet() instanceof CheckedInChangeSet) { + result.add(node); + } + } + } + return result.toArray(new ChangeSetDiffNode[result.size()]); + } + + private ChangeSetDiffNode[] getActiveChangeSetNodes(ISynchronizeModelElement root) { + List<ChangeSetDiffNode> result = new ArrayList<>(); + IDiffElement[] children = root.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + if (element instanceof ChangeSetDiffNode) { + ChangeSetDiffNode node = (ChangeSetDiffNode)element; + if (node.getSet() instanceof ActiveChangeSet) { + result.add(node); + } + } + } + return result.toArray(new ChangeSetDiffNode[result.size()]); + } - /** - * Adds IFiles to the list - */ - private void getFileChildren(ISynchronizeModelElement node, List<IResource> list) { - IResource resource = node.getResource(); - if (resource != null && resource.getType() == IResource.FILE) { - list.add(resource); - } - IDiffElement[] children = node.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement child = children[i]; - getFileChildren((ISynchronizeModelElement)child, list); - } - return; - } + /** + * Adds IFiles to the list + */ + private void getFileChildren(ISynchronizeModelElement node, List<IResource> list) { + IResource resource = node.getResource(); + if (resource != null && resource.getType() == IResource.FILE) { + list.add(resource); + } + IDiffElement[] children = node.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement child = children[i]; + getFileChildren((ISynchronizeModelElement)child, list); + } + return; + } - private ChangeSetDiffNode getCommitSetFor(ISynchronizeModelElement root, String message) { - IDiffElement[] children = root.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - if (element instanceof ChangeSetDiffNode) { - ChangeSetDiffNode node = (ChangeSetDiffNode)element; - if (node.getSet().getComment().equals(message)) { - return node; - } - } - } - return null; - } + private ChangeSetDiffNode getCommitSetFor(ISynchronizeModelElement root, String message) { + IDiffElement[] children = root.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + if (element instanceof ChangeSetDiffNode) { + ChangeSetDiffNode node = (ChangeSetDiffNode)element; + if (node.getSet().getComment().equals(message)) { + return node; + } + } + } + return null; + } - private void refresh(Subscriber workspaceSubscriber) throws TeamException { - workspaceSubscriber.refresh(workspaceSubscriber.roots(), IResource.DEPTH_INFINITE, DEFAULT_MONITOR); - } + private void refresh(Subscriber workspaceSubscriber) throws TeamException { + workspaceSubscriber.refresh(workspaceSubscriber.roots(), IResource.DEPTH_INFINITE, DEFAULT_MONITOR); + } - private void enableChangeSets(Subscriber workspaceSubscriber) throws PartInitException { - ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); - SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); - ChangeSetModelManager manager = (ChangeSetModelManager)page.getConfiguration().getProperty(SynchronizePageConfiguration.P_MODEL_MANAGER); - manager.setCommitSetsEnabled(true); - page.getConfiguration().setMode(ISynchronizePageConfiguration.BOTH_MODE); - } + private void enableChangeSets(Subscriber workspaceSubscriber) throws PartInitException { + ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); + SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); + ChangeSetModelManager manager = (ChangeSetModelManager)page.getConfiguration().getProperty(SynchronizePageConfiguration.P_MODEL_MANAGER); + manager.setCommitSetsEnabled(true); + page.getConfiguration().setMode(ISynchronizePageConfiguration.BOTH_MODE); + } - private void enableCheckedInChangeSets(Subscriber workspaceSubscriber) throws PartInitException { - enableChangeSets(workspaceSubscriber); - ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); - SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); - page.getConfiguration().setMode(ISynchronizePageConfiguration.INCOMING_MODE); - } - - private void enableActiveChangeSets(Subscriber workspaceSubscriber) throws PartInitException { - enableChangeSets(workspaceSubscriber); - ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); - SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); - page.getConfiguration().setMode(ISynchronizePageConfiguration.OUTGOING_MODE); - } - - /* - * Wait until all the background handlers have settled and then return the root element in the sync view - */ - private ISynchronizeModelElement getModelRoot(Subscriber workspaceSubscriber) throws CoreException { - IProgressMonitor eventLoopProgressMonitor = new IProgressMonitor() { + private void enableCheckedInChangeSets(Subscriber workspaceSubscriber) throws PartInitException { + enableChangeSets(workspaceSubscriber); + ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); + SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); + page.getConfiguration().setMode(ISynchronizePageConfiguration.INCOMING_MODE); + } + + private void enableActiveChangeSets(Subscriber workspaceSubscriber) throws PartInitException { + enableChangeSets(workspaceSubscriber); + ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); + SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); + page.getConfiguration().setMode(ISynchronizePageConfiguration.OUTGOING_MODE); + } + + /* + * Wait until all the background handlers have settled and then return the root element in the sync view + */ + private ISynchronizeModelElement getModelRoot(Subscriber workspaceSubscriber) throws CoreException { + IProgressMonitor eventLoopProgressMonitor = new IProgressMonitor() { public void beginTask(String name, int totalWork) { } public void done() { @@ -206,218 +206,218 @@ public class CVSChangeSetTests extends CVSSyncSubscriberTest { while (Display.getCurrent().readAndDispatch()) {} } }; - SubscriberParticipantSyncInfoSource.getCollector(workspaceSubscriber); - ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); - ChangeSetCapability capability = ((IChangeSetProvider)participant).getChangeSetCapability(); - SubscriberChangeSetManager activeManager = (SubscriberChangeSetManager)capability.getActiveChangeSetManager(); - activeManager.waitUntilDone(eventLoopProgressMonitor); - SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); - ChangeSetModelManager manager = (ChangeSetModelManager)page.getConfiguration().getProperty(SynchronizePageConfiguration.P_MODEL_MANAGER); - AbstractSynchronizeModelProvider provider = (AbstractSynchronizeModelProvider)manager.getActiveModelProvider(); - provider.waitUntilDone(eventLoopProgressMonitor); - return provider.getModelRoot(); - } + SubscriberParticipantSyncInfoSource.getCollector(workspaceSubscriber); + ISynchronizeParticipant participant = SubscriberParticipantSyncInfoSource.getParticipant(workspaceSubscriber); + ChangeSetCapability capability = ((IChangeSetProvider)participant).getChangeSetCapability(); + SubscriberChangeSetManager activeManager = (SubscriberChangeSetManager)capability.getActiveChangeSetManager(); + activeManager.waitUntilDone(eventLoopProgressMonitor); + SubscriberParticipantPage page = (SubscriberParticipantPage)SubscriberParticipantSyncInfoSource.getSyncViewPage(participant); + ChangeSetModelManager manager = (ChangeSetModelManager)page.getConfiguration().getProperty(SynchronizePageConfiguration.P_MODEL_MANAGER); + AbstractSynchronizeModelProvider provider = (AbstractSynchronizeModelProvider)manager.getActiveModelProvider(); + provider.waitUntilDone(eventLoopProgressMonitor); + return provider.getModelRoot(); + } - private ActiveChangeSetManager getActiveChangeSetManager() { - return CVSUIPlugin.getPlugin().getChangeSetManager(); - } - - /* - * Assert that the given resources make up the given set both directly - * and by what is displayed in the sync view. - */ - private void assertInActiveSet(IResource[] resources, ActiveChangeSet set) throws CoreException { - assertResourcesAreTheSame(resources, set.getResources(), true); - ISynchronizeModelElement root = getModelRoot(((SubscriberChangeSetManager)getActiveChangeSetManager()).getSubscriber()); - ChangeSetDiffNode node = getChangeSetNodeFor(root, set); - assertNotNull("Change set " + set.getTitle() + " did not appear in the sync view", node); - IResource[] outOfSync = getOutOfSyncResources(node); - assertResourcesAreTheSame(resources, outOfSync, true); - // Assert that all active sets are visible in the view - ChangeSet[] sets = getActiveChangeSetManager().getSets(); - for (int i = 0; i < sets.length; i++) { - ChangeSet changeSet = sets[i]; - node = getChangeSetNodeFor(root, changeSet); - assertNotNull("The node for set " + set.getName() + " is not in the view", node); - - } - ChangeSetDiffNode[] nodes = getActiveChangeSetNodes(root); - assertNodesInViewer(getWorkspaceSubscriber(), nodes); - } - - private ChangeSetDiffNode getChangeSetNodeFor(ISynchronizeModelElement root, ChangeSet set) { - IDiffElement[] children = root.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - if (element instanceof ChangeSetDiffNode) { - ChangeSetDiffNode node = (ChangeSetDiffNode)element; - if (node.getSet() == set) { - return node; - } - } - } - return null; - } + private ActiveChangeSetManager getActiveChangeSetManager() { + return CVSUIPlugin.getPlugin().getChangeSetManager(); + } + + /* + * Assert that the given resources make up the given set both directly + * and by what is displayed in the sync view. + */ + private void assertInActiveSet(IResource[] resources, ActiveChangeSet set) throws CoreException { + assertResourcesAreTheSame(resources, set.getResources(), true); + ISynchronizeModelElement root = getModelRoot(((SubscriberChangeSetManager)getActiveChangeSetManager()).getSubscriber()); + ChangeSetDiffNode node = getChangeSetNodeFor(root, set); + assertNotNull("Change set " + set.getTitle() + " did not appear in the sync view", node); + IResource[] outOfSync = getOutOfSyncResources(node); + assertResourcesAreTheSame(resources, outOfSync, true); + // Assert that all active sets are visible in the view + ChangeSet[] sets = getActiveChangeSetManager().getSets(); + for (int i = 0; i < sets.length; i++) { + ChangeSet changeSet = sets[i]; + node = getChangeSetNodeFor(root, changeSet); + assertNotNull("The node for set " + set.getName() + " is not in the view", node); + + } + ChangeSetDiffNode[] nodes = getActiveChangeSetNodes(root); + assertNodesInViewer(getWorkspaceSubscriber(), nodes); + } + + private ChangeSetDiffNode getChangeSetNodeFor(ISynchronizeModelElement root, ChangeSet set) { + IDiffElement[] children = root.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + if (element instanceof ChangeSetDiffNode) { + ChangeSetDiffNode node = (ChangeSetDiffNode)element; + if (node.getSet() == set) { + return node; + } + } + } + return null; + } - private IResource[] getOutOfSyncResources(ISynchronizeModelElement element) { - ArrayList<SyncInfo> arrayList = new ArrayList<>(); - getOutOfSync(element, arrayList); - SyncInfo[] infos = arrayList.toArray(new SyncInfo[arrayList.size()]); - IResource[] resources = getResources(infos); - return resources; - } + private IResource[] getOutOfSyncResources(ISynchronizeModelElement element) { + ArrayList<SyncInfo> arrayList = new ArrayList<>(); + getOutOfSync(element, arrayList); + SyncInfo[] infos = arrayList.toArray(new SyncInfo[arrayList.size()]); + IResource[] resources = getResources(infos); + return resources; + } - private IResource[] getResources(SyncInfo[] infos) { - IResource[] resources = new IResource[infos.length]; - for (int i = 0; i < resources.length; i++) { - resources[i] = infos[i].getLocal(); - } - return resources; - } + private IResource[] getResources(SyncInfo[] infos) { + IResource[] resources = new IResource[infos.length]; + for (int i = 0; i < resources.length; i++) { + resources[i] = infos[i].getLocal(); + } + return resources; + } - private void getOutOfSync(ISynchronizeModelElement node, List<SyncInfo> list) { - SyncInfo info = getSyncInfo(node); - if (info != null && info.getKind() != SyncInfo.IN_SYNC) { - list.add(info); - } - IDiffElement[] children = node.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement child = children[i]; - getOutOfSync((ISynchronizeModelElement)child, list); - } - return; - } - - private SyncInfo getSyncInfo(ISynchronizeModelElement node) { - if (node instanceof IAdaptable) { - return ((IAdaptable)node).getAdapter(SyncInfo.class); - } - return null; - } + private void getOutOfSync(ISynchronizeModelElement node, List<SyncInfo> list) { + SyncInfo info = getSyncInfo(node); + if (info != null && info.getKind() != SyncInfo.IN_SYNC) { + list.add(info); + } + IDiffElement[] children = node.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement child = children[i]; + getOutOfSync((ISynchronizeModelElement)child, list); + } + return; + } + + private SyncInfo getSyncInfo(ISynchronizeModelElement node) { + if (node instanceof IAdaptable) { + return ((IAdaptable)node).getAdapter(SyncInfo.class); + } + return null; + } - private void assertResourcesAreTheSame(IResource[] resources1, IResource[] resources2, boolean doNotAllowExtra) { - if (doNotAllowExtra) { - if (resources1.length != resources2.length) { - System.out.println("Expected"); - for (int i = 0; i < resources1.length; i++) { - IResource resource = resources1[i]; - System.out.println(resource.getFullPath().toString()); - } - System.out.println("Actual"); - for (int i = 0; i < resources2.length; i++) { - IResource resource = resources2[i]; - System.out.println(resource.getFullPath().toString()); - } - } - assertEquals("The number of resources do not match the expected number", resources1.length, resources2.length); - } - for (int i = 0; i < resources1.length; i++) { - IResource resource = resources1[i]; - boolean found = false; - for (int j = 0; j < resources2.length; j++) { - IResource resource2 = resources2[j]; - if (resource2.equals(resource)) { - found = true; - break; - } - } - assertTrue("Expected resource " + resource.getFullPath().toString() + " was not present", found); - } - } + private void assertResourcesAreTheSame(IResource[] resources1, IResource[] resources2, boolean doNotAllowExtra) { + if (doNotAllowExtra) { + if (resources1.length != resources2.length) { + System.out.println("Expected"); + for (int i = 0; i < resources1.length; i++) { + IResource resource = resources1[i]; + System.out.println(resource.getFullPath().toString()); + } + System.out.println("Actual"); + for (int i = 0; i < resources2.length; i++) { + IResource resource = resources2[i]; + System.out.println(resource.getFullPath().toString()); + } + } + assertEquals("The number of resources do not match the expected number", resources1.length, resources2.length); + } + for (int i = 0; i < resources1.length; i++) { + IResource resource = resources1[i]; + boolean found = false; + for (int j = 0; j < resources2.length; j++) { + IResource resource2 = resources2[j]; + if (resource2.equals(resource)) { + found = true; + break; + } + } + assertTrue("Expected resource " + resource.getFullPath().toString() + " was not present", found); + } + } - /* - * Assert that the given resources make up the root set - * displayed in the sync view. The root set is those - * resources that are not part of an active change set. - */ - private void assertInRootSet(IResource[] resources) throws CoreException { - ISynchronizeModelElement[] nodes = getNonChangeSetRoots(getModelRoot(((SubscriberChangeSetManager)getActiveChangeSetManager()).getSubscriber())); - List<SyncInfo> list = new ArrayList<>(); - for (int i = 0; i < nodes.length; i++) { - ISynchronizeModelElement element = nodes[i]; - getOutOfSync(element, list); - } - IResource[] outOfSync = getResources(list.toArray(new SyncInfo[list.size()])); - // Only require that the expected resources are there but allow extra. - // This is required because of junk left over from previous tests. - // This means there is a bug somewhere. But where? - assertResourcesAreTheSame(resources, outOfSync, false /* allow extra out-of-sync resources */); - - } - - private ISynchronizeModelElement[] getNonChangeSetRoots(ISynchronizeModelElement modelRoot) { - List<ISynchronizeModelElement> result = new ArrayList<>(); - IDiffElement[] children = modelRoot.getChildren(); - for (int i = 0; i < children.length; i++) { - IDiffElement element = children[i]; - if (!(element instanceof ChangeSetDiffNode)) { - result.add((ISynchronizeModelElement) element); - } - } - return result.toArray(new ISynchronizeModelElement[result.size()]); - } + /* + * Assert that the given resources make up the root set + * displayed in the sync view. The root set is those + * resources that are not part of an active change set. + */ + private void assertInRootSet(IResource[] resources) throws CoreException { + ISynchronizeModelElement[] nodes = getNonChangeSetRoots(getModelRoot(((SubscriberChangeSetManager)getActiveChangeSetManager()).getSubscriber())); + List<SyncInfo> list = new ArrayList<>(); + for (int i = 0; i < nodes.length; i++) { + ISynchronizeModelElement element = nodes[i]; + getOutOfSync(element, list); + } + IResource[] outOfSync = getResources(list.toArray(new SyncInfo[list.size()])); + // Only require that the expected resources are there but allow extra. + // This is required because of junk left over from previous tests. + // This means there is a bug somewhere. But where? + assertResourcesAreTheSame(resources, outOfSync, false /* allow extra out-of-sync resources */); + + } + + private ISynchronizeModelElement[] getNonChangeSetRoots(ISynchronizeModelElement modelRoot) { + List<ISynchronizeModelElement> result = new ArrayList<>(); + IDiffElement[] children = modelRoot.getChildren(); + for (int i = 0; i < children.length; i++) { + IDiffElement element = children[i]; + if (!(element instanceof ChangeSetDiffNode)) { + result.add((ISynchronizeModelElement) element); + } + } + return result.toArray(new ISynchronizeModelElement[result.size()]); + } - public void testSimpleCommit() throws CoreException { - enableCheckedInChangeSets(getWorkspaceSubscriber()); - - IProject project = createProject(new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); - - // Modify a file in a copy - IProject copy = checkoutCopy(project, CVSTag.DEFAULT); - setContentsAndEnsureModified(copy.getFile("file1.txt")); - String message1 = "Commit 1"; - commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE, message1); - assertIncomingChangesInSets(new IFile[][] {{ project.getFile("file1.txt") }}, new String[] {message1}); - - // Modify the copy some more - setContentsAndEnsureModified(copy.getFile("file2.txt")); - setContentsAndEnsureModified(copy.getFile("folder1/a.txt")); - String message2 = "Commit 2"; - commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE, message2); - assertIncomingChangesInSets(new IFile[][] { - { project.getFile("file1.txt") }, - { project.getFile("file2.txt"), project.getFile("folder1/a.txt") } - }, new String[] {message1, message2}); - - // Modify the copy some more - setContentsAndEnsureModified(copy.getFile("file2.txt")); - String message3 = "Commit 3"; - commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE, message3); - assertIncomingChangesInSets(new IFile[][] { - { project.getFile("file1.txt") }, - { project.getFile("folder1/a.txt") }, - { project.getFile("file2.txt")} - }, new String[] {message1, message2, message3}); - - // Now commit the files in one of the sets and ensure it is removed from the view - updateResources(new IResource[] { project.getFile("file1.txt")}, false); - assertIncomingChangesInSets(new IFile[][] { - { project.getFile("folder1/a.txt") }, - { project.getFile("file2.txt")} - }, new String[] {message2, message3}); + public void testSimpleCommit() throws CoreException { + enableCheckedInChangeSets(getWorkspaceSubscriber()); + + IProject project = createProject(new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); + + // Modify a file in a copy + IProject copy = checkoutCopy(project, CVSTag.DEFAULT); + setContentsAndEnsureModified(copy.getFile("file1.txt")); + String message1 = "Commit 1"; + commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE, message1); + assertIncomingChangesInSets(new IFile[][] {{ project.getFile("file1.txt") }}, new String[] {message1}); + + // Modify the copy some more + setContentsAndEnsureModified(copy.getFile("file2.txt")); + setContentsAndEnsureModified(copy.getFile("folder1/a.txt")); + String message2 = "Commit 2"; + commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE, message2); + assertIncomingChangesInSets(new IFile[][] { + { project.getFile("file1.txt") }, + { project.getFile("file2.txt"), project.getFile("folder1/a.txt") } + }, new String[] {message1, message2}); + + // Modify the copy some more + setContentsAndEnsureModified(copy.getFile("file2.txt")); + String message3 = "Commit 3"; + commitResources(new IResource[] {copy}, IResource.DEPTH_INFINITE, message3); + assertIncomingChangesInSets(new IFile[][] { + { project.getFile("file1.txt") }, + { project.getFile("folder1/a.txt") }, + { project.getFile("file2.txt")} + }, new String[] {message1, message2, message3}); + + // Now commit the files in one of the sets and ensure it is removed from the view + updateResources(new IResource[] { project.getFile("file1.txt")}, false); + assertIncomingChangesInSets(new IFile[][] { + { project.getFile("folder1/a.txt") }, + { project.getFile("file2.txt")} + }, new String[] {message2, message3}); } - public void testSimpleActiveChangeSet() throws CoreException { - IProject project = createProject(new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); - // Enable Change Sets - enableActiveChangeSets(getWorkspaceSubscriber()); - // Add a folder and file - IFolder newFolder = project.getFolder("folder2"); - newFolder.create(false, true, null); - IFile newFile = newFolder.getFile("file.txt"); - newFile.create(new ByteArrayInputStream("Hi There".getBytes()), false, null); - // Create an active commit set and assert that it appears in the sync view - ActiveChangeSetManager manager = getActiveChangeSetManager(); - ActiveChangeSet set = manager.createSet("test", new IDiff[0]); - manager.add(set); - assertInActiveSet(new IResource[] { }, set); - assertInRootSet(new IResource[] {newFolder, newFile}); - // Add the new file to the set and assert that the file is in the set and the folder is still at the root - set.add(new IResource[] { newFile }); - assertInActiveSet(new IResource[] { newFile }, set); - assertInRootSet(new IResource[] {newFolder }); - // Add the folder to the set - set.add(new IResource[] { newFolder }); - assertInActiveSet(new IResource[] { newFolder, newFile }, set); - } + public void testSimpleActiveChangeSet() throws CoreException { + IProject project = createProject(new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); + // Enable Change Sets + enableActiveChangeSets(getWorkspaceSubscriber()); + // Add a folder and file + IFolder newFolder = project.getFolder("folder2"); + newFolder.create(false, true, null); + IFile newFile = newFolder.getFile("file.txt"); + newFile.create(new ByteArrayInputStream("Hi There".getBytes()), false, null); + // Create an active commit set and assert that it appears in the sync view + ActiveChangeSetManager manager = getActiveChangeSetManager(); + ActiveChangeSet set = manager.createSet("test", new IDiff[0]); + manager.add(set); + assertInActiveSet(new IResource[] { }, set); + assertInRootSet(new IResource[] {newFolder, newFile}); + // Add the new file to the set and assert that the file is in the set and the folder is still at the root + set.add(new IResource[] { newFile }); + assertInActiveSet(new IResource[] { newFile }, set); + assertInRootSet(new IResource[] {newFolder }); + // Add the folder to the set + set.add(new IResource[] { newFolder }); + assertInActiveSet(new IResource[] { newFolder, newFile }, set); + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSCompareSubscriberTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSCompareSubscriberTest.java index f90fe7f8b..b1b1bbc14 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSCompareSubscriberTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSCompareSubscriberTest.java @@ -125,58 +125,58 @@ public class CVSCompareSubscriberTest extends CVSSyncSubscriberTest { SyncInfo.DELETION}); } - public void testBinaryAddition() throws CoreException { - // See bug 132255 - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); + public void testBinaryAddition() throws CoreException { + // See bug 132255 + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); // Checkout and branch a copy CVSTag v1 = new CVSTag("v1", CVSTag.VERSION); // Add a binary file that contains LFs - IProject copy = checkoutCopy(project, "-copy"); - create(copy.getFile("binaryFile"), true); - setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { copy.getFile("binaryFile") }); - commitProject(copy); - // Tag the project - tagProject(copy, v1, false); - // Compare with the tag and merge the changes - CVSCompareSubscriber subscriber = getSyncInfoSource().createCompareSubscriber(project, v1); - getSyncInfoSource().refresh(subscriber, project); - getSyncInfoSource().overrideAndUpdateResources(subscriber, false, new IResource[] { project.getFile("binaryFile") }); - assertContentsEqual(copy.getFile("binaryFile"), project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } - - public void testBinaryMarkAsMerged() throws CoreException, InvocationTargetException, InterruptedException { - // See bug 132255 - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); + IProject copy = checkoutCopy(project, "-copy"); + create(copy.getFile("binaryFile"), true); + setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { copy.getFile("binaryFile") }); + commitProject(copy); + // Tag the project + tagProject(copy, v1, false); + // Compare with the tag and merge the changes + CVSCompareSubscriber subscriber = getSyncInfoSource().createCompareSubscriber(project, v1); + getSyncInfoSource().refresh(subscriber, project); + getSyncInfoSource().overrideAndUpdateResources(subscriber, false, new IResource[] { project.getFile("binaryFile") }); + assertContentsEqual(copy.getFile("binaryFile"), project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } + + public void testBinaryMarkAsMerged() throws CoreException, InvocationTargetException, InterruptedException { + // See bug 132255 + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); // Checkout and branch a copy CVSTag v1 = new CVSTag("v1", CVSTag.VERSION); // Add a binary file that contains LFs - IProject copy = checkoutCopy(project, "-copy"); - create(copy.getFile("binaryFile"), true); - setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { copy.getFile("binaryFile") }); - commitProject(copy); - // Tag the project - tagProject(copy, v1, false); - // Add the same file to the project but don't share it - create(project.getFile("binaryFile"), true); - setContentsAndEnsureModified(project.getFile("binaryFile"), "/n/nSome Content\n\n"); - // Compare with the tag and merge the changes - CVSCompareSubscriber subscriber = getSyncInfoSource().createCompareSubscriber(project, v1); - getSyncInfoSource().refresh(subscriber, project); - getSyncInfoSource().markAsMerged(subscriber, new IResource[] { project.getFile("binaryFile") }); - assertIsBinary(project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } + IProject copy = checkoutCopy(project, "-copy"); + create(copy.getFile("binaryFile"), true); + setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { copy.getFile("binaryFile") }); + commitProject(copy); + // Tag the project + tagProject(copy, v1, false); + // Add the same file to the project but don't share it + create(project.getFile("binaryFile"), true); + setContentsAndEnsureModified(project.getFile("binaryFile"), "/n/nSome Content\n\n"); + // Compare with the tag and merge the changes + CVSCompareSubscriber subscriber = getSyncInfoSource().createCompareSubscriber(project, v1); + getSyncInfoSource().refresh(subscriber, project); + getSyncInfoSource().markAsMerged(subscriber, new IResource[] { project.getFile("binaryFile") }); + assertIsBinary(project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java index 21c3ba380..d95f428ce 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java @@ -219,12 +219,12 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testMergableConflicts", subscriber, project, new String[] { "file1.txt", "file2.txt"}, true, new int[] { - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE}); + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE}); // Perform a merge mergeResources(subscriber, project, new String[] { - "file1.txt", + "file1.txt", "file2.txt"}, false /* allow overwrite */); @@ -232,8 +232,8 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testMergableConflicts", getWorkspaceSubscriber(), project, new String[] { "file1.txt", "file2.txt"}, true, new int[] { - SyncInfo.OUTGOING | SyncInfo.CHANGE, - SyncInfo.OUTGOING | SyncInfo.CHANGE}); + SyncInfo.OUTGOING | SyncInfo.CHANGE, + SyncInfo.OUTGOING | SyncInfo.CHANGE}); //TODO: How do we know if the right thing happened to the file contents? } @@ -272,12 +272,12 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testUnmergableConflicts", subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"}, true, new int[] { - SyncInfo.IN_SYNC, /* TODO: is this OK */ - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.ADDITION, - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE}); + SyncInfo.IN_SYNC, /* TODO: is this OK */ + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.ADDITION, + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE}); // TODO: Should actually perform the merge and check the results // However, this would require the changes to be redone @@ -289,12 +289,12 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testUnmergableConflicts", subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"}, true, new int[] { - SyncInfo.IN_SYNC, /* TODO: is this OK */ - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.ADDITION, - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE}); + SyncInfo.IN_SYNC, /* TODO: is this OK */ + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.ADDITION, + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE}); // Perform a merge mergeResources(subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"}, true /* allow overwrite */); @@ -303,11 +303,11 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testUnmergableConflicts", getWorkspaceSubscriber(), project, new String[] { "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"}, true, new int[] { - SyncInfo.OUTGOING | SyncInfo.CHANGE, - SyncInfo.OUTGOING | SyncInfo.CHANGE, - SyncInfo.OUTGOING | SyncInfo.CHANGE, - SyncInfo.OUTGOING | SyncInfo.DELETION, - SyncInfo.OUTGOING | SyncInfo.ADDITION}); + SyncInfo.OUTGOING | SyncInfo.CHANGE, + SyncInfo.OUTGOING | SyncInfo.CHANGE, + SyncInfo.OUTGOING | SyncInfo.CHANGE, + SyncInfo.OUTGOING | SyncInfo.DELETION, + SyncInfo.OUTGOING | SyncInfo.ADDITION}); assertDeleted("testUnmergableConflicts", project, new String[] { "delete.txt" }); //TODO: How do we know if the right thing happend to the file contents? @@ -343,12 +343,12 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testLocalScrub", subscriber, project, new String[] { "delete.txt", "file1.txt", "works.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"}, true, new int[] { - SyncInfo.INCOMING | SyncInfo.DELETION, - SyncInfo.INCOMING | SyncInfo.CHANGE, - SyncInfo.INCOMING | SyncInfo.CHANGE, - SyncInfo.INCOMING | SyncInfo.ADDITION, - SyncInfo.INCOMING | SyncInfo.DELETION, - SyncInfo.INCOMING | SyncInfo.CHANGE}); + SyncInfo.INCOMING | SyncInfo.DELETION, + SyncInfo.INCOMING | SyncInfo.CHANGE, + SyncInfo.INCOMING | SyncInfo.CHANGE, + SyncInfo.INCOMING | SyncInfo.ADDITION, + SyncInfo.INCOMING | SyncInfo.DELETION, + SyncInfo.INCOMING | SyncInfo.CHANGE}); //Refresh project to make sure we delete all existing files. See bug 403309 project.refreshLocal(IProject.DEPTH_INFINITE, DEFAULT_MONITOR); @@ -528,11 +528,11 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testMarkAsMergedConflicts", subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt"}, true, new int[] { - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.CHANGE, - SyncInfo.CONFLICTING | SyncInfo.ADDITION, - SyncInfo.CONFLICTING | SyncInfo.CHANGE}); + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.CHANGE, + SyncInfo.CONFLICTING | SyncInfo.ADDITION, + SyncInfo.CONFLICTING | SyncInfo.CHANGE}); markAsMerged(subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt"}); @@ -540,11 +540,11 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testMarkAsMerged", subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt"}, true, new int[] { - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC}); + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC}); } @Override @@ -656,59 +656,59 @@ public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest { assertContentsEqual(project, branchedProject); } - public void testBinaryAddition() throws CoreException { - // See bug 132255 - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); + public void testBinaryAddition() throws CoreException { + // See bug 132255 + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); // Checkout and branch a copy CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION); CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH); IProject branchedProject = branchProject(project, root, branch); // Add a binary file to the branch that contains LFs - create(branchedProject.getFile("binaryFile"), true); - setContentsAndEnsureModified(branchedProject.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { branchedProject.getFile("binaryFile") }); - commitProject(branchedProject); - // Merge the addition with HEAD - CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch); - getSyncInfoSource().refresh(subscriber, project); - getSyncInfoSource().updateResources(subscriber, new IResource[] { project.getFile("binaryFile") }); - assertContentsEqual(branchedProject.getFile("binaryFile"), project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } - - public void testBinaryMarkAsMerged() throws CoreException, InvocationTargetException, InterruptedException { - // See bug 132255 - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); + create(branchedProject.getFile("binaryFile"), true); + setContentsAndEnsureModified(branchedProject.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { branchedProject.getFile("binaryFile") }); + commitProject(branchedProject); + // Merge the addition with HEAD + CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch); + getSyncInfoSource().refresh(subscriber, project); + getSyncInfoSource().updateResources(subscriber, new IResource[] { project.getFile("binaryFile") }); + assertContentsEqual(branchedProject.getFile("binaryFile"), project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } + + public void testBinaryMarkAsMerged() throws CoreException, InvocationTargetException, InterruptedException { + // See bug 132255 + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); // Checkout and branch a copy CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION); CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH); IProject branchedProject = branchProject(project, root, branch); // Add a binary file to the branch that contains LFs - create(branchedProject.getFile("binaryFile"), true); - setContentsAndEnsureModified(branchedProject.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { branchedProject.getFile("binaryFile") }); - commitProject(branchedProject); - // Add the same file to the project but don't share it - create(project.getFile("binaryFile"), true); - setContentsAndEnsureModified(project.getFile("binaryFile"), "/n/nSome Content\n\n"); - // Merge the addition with HEAD - CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch); - getSyncInfoSource().refresh(subscriber, project); - getSyncInfoSource().markAsMerged(subscriber, new IResource[] { project.getFile("binaryFile") }); - assertIsBinary(project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } - + create(branchedProject.getFile("binaryFile"), true); + setContentsAndEnsureModified(branchedProject.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { branchedProject.getFile("binaryFile") }); + commitProject(branchedProject); + // Add the same file to the project but don't share it + create(project.getFile("binaryFile"), true); + setContentsAndEnsureModified(project.getFile("binaryFile"), "/n/nSome Content\n\n"); + // Merge the addition with HEAD + CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch); + getSyncInfoSource().refresh(subscriber, project); + getSyncInfoSource().markAsMerged(subscriber, new IResource[] { project.getFile("binaryFile") }); + assertIsBinary(project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } + public void testMergeNewFileToBranch() throws InvocationTargetException, InterruptedException, CoreException { // Create a project IProject project = createProject(new String[] {"file1.txt"}); diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSWorkspaceSubscriberTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSWorkspaceSubscriberTest.java index bd0c14a73..b45c7aa2a 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSWorkspaceSubscriberTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSWorkspaceSubscriberTest.java @@ -455,41 +455,41 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { } public void testOverideAndUpdateSimple() throws CVSException, CoreException, IOException { - IProject project = createProject("testOutgoingChangesOverideAndUpdate", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); + IProject project = createProject("testOutgoingChangesOverideAndUpdate", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); - // Make some modifications - setContentsAndEnsureModified(project.getFile("folder1/a.txt")); - addResources(project, new String[] { "folder2/folder3/add.txt" }, false); - deleteResources(project, new String[] {"folder1/b.txt"}, false); + // Make some modifications + setContentsAndEnsureModified(project.getFile("folder1/a.txt")); + addResources(project, new String[] { "folder2/folder3/add.txt" }, false); + deleteResources(project, new String[] {"folder1/b.txt"}, false); - // Get the sync tree for the project - assertSyncEquals("testOutgoingChangesOverwrite", project, - new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder2/", "folder2/folder3/", "folder2/folder3/add.txt"}, - true, new int[] { - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.OUTGOING | SyncInfo.CHANGE, - SyncInfo.OUTGOING | SyncInfo.DELETION, - SyncInfo.IN_SYNC, /* adding a folder creates it remotely */ - SyncInfo.IN_SYNC, /* adding a folder creates it remotely */ - SyncInfo.OUTGOING | SyncInfo.ADDITION}); + // Get the sync tree for the project + assertSyncEquals("testOutgoingChangesOverwrite", project, + new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder2/", "folder2/folder3/", "folder2/folder3/add.txt"}, + true, new int[] { + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.OUTGOING | SyncInfo.CHANGE, + SyncInfo.OUTGOING | SyncInfo.DELETION, + SyncInfo.IN_SYNC, /* adding a folder creates it remotely */ + SyncInfo.IN_SYNC, /* adding a folder creates it remotely */ + SyncInfo.OUTGOING | SyncInfo.ADDITION}); - // Revert the changes - overrideAndUpdate(project, new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder2/", "folder2/folder3/", "folder2/folder3/add.txt"}, true /* should prompt */); + // Revert the changes + overrideAndUpdate(project, new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt", "folder2/", "folder2/folder3/", "folder2/folder3/add.txt"}, true /* should prompt */); - // Ensure we're in sync - assertSyncEquals("testOutgoingChangesOverwrite", project, - new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder2/", "folder2/folder3/", "folder2/folder3/add.txt"}, - true, new int[] { - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC}); + // Ensure we're in sync + assertSyncEquals("testOutgoingChangesOverwrite", project, + new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder2/", "folder2/folder3/", "folder2/folder3/add.txt"}, + true, new int[] { + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC, + SyncInfo.IN_SYNC}); - // Ensure deleted resource is re-created - assertExistsInWorkspace("testOutgoingChangesOverwrite", project.getFile(new Path("folder1/b.txt"))); + // Ensure deleted resource is re-created + assertExistsInWorkspace("testOutgoingChangesOverwrite", project.getFile(new Path("folder1/b.txt"))); // Test conflicting changes IProject copy = checkoutCopy(project, "-copy"); @@ -649,7 +649,7 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { update( project, new String[] {"file1.txt"}); - + assertSyncEquals("testFileConflict", project, new String[] { "file1.txt", "folder1/", "folder1/a.txt"}, true, new int[] { @@ -911,7 +911,7 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { SyncInfo.INCOMING | SyncInfo.ADDITION, SyncInfo.INCOMING | SyncInfo.ADDITION}); } - + /* * Test that a deleted file can still be deleted through the team provider */ @@ -982,9 +982,9 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { SyncInfo.IN_SYNC, SyncInfo.IN_SYNC}); } - - public void testSyncOnBranch() throws CoreException { - + + public void testSyncOnBranch() throws CoreException { + // Create a test project and a branch IProject project = createProject(new String[] { "file1.txt", "file2.txt", "file3.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH); @@ -1019,8 +1019,8 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { SyncInfo.INCOMING | SyncInfo.ADDITION, SyncInfo.INCOMING | SyncInfo.ADDITION, SyncInfo.INCOMING | SyncInfo.ADDITION}); - } - + } + public void testRenameProject() throws CoreException { String[] resourceNames = new String[] { "changed.txt", "folder1/", "folder1/a.txt" }; int[] inSync = new int[] {SyncInfo.IN_SYNC, SyncInfo.IN_SYNC, SyncInfo.IN_SYNC}; @@ -1078,9 +1078,9 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testFolderDeletion sync check", project, new String[] { "folder1/", "folder1/a.txt", "folder1/folder2/", "folder1/folder2/file.txt"}, true, new int[] { SyncInfo.IN_SYNC, - SyncInfo.OUTGOING | SyncInfo.DELETION, - SyncInfo.IN_SYNC, - SyncInfo.OUTGOING | SyncInfo.DELETION}); + SyncInfo.OUTGOING | SyncInfo.DELETION, + SyncInfo.IN_SYNC, + SyncInfo.OUTGOING | SyncInfo.DELETION}); // commit folder1/a.txt commit(project, new String[] { "folder1/a.txt" }); @@ -1089,8 +1089,8 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testFolderDeletion sync check", project, new String[] { "folder1/", "folder1/folder2/", "folder1/folder2/file.txt"}, true, new int[] { SyncInfo.IN_SYNC, - SyncInfo.IN_SYNC, - SyncInfo.OUTGOING | SyncInfo.DELETION}); + SyncInfo.IN_SYNC, + SyncInfo.OUTGOING | SyncInfo.DELETION}); assertDeleted("testFolderDeletion", project, new String[] {"folder1/a.txt"}); // Commit folder1/folder2/file.txt @@ -1100,10 +1100,10 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { assertDeleted("testFolderDeletion", project, new String[] {"folder1/", "folder1/folder2/", "folder1/folder2/file.txt"}); } /** - * There is special handling required when building a sync tree for a tag when there are undiscovered folders - * that only contain other folders. - */ - public void testTagRetrievalForFolderWithNoFile() throws TeamException, CoreException { + * There is special handling required when building a sync tree for a tag when there are undiscovered folders + * that only contain other folders. + */ + public void testTagRetrievalForFolderWithNoFile() throws TeamException, CoreException { IProject project = createProject("testTagRetrievalForFolderWithNoFile", new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt"}); // Checkout, branch and modify a copy IProject copy = checkoutCopy(project, "-copy"); @@ -1115,15 +1115,15 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { // Fetch the tree corresponding to the branch using the original as the base. // XXX This will fail for CVSNT with directory pruning on refresh(getSubscriber(), project); - } - - public void testIgnoredResource() throws CoreException, TeamException { + } + + public void testIgnoredResource() throws CoreException, TeamException { // Create a test project (which commits it as well) IProject project = createProject("testIgnoredResource", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); // Create a new file without adding it to version control buildResources(project, new String[] {"ignored.txt"}, false); - + // Get the sync tree for the project assertSyncEquals("testIgnoredResource", project, new String[] { "ignored.txt"}, @@ -1138,29 +1138,29 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { true, new int[] { SyncInfo.IN_SYNC, SyncInfo.OUTGOING | SyncInfo.ADDITION}); - } + } public void testRenameUnshared() throws CoreException, TeamException { - // Create a test project (which commits it as well) - IProject project = createProject("testRenameUnshared", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); - - // Create a new file without adding it to version control - buildResources(project, new String[] {"oldName.txt"}, false); - - // Get the sync tree for the project - assertSyncEquals("testRenameUnshared", project, - new String[] { "oldName.txt" }, - true, new int[] {SyncInfo.OUTGOING | SyncInfo.ADDITION}); + // Create a test project (which commits it as well) + IProject project = createProject("testRenameUnshared", new String[] { "file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}); + + // Create a new file without adding it to version control + buildResources(project, new String[] {"oldName.txt"}, false); + + // Get the sync tree for the project + assertSyncEquals("testRenameUnshared", project, + new String[] { "oldName.txt" }, + true, new int[] {SyncInfo.OUTGOING | SyncInfo.ADDITION}); - IFile rename = project.getFile("oldName.txt"); - rename.move(new Path("newName.txt"), false, false, DEFAULT_MONITOR); + IFile rename = project.getFile("oldName.txt"); + rename.move(new Path("newName.txt"), false, false, DEFAULT_MONITOR); - assertDeleted("testRenameUnshared", project, new String[] {"oldName.txt"}); + assertDeleted("testRenameUnshared", project, new String[] {"oldName.txt"}); - assertSyncEquals("testRenameUnshared", project, - new String[] { "newName.txt"}, - true, new int[] { - SyncInfo.OUTGOING | SyncInfo.ADDITION}); + assertSyncEquals("testRenameUnshared", project, + new String[] { "newName.txt"}, + true, new int[] { + SyncInfo.OUTGOING | SyncInfo.ADDITION}); } public void testOutgoingEmptyFolder() throws CoreException, TeamException { @@ -1209,9 +1209,9 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { // The files should show up as outgoing deletions assertSyncEquals("testConflictingFolderDeletion sync check", project, - new String[] { "folder1/", "folder1/a.txt", "folder1/b.txt"}, - true, new int[] { - SyncInfo.IN_SYNC, + new String[] { "folder1/", "folder1/a.txt", "folder1/b.txt"}, + true, new int[] { + SyncInfo.IN_SYNC, SyncInfo.IN_SYNC, /* conflicting deletions are handled automatically */ SyncInfo.IN_SYNC}); } @@ -1233,7 +1233,7 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { assertSyncEquals("testProjectClose sync check", project, new String[] { "file1.txt"}, true, new int[] { - SyncInfo.OUTGOING | SyncInfo.CHANGE, + SyncInfo.OUTGOING | SyncInfo.CHANGE, }); project.close(null); @@ -1396,61 +1396,61 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { assertTrue(project.getFile("file1.txt").exists()); } - public void testBinaryAddition() throws CoreException { - // See bug 132255 - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); + public void testBinaryAddition() throws CoreException { + // See bug 132255 + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); // Checkout a copy - IProject copy = checkoutCopy(project, "-copy"); + IProject copy = checkoutCopy(project, "-copy"); // Add a binary file that contains LFs - create(copy.getFile("binaryFile"), true); - setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { copy.getFile("binaryFile") }); - commitProject(copy); - // Update - getSyncInfoSource().refresh(getSubscriber(), project); - getSyncInfoSource().updateResources(getSubscriber(), new IResource[] { project.getFile("binaryFile") }); - assertContentsEqual(copy.getFile("binaryFile"), project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } - - public void testBinaryMarkAsMerged() throws CoreException, InvocationTargetException, InterruptedException { - KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); - try { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); - IProject project = createProject(new String[] { "a.txt"}); + create(copy.getFile("binaryFile"), true); + setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { copy.getFile("binaryFile") }); + commitProject(copy); + // Update + getSyncInfoSource().refresh(getSubscriber(), project); + getSyncInfoSource().updateResources(getSubscriber(), new IResource[] { project.getFile("binaryFile") }); + assertContentsEqual(copy.getFile("binaryFile"), project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } + + public void testBinaryMarkAsMerged() throws CoreException, InvocationTargetException, InterruptedException { + KSubstOption option = CVSProviderPlugin.getPlugin().getDefaultTextKSubstOption(); + try { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(Command.KSUBST_TEXT_KEYWORDS_ONLY); + IProject project = createProject(new String[] { "a.txt"}); // Checkout a copy - IProject copy = checkoutCopy(project, "-copy"); + IProject copy = checkoutCopy(project, "-copy"); // Add a binary file to the copy and commit - create(copy.getFile("binaryFile"), true); - setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); - addResources(new IResource[] { copy.getFile("binaryFile") }); - commitProject(copy); - // Add the same file to the project but don't share it - create(project.getFile("binaryFile"), true); - setContentsAndEnsureModified(project.getFile("binaryFile"), "/n/nSome Content\n\n"); - // Sync and mark as merged - getSyncInfoSource().refresh(getSubscriber(), project); - getSyncInfoSource().markAsMerged(getSubscriber(), new IResource[] { project.getFile("binaryFile") }); - assertIsBinary(project.getFile("binaryFile")); - } finally { - CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); - } - } - - public void testDisabledDirectoryDiscovery() throws CoreException { - // Create a project and disable new directory discovery - IProject project = createProject(new String[] { "file1.txt"}); - setFetchAbsentDirectories(project, false); - - IProject copy = checkoutCopy(project, "-copy"); - addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, true); - - // The new subfolder (folder2) and its contents should not have sync info (i.e. in_sync) + create(copy.getFile("binaryFile"), true); + setContentsAndEnsureModified(copy.getFile("binaryFile"), "/n/n\n\n"); + addResources(new IResource[] { copy.getFile("binaryFile") }); + commitProject(copy); + // Add the same file to the project but don't share it + create(project.getFile("binaryFile"), true); + setContentsAndEnsureModified(project.getFile("binaryFile"), "/n/nSome Content\n\n"); + // Sync and mark as merged + getSyncInfoSource().refresh(getSubscriber(), project); + getSyncInfoSource().markAsMerged(getSubscriber(), new IResource[] { project.getFile("binaryFile") }); + assertIsBinary(project.getFile("binaryFile")); + } finally { + CVSProviderPlugin.getPlugin().setDefaultTextKSubstOption(option); + } + } + + public void testDisabledDirectoryDiscovery() throws CoreException { + // Create a project and disable new directory discovery + IProject project = createProject(new String[] { "file1.txt"}); + setFetchAbsentDirectories(project, false); + + IProject copy = checkoutCopy(project, "-copy"); + addResources(copy, new String[] { "added.txt", "folder2/", "folder2/added.txt" }, true); + + // The new subfolder (folder2) and its contents should not have sync info (i.e. in_sync) assertSyncEquals("testDisabledDirectoryDiscovery", project, new String[] {"file1.txt", "added.txt", "folder2/", "folder2/added.txt" }, true, new int[] { @@ -1459,7 +1459,7 @@ public class CVSWorkspaceSubscriberTest extends CVSSyncSubscriberTest { SyncInfo.IN_SYNC, SyncInfo.IN_SYNC }); - } + } private void setFetchAbsentDirectories(IProject project, boolean fetch) throws CVSException { RepositoryProvider provider = RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java index 02dd4d60a..e91264443 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/SyncInfoSource.java @@ -104,10 +104,10 @@ public class SyncInfoSource { /** * Refresh the subscriber for the given resources */ - public void refresh(Subscriber subscriber, IResource[] resources) throws TeamException { - subscriber.refresh(resources, IResource.DEPTH_INFINITE, DEFAULT_MONITOR); - } - + public void refresh(Subscriber subscriber, IResource[] resources) throws TeamException { + subscriber.refresh(resources, IResource.DEPTH_INFINITE, DEFAULT_MONITOR); + } + protected void assertProjectRemoved(Subscriber subscriber, IProject project) { IResource[] roots = subscriber.roots(); for (int i = 0; i < roots.length; i++) { @@ -147,8 +147,8 @@ public class SyncInfoSource { assertDiffKindEquals(message, subscriber, resource, SyncInfoToDiffConverter.asDiffFlags(syncKind)); } Assert.assertTrue(message + ": improper sync state for " + resource + " expected " + - SyncInfo.kindToString(kindOther) + " but was " + - SyncInfo.kindToString(kind), kind == kindOther); + SyncInfo.kindToString(kindOther) + " but was " + + SyncInfo.kindToString(kind), kind == kindOther); } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/TestUpdateOperation.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/TestUpdateOperation.java index f9df87569..937d8704c 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/TestUpdateOperation.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/TestUpdateOperation.java @@ -59,10 +59,10 @@ class TestUpdateOperation extends WorkspaceUpdateOperation { UpdateOnlyMergableOperation operation = new UpdateOnlyMergableOperation(getPart(), project, resources, localOptions) { @Override public ISynchronizationScope buildScope(IProgressMonitor monitor) throws InterruptedException, CVSException { - if (getScopeManager() == null) { - // manager = createScopeManager(consultModelsWhenBuildingScope && consultModelsForMappings()); - ReflectionUtils.setField(this, "manager", createScopeManager(consultModelsWhenBuildingScope && consultModelsForMappings())); - BuildScopeOperation op = new BuildScopeOperation(getPart(), getScopeManager()) { + if (getScopeManager() == null) { + // manager = createScopeManager(consultModelsWhenBuildingScope && consultModelsForMappings()); + ReflectionUtils.setField(this, "manager", createScopeManager(consultModelsWhenBuildingScope && consultModelsForMappings())); + BuildScopeOperation op = new BuildScopeOperation(getPart(), getScopeManager()) { @Override protected boolean promptForInputChange(String requestPreviewMessage, IProgressMonitor monitor) { return false; // do not prompt @@ -73,8 +73,8 @@ class TestUpdateOperation extends WorkspaceUpdateOperation { } catch (InvocationTargetException e) { throw CVSException.wrapException(e); } - } - return getScope(); + } + return getScope(); } }; operation.run(monitor); diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/CommitSetTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/CommitSetTests.java index 2e98c7369..cea7238a4 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/CommitSetTests.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/CommitSetTests.java @@ -42,169 +42,169 @@ public class CommitSetTests extends EclipseTest { private List<ChangeSet> addedSets = new ArrayList<>(); private List<ChangeSet> removedSets = new ArrayList<>(); private IChangeSetChangeListener listener = new IChangeSetChangeListener() { - @Override + @Override public void setAdded(ChangeSet set) { - addedSets.add(set); - } - @Override + addedSets.add(set); + } + @Override public void setRemoved(ChangeSet set) { - removedSets.add(set); - } - @Override + removedSets.add(set); + } + @Override public void nameChanged(ChangeSet set) { - // TODO Auto-generated method stub + // TODO Auto-generated method stub - } - @Override + } + @Override public void defaultSetChanged(ChangeSet oldDefault, ChangeSet set) { - // TODO Auto-generated method stub - - } - @Override + // TODO Auto-generated method stub + + } + @Override public void resourcesChanged(ChangeSet set, IPath[] paths) { - // TODO Auto-generated method stub - - } - }; + // TODO Auto-generated method stub + + } + }; - public static Test suite() { + public static Test suite() { return suite(CommitSetTests.class); } - public CommitSetTests() { - super(); - } - - public CommitSetTests(String name) { - super(name); - } - - /** - * Create a commit set and verify that it was created and contains the supplied files - * @param title the title of the new set - * @param files the files for the new set - * @return the newly create commit set - * @throws TeamException - */ - protected ActiveChangeSet createCommitSet(String title, IFile[] files, boolean manageSet) throws CoreException { - assertIsModified(getName(), files); - ActiveChangeSetManager manager = CVSUIPlugin.getPlugin().getChangeSetManager(); - ActiveChangeSet set = manager.createSet(title, files); - assertEquals("Not all files were added to the set", files.length, set.getResources().length); - if (manageSet) { - manager.add(set); - waitForSetAddedEvent(set); - } - return set; - } + public CommitSetTests() { + super(); + } + + public CommitSetTests(String name) { + super(name); + } + + /** + * Create a commit set and verify that it was created and contains the supplied files + * @param title the title of the new set + * @param files the files for the new set + * @return the newly create commit set + * @throws TeamException + */ + protected ActiveChangeSet createCommitSet(String title, IFile[] files, boolean manageSet) throws CoreException { + assertIsModified(getName(), files); + ActiveChangeSetManager manager = CVSUIPlugin.getPlugin().getChangeSetManager(); + ActiveChangeSet set = manager.createSet(title, files); + assertEquals("Not all files were added to the set", files.length, set.getResources().length); + if (manageSet) { + manager.add(set); + waitForSetAddedEvent(set); + } + return set; + } - /** - * Commit the files in the given set to the repository - * and ensure that the files are in the proper state - * @param set the commit set - * @throws CVSException - */ - protected void commit(ActiveChangeSet set) throws CoreException { - boolean isManaged = setIsManaged(set); - commitResources(set.getResources(), IResource.DEPTH_ZERO); - if (isManaged) { - // Committing the set should remove it from the manager - waitForSetRemovedEvent(set); - } - } - - private boolean setIsManaged(ActiveChangeSet set) { - return CVSUIPlugin.getPlugin().getChangeSetManager().contains(set); - } + /** + * Commit the files in the given set to the repository + * and ensure that the files are in the proper state + * @param set the commit set + * @throws CVSException + */ + protected void commit(ActiveChangeSet set) throws CoreException { + boolean isManaged = setIsManaged(set); + commitResources(set.getResources(), IResource.DEPTH_ZERO); + if (isManaged) { + // Committing the set should remove it from the manager + waitForSetRemovedEvent(set); + } + } + + private boolean setIsManaged(ActiveChangeSet set) { + return CVSUIPlugin.getPlugin().getChangeSetManager().contains(set); + } - private void waitForSetAddedEvent(ActiveChangeSet set) { - int count = 0; - while (count < 5) { - if (addedSets.contains(set)) { - addedSets.remove(set); - return; - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // keep going - } - count++; - } - fail("Did not receive expected set added event"); - } + private void waitForSetAddedEvent(ActiveChangeSet set) { + int count = 0; + while (count < 5) { + if (addedSets.contains(set)) { + addedSets.remove(set); + return; + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // keep going + } + count++; + } + fail("Did not receive expected set added event"); + } - private void waitForSetRemovedEvent(ActiveChangeSet set) { - int count = 0; - while (count < 5) { - if (removedSets.contains(set)) { - removedSets.remove(set); - return; - } - try { - while (Display.getCurrent().readAndDispatch()) {} - Thread.sleep(1000); - } catch (InterruptedException e) { - // keep going - } - count++; - } - fail("Did not receive expected set removed event"); - } - + private void waitForSetRemovedEvent(ActiveChangeSet set) { + int count = 0; + while (count < 5) { + if (removedSets.contains(set)) { + removedSets.remove(set); + return; + } + try { + while (Display.getCurrent().readAndDispatch()) {} + Thread.sleep(1000); + } catch (InterruptedException e) { + // keep going + } + count++; + } + fail("Did not receive expected set removed event"); + } + @Override - protected void setUp() throws Exception { - super.setUp(); - CVSUIPlugin.getPlugin().getChangeSetManager().addListener(listener); - } - + protected void setUp() throws Exception { + super.setUp(); + CVSUIPlugin.getPlugin().getChangeSetManager().addListener(listener); + } + @Override - protected void tearDown() throws Exception { - super.tearDown(); - CVSUIPlugin.getPlugin().getChangeSetManager().removeListener(listener); - } - - /** - * Test a simple commit of a commit set. The set being committed is not managed. - * @throws CoreException - * @throws IOException - * @throws TeamException - */ - public void testSimpleCommit() throws TeamException, CoreException, IOException { - IProject project = createProject(new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt" }); - setContentsAndEnsureModified(project.getFile("changed.txt")); - deleteResources(project, new String[] { "deleted.txt" }, false /* don't commit */); - addResources(project, new String[] { "added.txt" }, false /* don't commit */); - - IFile[] files = new IFile[] { - project.getFile("changed.txt"), - project.getFile("deleted.txt"), - project.getFile("added.txt")}; - ActiveChangeSet set = createCommitSet("testSimpleCommit", files, false /* do not manage the set */); - commit(set); - assertLocalStateEqualsRemote(project); - } - - /** - * Test a managed commit of a commit set. The set being committed is managed - * and should be removed once the commit succeeds. - * @throws CoreException - * @throws IOException - * @throws TeamException - */ - public void testManagedCommit() throws TeamException, CoreException, IOException { - IProject project = createProject(new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt" }); - setContentsAndEnsureModified(project.getFile("changed.txt")); - deleteResources(project, new String[] { "deleted.txt" }, false /* don't commit */); - addResources(project, new String[] { "added.txt" }, false /* don't commit */); - - IFile[] files = new IFile[] { - project.getFile("changed.txt"), - project.getFile("deleted.txt"), - project.getFile("added.txt")}; - ActiveChangeSet set = createCommitSet("testSimpleCommit", files, true /* manage the set */); - commit(set); - assertLocalStateEqualsRemote(project); - } + protected void tearDown() throws Exception { + super.tearDown(); + CVSUIPlugin.getPlugin().getChangeSetManager().removeListener(listener); + } + + /** + * Test a simple commit of a commit set. The set being committed is not managed. + * @throws CoreException + * @throws IOException + * @throws TeamException + */ + public void testSimpleCommit() throws TeamException, CoreException, IOException { + IProject project = createProject(new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt" }); + setContentsAndEnsureModified(project.getFile("changed.txt")); + deleteResources(project, new String[] { "deleted.txt" }, false /* don't commit */); + addResources(project, new String[] { "added.txt" }, false /* don't commit */); + + IFile[] files = new IFile[] { + project.getFile("changed.txt"), + project.getFile("deleted.txt"), + project.getFile("added.txt")}; + ActiveChangeSet set = createCommitSet("testSimpleCommit", files, false /* do not manage the set */); + commit(set); + assertLocalStateEqualsRemote(project); + } + + /** + * Test a managed commit of a commit set. The set being committed is managed + * and should be removed once the commit succeeds. + * @throws CoreException + * @throws IOException + * @throws TeamException + */ + public void testManagedCommit() throws TeamException, CoreException, IOException { + IProject project = createProject(new String[] { "changed.txt", "deleted.txt", "folder1/", "folder1/a.txt" }); + setContentsAndEnsureModified(project.getFile("changed.txt")); + deleteResources(project, new String[] { "deleted.txt" }, false /* don't commit */); + addResources(project, new String[] { "added.txt" }, false /* don't commit */); + + IFile[] files = new IFile[] { + project.getFile("changed.txt"), + project.getFile("deleted.txt"), + project.getFile("added.txt")}; + ActiveChangeSet set = createCommitSet("testSimpleCommit", files, true /* manage the set */); + commit(set); + assertLocalStateEqualsRemote(project); + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ModelParticipantSyncInfoSource.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ModelParticipantSyncInfoSource.java index 20d6a61cd..4961b670c 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ModelParticipantSyncInfoSource.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ModelParticipantSyncInfoSource.java @@ -553,21 +553,21 @@ public class ModelParticipantSyncInfoSource extends ParticipantSyncInfoSource { } private ModelSynchronizePage getPage(Subscriber subscriber) { - try { - ModelSynchronizeParticipant participant = getParticipant(subscriber); - if (participant == null) - throw new AssertionFailedError("The participant for " + subscriber.getName() + " could not be retrieved"); - IWorkbenchPage activePage = TeamUIPlugin.getActivePage(); - ISynchronizeView view = (ISynchronizeView)activePage.showView(ISynchronizeView.VIEW_ID); - IPage page = ((SynchronizeView)view).getPage(participant); - if (page instanceof ModelSynchronizePage) { - ModelSynchronizePage subscriberPage = (ModelSynchronizePage)page; - return subscriberPage; - } - } catch (PartInitException e) { - throw new AssertionFailedError("Cannot show sync view in active page"); - } - throw new AssertionFailedError("The page for " + subscriber.getName() + " could not be retrieved"); + try { + ModelSynchronizeParticipant participant = getParticipant(subscriber); + if (participant == null) + throw new AssertionFailedError("The participant for " + subscriber.getName() + " could not be retrieved"); + IWorkbenchPage activePage = TeamUIPlugin.getActivePage(); + ISynchronizeView view = (ISynchronizeView)activePage.showView(ISynchronizeView.VIEW_ID); + IPage page = ((SynchronizeView)view).getPage(participant); + if (page instanceof ModelSynchronizePage) { + ModelSynchronizePage subscriberPage = (ModelSynchronizePage)page; + return subscriberPage; + } + } catch (PartInitException e) { + throw new AssertionFailedError("Cannot show sync view in active page"); + } + throw new AssertionFailedError("The page for " + subscriber.getName() + " could not be retrieved"); } @Override @@ -584,7 +584,7 @@ public class ModelParticipantSyncInfoSource extends ParticipantSyncInfoSource { assertTreeMatchesDiffs(rootItems, copy); } - private void assertTreeMatchesDiffs(TreeItem[] rootItems, ResourceDiffTree copy) { + private void assertTreeMatchesDiffs(TreeItem[] rootItems, ResourceDiffTree copy) { assertItemsInDiffTree(rootItems, copy); if (!copy.isEmpty()) { new AssertionFailedError("Viewer is not showing all diffs"); @@ -592,10 +592,10 @@ public class ModelParticipantSyncInfoSource extends ParticipantSyncInfoSource { } private void assertItemsInDiffTree(TreeItem[] items, ResourceDiffTree copy) { - if (items == null || items.length == 0) { - return; - } - for (TreeItem item : items) { + if (items == null || items.length == 0) { + return; + } + for (TreeItem item : items) { assertItemInTree(item, copy); } @@ -623,15 +623,15 @@ public class ModelParticipantSyncInfoSource extends ParticipantSyncInfoSource { } private TreeItem[] getTreeItems(Subscriber subscriber) { - ModelSynchronizePage page = getPage(subscriber); - Viewer v = page.getViewer(); - if (v instanceof TreeViewer) { - TreeViewer treeViewer = (TreeViewer)v; - treeViewer.expandAll(); - Tree t = (treeViewer).getTree(); - return t.getItems(); - } - throw new AssertionFailedError("The tree for " + subscriber.getName() + " could not be retrieved"); - } + ModelSynchronizePage page = getPage(subscriber); + Viewer v = page.getViewer(); + if (v instanceof TreeViewer) { + TreeViewer treeViewer = (TreeViewer)v; + treeViewer.expandAll(); + Tree t = (treeViewer).getTree(); + return t.getItems(); + } + throw new AssertionFailedError("The tree for " + subscriber.getName() + " could not be retrieved"); + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ParticipantSyncInfoSource.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ParticipantSyncInfoSource.java index f29eaefcd..76818f070 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ParticipantSyncInfoSource.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/ParticipantSyncInfoSource.java @@ -33,13 +33,13 @@ import org.eclipse.ui.part.IPage; public class ParticipantSyncInfoSource extends SyncInfoSource { - public static ISynchronizePage getSyncViewPage(ISynchronizeParticipant participant) throws PartInitException { + public static ISynchronizePage getSyncViewPage(ISynchronizeParticipant participant) throws PartInitException { IWorkbenchPage activePage = TeamUIPlugin.getActivePage(); ISynchronizeView view = (ISynchronizeView)activePage.showView(ISynchronizeView.VIEW_ID); IPage page = ((SynchronizeView)view).getPage(participant); return (ISynchronizePage)page; } - + public ParticipantSyncInfoSource() { IWorkbenchPage activePage = TeamUIPlugin.getActivePage(); try { @@ -91,13 +91,13 @@ public class ParticipantSyncInfoSource extends SyncInfoSource { * @param subscriber the subscriber */ public void assertViewMatchesModel(Subscriber subscriber) { - // Default is to do nothing. Subclasses may override + // Default is to do nothing. Subclasses may override } - public void refresh(Subscriber subscriber, IResource[] resources) - throws TeamException { - super.refresh(subscriber, resources); + public void refresh(Subscriber subscriber, IResource[] resources) + throws TeamException { + super.refresh(subscriber, resources); assertViewMatchesModel(subscriber); - } + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/PerspectiveFactory.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/PerspectiveFactory.java index 6593a2821..1c261e7f4 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/PerspectiveFactory.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/PerspectiveFactory.java @@ -18,11 +18,11 @@ import org.eclipse.ui.IPerspectiveFactory; public class PerspectiveFactory implements IPerspectiveFactory { - public void createInitialLayout(IPageLayout layout) { - String editorArea = layout.getEditorArea(); - /* IFolderLayout top = */ - layout.createFolder("top", IPageLayout.LEFT, 0.40f, editorArea); //$NON-NLS-1$ - layout.setEditorAreaVisible(true); - } + public void createInitialLayout(IPageLayout layout) { + String editorArea = layout.getEditorArea(); + /* IFolderLayout top = */ + layout.createFolder("top", IPageLayout.LEFT, 0.40f, editorArea); //$NON-NLS-1$ + layout.setEditorAreaVisible(true); + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/SubscriberParticipantSyncInfoSource.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/SubscriberParticipantSyncInfoSource.java index a7e1eec16..d70fa95d3 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/SubscriberParticipantSyncInfoSource.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/SubscriberParticipantSyncInfoSource.java @@ -134,10 +134,10 @@ public class SubscriberParticipantSyncInfoSource extends ParticipantSyncInfoSour if (participant == null) return null; SubscriberSyncInfoCollector syncInfoCollector = participant.getSubscriberSyncInfoCollector(); EclipseTest.waitForSubscriberInputHandling(syncInfoCollector); - SubscriberParticipantPage page = getPage(subscriber); - SynchronizeModelManager manager = (SynchronizeModelManager)page.getConfiguration().getProperty(SynchronizePageConfiguration.P_MODEL_MANAGER); - AbstractSynchronizeModelProvider provider = (AbstractSynchronizeModelProvider)manager.getActiveModelProvider(); - provider.waitUntilDone(new IProgressMonitor() { + SubscriberParticipantPage page = getPage(subscriber); + SynchronizeModelManager manager = (SynchronizeModelManager)page.getConfiguration().getProperty(SynchronizePageConfiguration.P_MODEL_MANAGER); + AbstractSynchronizeModelProvider provider = (AbstractSynchronizeModelProvider)manager.getActiveModelProvider(); + provider.waitUntilDone(new IProgressMonitor() { @Override public void beginTask(String name, int totalWork) { } @@ -211,91 +211,91 @@ public class SubscriberParticipantSyncInfoSource extends ParticipantSyncInfoSour return findSyncInfo(root, resource); } - private SyncInfo findSyncInfo(ISynchronizeModelElement node, IResource resource) { - if (node instanceof SyncInfoModelElement) { - SyncInfoModelElement element = (SyncInfoModelElement)node; - if (element.getResource().equals(resource)) { - return element.getSyncInfo(); - } - } - IDiffElement[] children = node.getChildren(); - for (IDiffElement element : children) { - ISynchronizeModelElement child = (ISynchronizeModelElement)element; - SyncInfo info = findSyncInfo(child, resource); - if (info != null) - return info; - } - return null; - } - - @Override + private SyncInfo findSyncInfo(ISynchronizeModelElement node, IResource resource) { + if (node instanceof SyncInfoModelElement) { + SyncInfoModelElement element = (SyncInfoModelElement)node; + if (element.getResource().equals(resource)) { + return element.getSyncInfo(); + } + } + IDiffElement[] children = node.getChildren(); + for (IDiffElement element : children) { + ISynchronizeModelElement child = (ISynchronizeModelElement)element; + SyncInfo info = findSyncInfo(child, resource); + if (info != null) + return info; + } + return null; + } + + @Override public void assertViewMatchesModel(Subscriber subscriber) { - // Getting the collector waits for the subscriber input handlers - getCollector(subscriber); + // Getting the collector waits for the subscriber input handlers + getCollector(subscriber); ISynchronizeModelElement root = getModelRoot(subscriber); TreeItem[] rootItems = getTreeItems(subscriber); assertMatchingTrees(root, rootItems, root.getChildren()); - } + } - private ISynchronizeModelElement getModelRoot(Subscriber subscriber) { - SubscriberParticipantPage page = getPage(subscriber); - return ((TreeViewerAdvisor)page.getViewerAdvisor()).getModelManager().getModelRoot(); - } - - private TreeItem[] getTreeItems(Subscriber subscriber) { - SubscriberParticipantPage page = getPage(subscriber); - Viewer v = page.getViewer(); - if (v instanceof TreeViewer) { - TreeViewer treeViewer = (TreeViewer)v; - treeViewer.expandAll(); - Tree t = (treeViewer).getTree(); - return t.getItems(); - } - throw new AssertionFailedError("The tree for " + subscriber.getName() + " could not be retrieved"); - } + private ISynchronizeModelElement getModelRoot(Subscriber subscriber) { + SubscriberParticipantPage page = getPage(subscriber); + return ((TreeViewerAdvisor)page.getViewerAdvisor()).getModelManager().getModelRoot(); + } + + private TreeItem[] getTreeItems(Subscriber subscriber) { + SubscriberParticipantPage page = getPage(subscriber); + Viewer v = page.getViewer(); + if (v instanceof TreeViewer) { + TreeViewer treeViewer = (TreeViewer)v; + treeViewer.expandAll(); + Tree t = (treeViewer).getTree(); + return t.getItems(); + } + throw new AssertionFailedError("The tree for " + subscriber.getName() + " could not be retrieved"); + } - private static SubscriberParticipantPage getPage(Subscriber subscriber) { - try { - SubscriberParticipant participant = getParticipant(subscriber); - if (participant == null) - throw new AssertionFailedError("The participant for " + subscriber.getName() + " could not be retrieved"); - IWorkbenchPage activePage = TeamUIPlugin.getActivePage(); - ISynchronizeView view = (ISynchronizeView)activePage.showView(ISynchronizeView.VIEW_ID); - IPage page = ((SynchronizeView)view).getPage(participant); - if (page instanceof SubscriberParticipantPage) { - SubscriberParticipantPage subscriberPage = (SubscriberParticipantPage)page; - return subscriberPage; - } - } catch (PartInitException e) { - throw new AssertionFailedError("Cannot show sync view in active page"); - } - throw new AssertionFailedError("The page for " + subscriber.getName() + " could not be retrieved"); - } - - private void assertMatchingTrees(IDiffElement parent, TreeItem[] items, IDiffElement[] children) { - if ((items == null || items.length == 0) && (children == null || children.length == 0)) { - // No children in either case so just return - return; - } - if (items == null || children == null || items.length != children.length) { - throw new AssertionFailedError("The number of children of " + parent.getName() + " is " + - (children == null ? 0: children.length) + " but the view has " + - (items == null ? 0 : items.length)); - } - for (IDiffElement element : children) { - TreeItem foundItem = null; - for (TreeItem item : items) { - if (item.getData() == element) { - foundItem = item; - break; - } - } - if (foundItem == null) { - throw new AssertionFailedError("Element" + element.getName() + " is in the model but not in the view"); - } else { - assertMatchingTrees(element, foundItem.getItems(), ((IDiffContainer)element).getChildren()); - } - } - - } + private static SubscriberParticipantPage getPage(Subscriber subscriber) { + try { + SubscriberParticipant participant = getParticipant(subscriber); + if (participant == null) + throw new AssertionFailedError("The participant for " + subscriber.getName() + " could not be retrieved"); + IWorkbenchPage activePage = TeamUIPlugin.getActivePage(); + ISynchronizeView view = (ISynchronizeView)activePage.showView(ISynchronizeView.VIEW_ID); + IPage page = ((SynchronizeView)view).getPage(participant); + if (page instanceof SubscriberParticipantPage) { + SubscriberParticipantPage subscriberPage = (SubscriberParticipantPage)page; + return subscriberPage; + } + } catch (PartInitException e) { + throw new AssertionFailedError("Cannot show sync view in active page"); + } + throw new AssertionFailedError("The page for " + subscriber.getName() + " could not be retrieved"); + } + + private void assertMatchingTrees(IDiffElement parent, TreeItem[] items, IDiffElement[] children) { + if ((items == null || items.length == 0) && (children == null || children.length == 0)) { + // No children in either case so just return + return; + } + if (items == null || children == null || items.length != children.length) { + throw new AssertionFailedError("The number of children of " + parent.getName() + " is " + + (children == null ? 0: children.length) + " but the view has " + + (items == null ? 0 : items.length)); + } + for (IDiffElement element : children) { + TreeItem foundItem = null; + for (TreeItem item : items) { + if (item.getData() == element) { + foundItem = item; + break; + } + } + if (foundItem == null) { + throw new AssertionFailedError("Element" + element.getName() + " is in the model but not in the view"); + } else { + assertMatchingTrees(element, foundItem.getItems(), ((IDiffContainer)element).getChildren()); + } + } + + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/AllBenchmarkTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/AllBenchmarkTests.java index a95e8edae..59f4c5cfe 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/AllBenchmarkTests.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/AllBenchmarkTests.java @@ -32,7 +32,7 @@ public class AllBenchmarkTests extends EclipseTest { TestSuite suite = new TestSuite(); suite.addTest(WorkflowTests.suite()); suite.addTest(SyncTests.suite()); - // TODO: Enable decorators? + // TODO: Enable decorators? return new CVSTestSetup(suite); } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTest.java index e8fd6b18a..ebb4434da 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTest.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTest.java @@ -43,9 +43,9 @@ import org.eclipse.ui.handlers.IHandlerService; public abstract class BenchmarkTest extends EclipseTest { private HashMap<String, PerformanceMeter> groups; - private PerformanceMeter currentMeter; + private PerformanceMeter currentMeter; - protected BenchmarkTest() { + protected BenchmarkTest() { } protected BenchmarkTest(String name) { @@ -63,30 +63,30 @@ public abstract class BenchmarkTest extends EclipseTest { return project; } - /** - * @param string - */ - protected void startTask(String string) { - // TODO Auto-generated method stub - - } - /** - * - */ + * @param string + */ + protected void startTask(String string) { + // TODO Auto-generated method stub + + } + + /** + * + */ protected void endTask() { - // TODO Auto-generated method stub - - } + // TODO Auto-generated method stub + + } - /** - * Create a set of performance meters that can be started with the - * startGroup method. - * @param performance_groups - */ + /** + * Create a set of performance meters that can be started with the + * startGroup method. + * @param performance_groups + */ protected void setupGroups(String[] performance_groups) { - setupGroups(performance_groups, null, false); - } + setupGroups(performance_groups, null, false); + } protected void setupGroups(String[] performance_groups, String globalName, boolean global) { groups = new HashMap<>(); @@ -103,127 +103,127 @@ public abstract class BenchmarkTest extends EclipseTest { // Use a meter for each group, provides fine grain results for (String suffix : performance_groups) { meter = perf.createPerformanceMeter(perf.getDefaultScenarioId(this) + suffix); - Performance.getDefault().setComment(meter, Performance.EXPLAINS_DEGRADATION_COMMENT, "The current setup for the CVS test does not provide reliable timings. Only consistent test failures over time can be considered significant."); + Performance.getDefault().setComment(meter, Performance.EXPLAINS_DEGRADATION_COMMENT, "The current setup for the CVS test does not provide reliable timings. Only consistent test failures over time can be considered significant."); groups.put(suffix, meter); // if (globalName != null) { // perf.tagAsSummary(meter, suffix, Dimension.ELAPSED_PROCESS); // } } } - } - - /** + } + + /** * Commit the performance meters that were created by setupGroups and * started and stopped using startGroup/endGroup */ - protected void commitGroups(boolean global) { + protected void commitGroups(boolean global) { for (PerformanceMeter meter : groups.values()) { - meter.commit(); - if(global) - break; - } - } - - @Override + meter.commit(); + if(global) + break; + } + } + + @Override protected void setUp() throws Exception { - super.setUp(); - setModelSync(false); - } - - @Override + super.setUp(); + setModelSync(false); + } + + @Override protected void tearDown() throws Exception { - try { - if (groups != null) { - Performance perf = Performance.getDefault(); - try { + try { + if (groups != null) { + Performance perf = Performance.getDefault(); + try { for (PerformanceMeter meter : groups.values()) { perf.assertPerformanceInRelativeBand(meter, Dimension.ELAPSED_PROCESS, -100, 20); - } - } finally { + } + } finally { for (PerformanceMeter meter : groups.values()) { - meter.dispose(); - } - } - groups = null; - } - } finally { - super.tearDown(); - } - } - - /** - * Start the meter that was created for the given key - * @param string - */ - protected void startGroup(String key) { - assertNull(currentMeter); - currentMeter = groups.get(key); - currentMeter.start(); - } - + meter.dispose(); + } + } + groups = null; + } + } finally { + super.tearDown(); + } + } + /** - * End the current meter - */ + * Start the meter that was created for the given key + * @param string + */ + protected void startGroup(String key) { + assertNull(currentMeter); + currentMeter = groups.get(key); + currentMeter.start(); + } + + /** + * End the current meter + */ protected void endGroup() { - currentMeter.stop(); - currentMeter = null; - } + currentMeter.stop(); + currentMeter = null; + } protected void disableLog() { - // TODO: + // TODO: } protected void enableLog() { - // TODO: + // TODO: } protected void syncResources(SyncInfoSource source, Subscriber subscriber, IResource[] resources) throws TeamException { - startTask("Synchronize with Repository action"); - source.refresh(subscriber, resources); - endTask(); + startTask("Synchronize with Repository action"); + source.refresh(subscriber, resources); + endTask(); } - /** - * @param resources - * @param string - * @throws CoreException - * @throws TeamException - */ - protected void syncCommitResources(SyncInfoSource source, IResource[] resources, String comment) throws TeamException, CoreException { - startTask("Synchronize outgoing changes"); - syncResources(source, source.createWorkspaceSubscriber(), resources); - endTask(); - // TODO: Commit all outgoing changes that are children of the given resource - // by extracting them from the subscriber sync set - startTask("Commit outgoing changes"); - commitResources(resources, IResource.DEPTH_INFINITE); - endTask(); - } - - /** - * @param resources - * @throws TeamException - */ - protected void syncUpdateResources(SyncInfoSource source, IResource[] resources) throws TeamException { - startTask("Synchronize incoming changes"); - syncResources(source, source.createWorkspaceSubscriber(), resources); - endTask(); - // TODO: Update all incoming changes that are children of the given resource - // by extracting them from the subscriber sync set - startTask("Update incoming changes"); - updateResources(resources, false); - endTask(); - } - - protected void openEmptyPerspective() throws WorkbenchException { - // First close any open perspectives + /** + * @param resources + * @param string + * @throws CoreException + * @throws TeamException + */ + protected void syncCommitResources(SyncInfoSource source, IResource[] resources, String comment) throws TeamException, CoreException { + startTask("Synchronize outgoing changes"); + syncResources(source, source.createWorkspaceSubscriber(), resources); + endTask(); + // TODO: Commit all outgoing changes that are children of the given resource + // by extracting them from the subscriber sync set + startTask("Commit outgoing changes"); + commitResources(resources, IResource.DEPTH_INFINITE); + endTask(); + } + + /** + * @param resources + * @throws TeamException + */ + protected void syncUpdateResources(SyncInfoSource source, IResource[] resources) throws TeamException { + startTask("Synchronize incoming changes"); + syncResources(source, source.createWorkspaceSubscriber(), resources); + endTask(); + // TODO: Update all incoming changes that are children of the given resource + // by extracting them from the subscriber sync set + startTask("Update incoming changes"); + updateResources(resources, false); + endTask(); + } + + protected void openEmptyPerspective() throws WorkbenchException { + // First close any open perspectives IHandlerService handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class); try { handlerService.executeCommand( "org.eclipse.ui.window.closeAllPerspectives", null); } catch (ExecutionException | NotDefinedException | NotEnabledException | NotHandledException e1) { } - // Now open our empty perspective - PlatformUI.getWorkbench().showPerspective("org.eclipse.team.tests.cvs.ui.perspective1", PlatformUI.getWorkbench().getActiveWorkbenchWindow()); - } + // Now open our empty perspective + PlatformUI.getWorkbench().showPerspective("org.eclipse.team.tests.cvs.ui.perspective1", PlatformUI.getWorkbench().getActiveWorkbenchWindow()); + } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTestSetup.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTestSetup.java index 2247ccd2c..fd6e8e311 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTestSetup.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/BenchmarkTestSetup.java @@ -32,7 +32,7 @@ public class BenchmarkTestSetup extends CVSTestSetup { // Static initializer for constants static { - try { + try { LOOP_COUNT = Integer.valueOf(System.getProperty("eclipse.cvs.loopCount", "6")).intValue(); } catch (NumberFormatException e1) { LOOP_COUNT = 1; diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/Bug152581Test.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/Bug152581Test.java index 90c89a3f5..aa9ceb720 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/Bug152581Test.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/Bug152581Test.java @@ -38,8 +38,8 @@ public class Bug152581Test extends BenchmarkTest { private static final String OLD_SYNCHRONIZE_GROUP_SUFFIX2 = "OldSynchronize2"; private static final String NEW_SYNCHRONIZE_GROUP_SUFFIX2 = "NewSynchronize2"; private static final String UPDATE_GROUP_SUFFIX2 = "Update2"; - private static final String[] PERFORMANCE_GROUPS = new String[] {OLD_SYNCHRONIZE_GROUP_SUFFIX, NEW_SYNCHRONIZE_GROUP_SUFFIX, UPDATE_GROUP_SUFFIX, OLD_SYNCHRONIZE_GROUP_SUFFIX2, NEW_SYNCHRONIZE_GROUP_SUFFIX2, UPDATE_GROUP_SUFFIX2}; - + private static final String[] PERFORMANCE_GROUPS = new String[] {OLD_SYNCHRONIZE_GROUP_SUFFIX, NEW_SYNCHRONIZE_GROUP_SUFFIX, UPDATE_GROUP_SUFFIX, OLD_SYNCHRONIZE_GROUP_SUFFIX2, NEW_SYNCHRONIZE_GROUP_SUFFIX2, UPDATE_GROUP_SUFFIX2}; + public Bug152581Test() { super(); } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/SyncTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/SyncTests.java index 6b1393fdb..77e3d43bc 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/SyncTests.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/SyncTests.java @@ -28,7 +28,7 @@ public class SyncTests extends BenchmarkTest { private static final String ADDED_GROUP_SUFFIX = "AddedFiles"; private static final String REMOVED_GROUP_SUFFIX = "RemovedFiles"; private static final String MODIFIED_GROUP_SUFFIX = "ModifiedFiles"; - private static final String[] PERFORMANCE_GROUPS = new String[] {ADDED_GROUP_SUFFIX, MODIFIED_GROUP_SUFFIX, REMOVED_GROUP_SUFFIX}; + private static final String[] PERFORMANCE_GROUPS = new String[] {ADDED_GROUP_SUFFIX, MODIFIED_GROUP_SUFFIX, REMOVED_GROUP_SUFFIX}; public SyncTests() { super(); @@ -41,10 +41,10 @@ public class SyncTests extends BenchmarkTest { public static Test suite() { return suite(SyncTests.class); } - - public void testSync100NoUI() throws Exception { - runTestSync(100, "CVS Synchronize No UI", false, new SyncInfoSource()); - } + + public void testSync100NoUI() throws Exception { + runTestSync(100, "CVS Synchronize No UI", false, new SyncInfoSource()); + } protected IProject setupOutProject() throws Exception { IProject project = createUniqueProject(BenchmarkTestSetup.SMALL_ZIP_FILE); @@ -57,9 +57,9 @@ public class SyncTests extends BenchmarkTest { * A parallel project is used to generate incoming changes. */ protected void runTestSync(int size, String globalName, boolean global, SyncInfoSource source) throws Exception { - openEmptyPerspective(); - setupGroups(PERFORMANCE_GROUPS, globalName, global); - for (int i = 0; i < BenchmarkTestSetup.LOOP_COUNT; i++) { + openEmptyPerspective(); + setupGroups(PERFORMANCE_GROUPS, globalName, global); + for (int i = 0; i < BenchmarkTestSetup.LOOP_COUNT; i++) { final SequenceGenerator gen = new SequenceGenerator(); // setup out project then move it out of the way @@ -90,7 +90,7 @@ public class SyncTests extends BenchmarkTest { syncCommitResources(source, new IResource[] { outProject }, ""); syncUpdateResources(source, new IResource[] { inProject }); endGroup(); - } - commitGroups(global); + } + commitGroups(global); } } diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/WorkflowTests.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/WorkflowTests.java index 1959a54d5..f236a8212 100644 --- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/WorkflowTests.java +++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/ui/benchmark/WorkflowTests.java @@ -30,24 +30,24 @@ public class WorkflowTests extends BenchmarkTest { private int FILE_SIZE_MEAN = 16384; private int FILE_SIZE_VARIANCE = 12288; private int PROB_BINARY = 5; - private static final String SHARE_PROJECT = "Share"; - private static final String CHECKOUT_PROJECT = "Checkout"; - private static final String COMMIT1 = "Commit1"; - private static final String COMMIT2 = "Commit2"; - private static final String COMMIT3 = "Commit3"; - private static final String COMMIT4 = "Commit4"; - private static final String UPDATE1 = "Update1"; - private static final String UPDATE2 = "Update2"; - private static final String UPDATE3 = "Update3"; - private static final String UPDATE4 = "Update4"; - private static final String REPLACE1 = "Replace1"; - private static final String REPLACE2 = "Replace2"; - private static final String REPLACE3 = "Replace3"; - private static final String TAG1 = "Tag1"; - private static final String[] PERFORMANCE_GROUPS = new String[] { - SHARE_PROJECT, CHECKOUT_PROJECT, COMMIT1, COMMIT2, COMMIT3, COMMIT4, - UPDATE1, UPDATE2, UPDATE3, UPDATE4, REPLACE1, REPLACE2, REPLACE3, TAG1 - }; + private static final String SHARE_PROJECT = "Share"; + private static final String CHECKOUT_PROJECT = "Checkout"; + private static final String COMMIT1 = "Commit1"; + private static final String COMMIT2 = "Commit2"; + private static final String COMMIT3 = "Commit3"; + private static final String COMMIT4 = "Commit4"; + private static final String UPDATE1 = "Update1"; + private static final String UPDATE2 = "Update2"; + private static final String UPDATE3 = "Update3"; + private static final String UPDATE4 = "Update4"; + private static final String REPLACE1 = "Replace1"; + private static final String REPLACE2 = "Replace2"; + private static final String REPLACE3 = "Replace3"; + private static final String TAG1 = "Tag1"; + private static final String[] PERFORMANCE_GROUPS = new String[] { + SHARE_PROJECT, CHECKOUT_PROJECT, COMMIT1, COMMIT2, COMMIT3, COMMIT4, + UPDATE1, UPDATE2, UPDATE3, UPDATE4, REPLACE1, REPLACE2, REPLACE3, TAG1 + }; public WorkflowTests() { super(); @@ -60,29 +60,29 @@ public class WorkflowTests extends BenchmarkTest { public static Test suite() { return suite(WorkflowTests.class); } - - public void testBigWorkflowNoUI() throws Exception { - runWorkflowTests("testBigWithNoUI", BenchmarkTestSetup.BIG_ZIP_FILE, "CVS Workflow No UI", BenchmarkTestSetup.LOOP_COUNT, false, new SyncInfoSource()); - } - protected void waitForBuild() { - super.waitForBuild(); - // Ensure that we can obtrain the worksapce lock before continuing - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - try { - Job.getJobManager().beginRule(root, null); - } finally { - Job.getJobManager().endRule(root); - } - } - + public void testBigWorkflowNoUI() throws Exception { + runWorkflowTests("testBigWithNoUI", BenchmarkTestSetup.BIG_ZIP_FILE, "CVS Workflow No UI", BenchmarkTestSetup.LOOP_COUNT, false, new SyncInfoSource()); + } + + protected void waitForBuild() { + super.waitForBuild(); + // Ensure that we can obtrain the worksapce lock before continuing + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + try { + Job.getJobManager().beginRule(root, null); + } finally { + Job.getJobManager().endRule(root); + } + } + /** * Runs a series of incoming and outgoing workflow-related tests. */ protected void runWorkflowTests(String name, File initialContents, String globalName, int loopCount, boolean global, SyncInfoSource source) throws Exception { - openEmptyPerspective(); - setupGroups(PERFORMANCE_GROUPS, globalName, global); - for (int i = 0; i < loopCount; i++) { + openEmptyPerspective(); + setupGroups(PERFORMANCE_GROUPS, globalName, global); + for (int i = 0; i < loopCount; i++) { final SequenceGenerator gen = new SequenceGenerator(); IProject outProject = createAndImportProject(name, initialContents); @@ -183,7 +183,7 @@ public class WorkflowTests extends BenchmarkTest { startGroup(REPLACE3); replace(new IResource[] { inProject }, null, true); endGroup(); - } - commitGroups(global); + } + commitGroups(global); } } |