diff --git a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java index 0633eccf591..f152303b6ee 100644 --- a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java +++ b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java @@ -82,11 +82,11 @@ public void run() { } - private ProjectionViewer fProjectionViewer; - private IAnnotationAccess fAnnotationAccess; + private final ProjectionViewer fProjectionViewer; + private final IAnnotationAccess fAnnotationAccess; private List fConfiguredAnnotationTypes; - private Object fLock= new Object(); + private final Object fLock= new Object(); private IProgressMonitor fProgressMonitor; private volatile Summarizer fSummarizer; diff --git a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java index 7b35568475b..beb5bb57fe1 100644 --- a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java +++ b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java @@ -143,9 +143,9 @@ public void projectionDisabled() { } } - private ProjectionViewer fViewer; - private IAnnotationAccess fAnnotationAccess; - private ISharedTextColors fSharedTextColors; + private final ProjectionViewer fViewer; + private final IAnnotationAccess fAnnotationAccess; + private final ISharedTextColors fSharedTextColors; private List fSummarizableTypes; private IInformationControlCreator fInformationControlCreator; private IInformationControlCreator fInformationPresenterControlCreator; diff --git a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java index 576c0212ec9..039aa9cfa0f 100644 --- a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java +++ b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java @@ -136,7 +136,7 @@ private void processModelChanged(IAnnotationModel model, AnnotationModelEvent ev */ private class ReplaceVisibleDocumentExecutor implements IDocumentListener { - private IDocument fSlaveDocument; + private final IDocument fSlaveDocument; private IDocument fExecutionTrigger; /** @@ -309,7 +309,7 @@ public void documentAboutToBeChanged(DocumentEvent event) { /** The projection annotation model used by this viewer. */ private ProjectionAnnotationModel fProjectionAnnotationModel; /** The annotation model listener */ - private IAnnotationModelListener fAnnotationModelListener= new AnnotationModelListener(); + private final IAnnotationModelListener fAnnotationModelListener= new AnnotationModelListener(); /** The projection summary. */ private ProjectionSummary fProjectionSummary; /** Indication that an annotation world change has not yet been processed. */ @@ -319,9 +319,9 @@ public void documentAboutToBeChanged(DocumentEvent event) { /** The list of projection listeners. */ private List fProjectionListeners; /** Internal lock for protecting the list of pending requests */ - private Object fLock= new Object(); + private final Object fLock= new Object(); /** The list of pending requests */ - private List fPendingRequests= new ArrayList<>(); + private final List fPendingRequests= new ArrayList<>(); /** The replace-visible-document execution trigger */ private IDocument fReplaceVisibleDocumentExecutionTrigger; /** true if projection was on the last time we switched to segmented mode. */ @@ -340,7 +340,7 @@ public void documentAboutToBeChanged(DocumentEvent event) { */ private int fDeletedLines; - private UpdateDocumentListener fUpdateDocumentListener; + private final UpdateDocumentListener fUpdateDocumentListener; /** * Creates a new projection source viewer. diff --git a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/SourceViewerInformationControl.java b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/SourceViewerInformationControl.java index f3e7c9d5a4e..22900f98863 100644 --- a/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/SourceViewerInformationControl.java +++ b/bundles/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/SourceViewerInformationControl.java @@ -66,7 +66,7 @@ class SourceViewerInformationControl implements IInformationControl, IInformatio /** The text font (do not dispose!) */ private Font fTextFont; /** The control's source viewer */ - private SourceViewer fViewer; + private final SourceViewer fViewer; /** The optional status field. */ private Label fStatusField; /** The separator for the optional status field. */ diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java index c9cfa2774c1..67f8135e783 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java @@ -58,11 +58,11 @@ public abstract class AbstractControlContentAssistSubjectAdapter implements ICon /** * VerifyKeyListeners for the control. */ - private List fVerifyKeyListeners; + private final List fVerifyKeyListeners; /** * KeyListeners for the control. */ - private Set fKeyListeners; + private final Set fKeyListeners; /** * The Listener installed on the control which passes events to * {@link #fVerifyKeyListeners fVerifyKeyListeners} and {@link #fKeyListeners}. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java index 48b44e1b137..58f76ef2720 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java @@ -60,7 +60,7 @@ private class InternalDocument extends Document { /** * Updates this document with changes in {@link #fCombo}. */ - private ModifyListener fModifyListener; + private final ModifyListener fModifyListener; private InternalDocument() { super(fCombo.getText()); @@ -80,8 +80,8 @@ public void replace(int pos, int length, String text) throws BadLocationExceptio /** * The combo widget. */ - private Combo fCombo; - private HashMap fModifyListeners; + private final Combo fCombo; + private final HashMap fModifyListeners; /** * Creates a content assist subject control adapter for the given combo. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/SubjectControlContextInformationValidator.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/SubjectControlContextInformationValidator.java index c8ec349b344..bf0cfabd1c9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/SubjectControlContextInformationValidator.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/SubjectControlContextInformationValidator.java @@ -32,7 +32,7 @@ public final class SubjectControlContextInformationValidator implements ISubjectControlContextInformationValidator { /** The content assist processor. */ - private IContentAssistProcessor fProcessor; + private final IContentAssistProcessor fProcessor; /** The context information to be validated. */ private IContextInformation fContextInformation; /** The content assist subject control. */ diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java index 862f31e98aa..0436cce136b 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java @@ -50,7 +50,7 @@ private class InternalDocument extends Document { /** * Updates this document with changes in this adapter's text widget. */ - private ModifyListener fModifyListener; + private final ModifyListener fModifyListener; private InternalDocument() { super(fText.getText()); @@ -68,9 +68,9 @@ public void replace(int pos, int length, String text) throws BadLocationExceptio } /** The text. */ - private Text fText; + private final Text fText; /** The modify listeners. */ - private HashMap fModifyListeners= new HashMap<>(); + private final HashMap fModifyListeners= new HashMap<>(); /** * Creates a content assist subject control adapter for the given text widget. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/TableOwnerDrawSupport.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/TableOwnerDrawSupport.java index a3052c84d42..7f4e72a346d 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/TableOwnerDrawSupport.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/TableOwnerDrawSupport.java @@ -36,7 +36,7 @@ public class TableOwnerDrawSupport implements Listener { private static final String STYLED_RANGES_KEY= "styled_ranges"; //$NON-NLS-1$ // shared text layout - private TextLayout fSharedLayout; + private final TextLayout fSharedLayout; private int fDeltaOfLastMeasure; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java index 1e79dc782f4..a813f278c49 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java @@ -161,7 +161,7 @@ public static boolean isAvailable(Composite parent) { * The listeners to be notified when the input changed. * @since 3.4 */ - private ListenerList fInputChangeListeners= new ListenerList<>(ListenerList.IDENTITY); + private final ListenerList fInputChangeListeners= new ListenerList<>(ListenerList.IDENTITY); /** * The symbolic name of the font used for size computations, or null to use dialog font. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java index fb5ac10fc5b..b64867974ae 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java @@ -80,7 +80,7 @@ public class HTML2TextReader extends SubstitutionReader { } private int fCounter= 0; - private TextPresentation fTextPresentation; + private final TextPresentation fTextPresentation; private int fBold= 0; private int fItalic= 0; private int fStrikeout= 0; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java index f88a14482b8..c3f772bf1e8 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java @@ -43,7 +43,7 @@ public class HTMLTextPresenter implements DefaultInformationControl.IInformation private static final String LINE_DELIM= System.lineSeparator(); - private boolean fEnforceUpperLineLimit; + private final boolean fEnforceUpperLineLimit; public HTMLTextPresenter(boolean enforceUpperLineLimit) { fEnforceUpperLineLimit= enforceUpperLineLimit; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/SubstitutionTextReader.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/SubstitutionTextReader.java index eca59c9e706..eb48d938993 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/SubstitutionTextReader.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/SubstitutionTextReader.java @@ -30,7 +30,7 @@ public abstract class SubstitutionTextReader extends SingleCharReader { protected static final String LINE_DELIM= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - private Reader fReader; + private final Reader fReader; protected boolean fWasWhiteSpace; private int fCharAfterWhiteSpace; @@ -40,7 +40,7 @@ public abstract class SubstitutionTextReader extends SingleCharReader { private boolean fSkipWhiteSpace= true; private boolean fReadFromBuffer; - private StringBuilder fBuffer; + private final StringBuilder fBuffer; private int fIndex; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/AdditionalInfoController2.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/AdditionalInfoController2.java index a3c5930b2f4..5be6a8867aa 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/AdditionalInfoController2.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/AdditionalInfoController2.java @@ -69,9 +69,9 @@ public void widgetDefaultSelected(SelectionEvent e) { /** Object to synchronize initial display of additional info */ private Object fStartSignal; /** The table selection listener */ - private SelectionListener fSelectionListener= new TableSelectionListener(); + private final SelectionListener fSelectionListener= new TableSelectionListener(); /** The delay after which additional information is displayed */ - private int fDelay; + private final int fDelay; /** diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java index df36199fa15..d4450c2eacc 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java @@ -76,13 +76,13 @@ class CompletionProposalPopup2 implements IContentAssistListener2 { /** The associated text viewer */ - private ITextViewer fViewer; + private final ITextViewer fViewer; /** The associated content assistant */ - private ContentAssistant2 fContentAssistant; + private final ContentAssistant2 fContentAssistant; /** The used additional info controller */ - private AdditionalInfoController2 fAdditionalInfoController; + private final AdditionalInfoController2 fAdditionalInfoController; /** The closing strategy for this completion proposal popup */ - private PopupCloser2 fPopupCloser= new PopupCloser2(); + private final PopupCloser2 fPopupCloser= new PopupCloser2(); /** The popup shell */ private Shell fProposalShell; /** The proposal table */ @@ -92,7 +92,7 @@ class CompletionProposalPopup2 implements IContentAssistListener2 { /** The key listener to control navigation */ private KeyListener fKeyListener; /** List of document events used for filtering proposals */ - private List fDocumentEvents= new ArrayList<>(); + private final List fDocumentEvents= new ArrayList<>(); /** Listener filling the document event queue */ private IDocumentListener fDocumentListener; /** Reentrance count for filterProposals */ diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java index 81a8dfbcb46..4a4fb0baae7 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java @@ -217,7 +217,7 @@ class AutoAssistListener implements VerifyKeyListener, Runnable { private Thread fThread; private boolean fIsReset= false; - private Object fMutex= new Object(); + private final Object fMutex= new Object(); private int fShowStyle; private final static int SHOW_PROPOSALS= 1; @@ -710,7 +710,7 @@ public void processEvent(VerifyEvent event) { private ContextInformationPopup2 fContextInfoPopup; private boolean fKeyListenerHooked= false; - private IContentAssistListener2[] fListeners= new IContentAssistListener2[4]; + private final IContentAssistListener2[] fListeners= new IContentAssistListener2[4]; private int fCompletionPosition; private String[] fProposalStrings; private ICompletionProposal[] fProposals; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java index d914a398cbd..7536cae5dca 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java @@ -76,10 +76,10 @@ static class ContextFrame { public IContextInformationPresenter fPresenter; } - private ITextViewer fViewer; - private ContentAssistant2 fContentAssistant; + private final ITextViewer fViewer; + private final ContentAssistant2 fContentAssistant; - private PopupCloser2 fPopupCloser= new PopupCloser2(); + private final PopupCloser2 fPopupCloser= new PopupCloser2(); private Shell fContextSelectorShell; private Table fContextSelectorTable; private IContextInformation[] fContextSelectorInput; @@ -89,7 +89,7 @@ static class ContextFrame { private StyledText fContextInfoText; private TextPresentation fTextPresentation; - private Stack fContextFrameStack= new Stack<>(); + private final Stack fContextFrameStack= new Stack<>(); /** @@ -639,7 +639,7 @@ private void validateContextInformation() { */ fContextInfoPopup.getDisplay().asyncExec(new Runnable() { - private ContextFrame fFrame= fContextFrameStack.peek(); + private final ContextFrame fFrame= fContextFrameStack.peek(); @Override public void run() { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java index a001961a37c..a2f63a9e74a 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java @@ -367,7 +367,7 @@ public void modelChanged(IAnnotationModel model) { * The information control creator. */ private static final class HoverInformationControlCreator extends AbstractReusableInformationControlCreator { - private boolean fIsFocusable; + private final boolean fIsFocusable; public HoverInformationControlCreator(boolean isFocusable) { fIsFocusable= isFocusable; @@ -562,7 +562,7 @@ public IInformationControlCreator getInformationPresenterControlCreator() { /** The cached list of ranges adapted to quick diff. */ private List fRevisionRanges= null; /** The annotations created for the overview ruler temporary display. */ - private List fAnnotations= new ArrayList<>(); + private final List fAnnotations= new ArrayList<>(); /* State */ diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractHoverInformationControlManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractHoverInformationControlManager.java index b748887c7b8..7d40462abd6 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractHoverInformationControlManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractHoverInformationControlManager.java @@ -110,8 +110,9 @@ public void setInformationControl(IInformationControl control) { @Override public void start(Rectangle subjectArea) { - if (fIsActive) + if (fIsActive) { return; + } fIsActive= true; fWaitForMouseUp= false; @@ -124,11 +125,13 @@ public void start(Rectangle subjectArea) { fSubjectControl.addKeyListener(this); if (fSubjectControl instanceof Scrollable scrollable) { ScrollBar vBar= scrollable.getVerticalBar(); - if (vBar != null) + if (vBar != null) { vBar.addSelectionListener(this); + } ScrollBar hBar= scrollable.getHorizontalBar(); - if (hBar != null) + if (hBar != null) { hBar.addSelectionListener(this); + } } fDisplay= fSubjectControl.getDisplay(); @@ -150,13 +153,15 @@ public void start(Rectangle subjectArea) { @Override public void stop() { - if (!fIsActive) + if (!fIsActive) { return; + } fIsActive= false; - if (DEBUG) + if (DEBUG) { System.out.println("AbstractHoverInformationControlManager.Closer stopped"); //$NON-NLS-1$ + } if (fSubjectControl != null && !fSubjectControl.isDisposed()) { fSubjectControl.removeMouseListener(this); @@ -165,11 +170,13 @@ public void stop() { fSubjectControl.removeKeyListener(this); if (fSubjectControl instanceof Scrollable scrollable) { ScrollBar vBar= scrollable.getVerticalBar(); - if (vBar != null) + if (vBar != null) { vBar.removeSelectionListener(this); + } ScrollBar hBar= scrollable.getHorizontalBar(); - if (hBar != null) + if (hBar != null) { hBar.removeSelectionListener(this); + } } } @@ -250,16 +257,17 @@ public void handleEvent(Event event) { switch (event.type) { case SWT.Activate: case SWT.MouseVerticalWheel: - if (!hasInformationControlReplacer()) + if (!hasInformationControlReplacer()) { hideInformationControl(); - else if (!isReplaceInProgress()) { + } else if (!isReplaceInProgress()) { IInformationControl infoControl= getCurrentInformationControl(); // During isReplaceInProgress(), events can come from the replacing information control if (event.widget instanceof Control control && infoControl instanceof IInformationControlExtension5 iControl5) { - if (!(iControl5.containsControl(control))) + if (!(iControl5.containsControl(control))) { hideInformationControl(); - else if (event.type == SWT.MouseVerticalWheel && cancelReplacingDelay()) + } else if (event.type == SWT.MouseVerticalWheel && cancelReplacingDelay()) { replaceInformationControl(false); + } } else if (infoControl != null && infoControl.isFocusControl() && cancelReplacingDelay()) { replaceInformationControl(true); } @@ -268,9 +276,9 @@ else if (event.type == SWT.MouseVerticalWheel && cancelReplacingDelay()) case SWT.MouseUp: case SWT.MouseDown: - if (!hasInformationControlReplacer()) + if (!hasInformationControlReplacer()) { hideInformationControl(); - else if (!isReplaceInProgress()) { + } else if (!isReplaceInProgress()) { IInformationControl infoControl= getCurrentInformationControl(); if (event.widget instanceof Control control && infoControl instanceof final IInformationControlExtension5 iControl5) { if (!(iControl5.containsControl(control))) { @@ -299,8 +307,9 @@ else if (!isReplaceInProgress()) { case SWT.FocusOut: IInformationControl iControl= getCurrentInformationControl(); - if (iControl != null && ! iControl.isFocusControl()) + if (iControl != null && ! iControl.isFocusControl()) { hideInformationControl(); + } break; case SWT.MouseMove: @@ -321,19 +330,22 @@ private void handleMouseMove(Event event) { // if (DEBUG) // System.out.println("AbstractHoverInformationControl.Closer.handleMouseMove():" + event); //$NON-NLS-1$ - if (!(event.widget instanceof Control eventControl)) + if (!(event.widget instanceof Control eventControl)) { return; + } //transform coordinates to subject control: Point mouseLoc= event.display.map(eventControl, fSubjectControl, event.x, event.y); - if (fSubjectArea.contains(mouseLoc)) + if (fSubjectArea.contains(mouseLoc)) { return; + } IInformationControl iControl= getCurrentInformationControl(); if (!hasInformationControlReplacer() || !canMoveIntoInformationControl(iControl)) { if (AbstractHoverInformationControlManager.this instanceof AnnotationBarHoverManager) { - if (getInternalAccessor().getAllowMouseExit()) + if (getInternalAccessor().getAllowMouseExit()) { return; + } } hideInformationControl(); return; @@ -344,8 +356,9 @@ private void handleMouseMove(Event event) { if (controlBounds != null) { Rectangle tooltipBounds= event.display.map(null, eventControl, controlBounds); if (tooltipBounds.contains(event.x, event.y)) { - if (!isReplaceInProgress() && event.type != SWT.MouseExit) + if (!isReplaceInProgress() && event.type != SWT.MouseExit) { startReplaceInformationControl(event.display); + } return; } cancelReplacingDelay(); @@ -439,8 +452,9 @@ public void start(Control subjectControl, Control areaControl) { fSubjectControl= subjectControl; fAreaControl= areaControl; - if (fSubjectControl != null && !fSubjectControl.isDisposed()) + if (fSubjectControl != null && !fSubjectControl.isDisposed()) { fSubjectControl.addMouseTrackListener(this); + } fIsInRestartMode= false; fIsComputing= false; @@ -474,8 +488,9 @@ public void stop() { public void mouseHover(MouseEvent event) { if (fIsComputing || fIsInRestartMode || (fSubjectControl != null && !fSubjectControl.isDisposed() && fSubjectControl.getShell() != fSubjectControl.getShell().getDisplay().getActiveShell())) { - if (DEBUG) + if (DEBUG) { System.out.println("AbstractHoverInformationControlManager...mouseHover: @ " + event.x + "/" + event.y + " : hover cancelled: fIsComputing= " + fIsComputing + ", fIsInRestartMode= " + fIsInRestartMode); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } return; } @@ -487,10 +502,12 @@ public void mouseHover(MouseEvent event) { fHoverEventStateMask= event.stateMask; fHoverEvent= event; fHoverArea= new Rectangle(event.x - EPSILON, event.y - EPSILON, 2 * EPSILON, 2 * EPSILON ); - if (fHoverArea.x < 0) + if (fHoverArea.x < 0) { fHoverArea.x= 0; - if (fHoverArea.y < 0) + } + if (fHoverArea.y < 0) { fHoverArea.y= 0; + } setSubjectArea(fHoverArea); if (fSubjectControl != null && !fSubjectControl.isDisposed()) { @@ -508,8 +525,9 @@ public void mouseHover(MouseEvent event) { * computing the information to be presented. */ protected void deactivate() { - if (fIsComputing) + if (fIsComputing) { return; + } fIsInRestartMode= false; if (fSubjectControl != null && !fSubjectControl.isDisposed()) { @@ -535,11 +553,13 @@ public void mouseExit(MouseEvent e) { @Override public void mouseMove(MouseEvent event) { if (!hasInformationControlReplacer() || !canMoveIntoInformationControl(getCurrentInformationControl())) { - if (!fSubjectArea.contains(event.x, event.y)) + if (!fSubjectArea.contains(event.x, event.y)) { deactivate(); + } } else { - if (!inKeepUpZone(event.x, event.y, fSubjectControl, fSubjectArea, false)) + if (!inKeepUpZone(event.x, event.y, fSubjectControl, fSubjectArea, false)) { deactivate(); + } } } @@ -574,15 +594,17 @@ public void computationCompleted() { */ public boolean isMouseLost() { - if (fMouseLostWhileComputing || fShellDeactivatedWhileComputing) + if (fMouseLostWhileComputing || fShellDeactivatedWhileComputing) { return true; + } if (fSubjectControl != null && !fSubjectControl.isDisposed()) { Display display= fSubjectControl.getDisplay(); Point p= display.getCursorLocation(); p= fSubjectControl.toControl(p); - if (!fSubjectArea.contains(p) && !fHoverArea.contains(p)) + if (!fSubjectArea.contains(p) && !fHoverArea.contains(p)) { return true; + } } return false; @@ -658,8 +680,9 @@ protected AbstractHoverInformationControlManager(IInformationControlCreator crea * @since 3.4 */ private boolean inKeepUpZone(int x, int y, Control subjectControl, Rectangle subjectArea, boolean blowUp) { - if (subjectArea.contains(x, y)) + if (subjectArea.contains(x, y)) { return true; + } IInformationControl iControl= getCurrentInformationControl(); if ((iControl instanceof IInformationControlExtension5 && !((IInformationControlExtension5) iControl).isVisible())) { @@ -682,8 +705,9 @@ private boolean inKeepUpZone(int x, int y, Control subjectControl, Rectangle sub } if (!blowUp) { - if (iControlBounds.contains(x, y)) + if (iControlBounds.contains(x, y)) { return true; + } if (subjectArea.y + subjectArea.height < iControlBounds.y) { // special case for hover events: subjectArea totally above iControl: @@ -740,8 +764,9 @@ private boolean inKeepUpZone(int x, int y, Control subjectControl, Rectangle sub // FIXME: should maybe use convex hull, not bounding box totalBounds.add(subjectArea); - if (totalBounds.contains(x, y)) + if (totalBounds.contains(x, y)) { return true; + } } return false; } @@ -811,16 +836,18 @@ boolean cancelReplacingDelay() { * {@link #replaceInformationControl(boolean)} in the UI thread */ private void startReplaceInformationControl(final Display display) { - if (fEnrichMode == EnrichMode.ON_CLICK) + if (fEnrichMode == EnrichMode.ON_CLICK) { return; + } if (fReplacingDelayJob != null) { if (fReplacingDelayJob.getState() != Job.RUNNING) { if (fReplacingDelayJob.cancel()) { if (fEnrichMode == EnrichMode.IMMEDIATELY) { fReplacingDelayJob= null; - if (! fWaitForMouseUp) + if (! fWaitForMouseUp) { replaceInformationControl(false); + } } else { // if (DEBUG) // System.out.println("AbstractHoverInformationControlManager.startReplaceInformationControl(): rescheduled"); //$NON-NLS-1$ @@ -839,10 +866,12 @@ public IStatus run(final IProgressMonitor monitor) { } display.syncExec(() -> { fReplacingDelayJob= null; - if (monitor.isCanceled()) + if (monitor.isCanceled()) { return; - if (!fWaitForMouseUp) + } + if (!fWaitForMouseUp) { replaceInformationControl(false); + } }); return Status.OK_STATUS; } @@ -862,8 +891,9 @@ protected void presentInformation() { } Rectangle area= getSubjectArea(); - if (area != null) + if (area != null) { fMouseTracker.setSubjectArea(area); + } if (fMouseTracker.isMouseLost()) { fMouseTracker.computationCompleted(); @@ -887,10 +917,11 @@ public void setEnabled(boolean enabled) { boolean is= isEnabled(); if (was != is && fMouseTracker != null) { - if (is) + if (is) { fMouseTracker.start(getSubjectControl(), fAreaControl); - else + } else { fMouseTracker.stop(); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControl.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControl.java index e956107216c..031c6ee18ac 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControl.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControl.java @@ -186,8 +186,9 @@ public AbstractInformationControl(Shell parentShell, boolean isResizable) { fResizeHandleSize= -1; fToolBarManager= toolBarManager; - if ((shellStyle & SWT.NO_TRIM) != 0) + if ((shellStyle & SWT.NO_TRIM) != 0) { shellStyle&= ~(SWT.NO_TRIM | SWT.SHELL_TRIM); // make sure we get the OS border but no other trims + } fResizable= (shellStyle & SWT.RESIZE) != 0; fShell= new Shell(parentShell, shellStyle); @@ -215,8 +216,9 @@ public AbstractInformationControl(Shell parentShell, boolean isResizable) { } private void createStatusComposite(final String statusFieldText, final ToolBarManager toolBarManager, Color foreground, Color background) { - if (toolBarManager == null && statusFieldText == null) + if (toolBarManager == null && statusFieldText == null) { return; + } fStatusComposite= new Composite(fShell, SWT.NONE); GridData gridData= new GridData(SWT.FILL, SWT.BOTTOM, true, false); @@ -284,8 +286,9 @@ private void addResizeSupportIfNecessary(final Composite bars) { // - https://bugs.eclipse.org/bugs/show_bug.cgi?id=23980 : platform specific shell resize behavior String platform= SWT.getPlatform(); final boolean isWin= platform.equals("win32"); //$NON-NLS-1$ - if (!isWin && !Util.isGtk()) + if (!isWin && !Util.isGtk()) { return; + } final Canvas resizer= new Canvas(bars, SWT.NONE); @@ -304,14 +307,18 @@ private void addResizeSupportIfNecessary(final Composite bars) { // draw dots e.gc.setBackground(resizer.getDisplay().getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); int end= min - 1; - for (int i1= 0; i1 <= 2; i1++) - for (int j1= 0; j1 <= 2 - i1; j1++) + for (int i1= 0; i1 <= 2; i1++) { + for (int j1= 0; j1 <= 2 - i1; j1++) { e.gc.fillRectangle(end - 4 * i1, end - 4 * j1, 2, 2); + } + } end--; e.gc.setBackground(resizer.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); - for (int i2= 0; i2 <= 2; i2++) - for (int j2= 0; j2 <= 2 - i2; j2++) + for (int i2= 0; i2 <= 2; i2++) { + for (int j2= 0; j2 <= 2 - i2; j2++) { e.gc.fillRectangle(end - 4 * i2, end - 4 * j2, 2, 2); + } + } } else { // draw diagonal lines @@ -505,16 +512,18 @@ public boolean isResizable() { @Override public void setVisible(boolean visible) { - if (visible && fShell.isVisible() == visible) + if (visible && fShell.isVisible() == visible) { return; + } fShell.setVisible(visible); } @Override public void dispose() { - if (fShell != null && !fShell.isDisposed()) + if (fShell != null && !fShell.isDisposed()) { fShell.dispose(); + } } /** @@ -559,8 +568,9 @@ protected final Point getSizeConstraints() { public Point computeSizeHint() { // XXX: Verify whether this is a good default implementation. If yes, document it. Point constrains= getSizeConstraints(); - if (constrains == null) + if (constrains == null) { return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + } return fShell.computeSize(constrains.x, constrains.y, true); } @@ -576,8 +586,9 @@ public Point computeSizeHint() { public Rectangle computeTrim() { Rectangle trim= fShell.computeTrim(0, 0, 0, 0); - if (fStatusComposite != null) + if (fStatusComposite != null) { trim.height+= fStatusComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; + } return trim; } @@ -641,7 +652,9 @@ public void setBackgroundColor(Color background) { } private void setStatusLabelColors(Color foreground, Color background) { - if (foreground == null || background == null) return; + if (foreground == null || background == null) { + return; + } Color statusLabelForeground= new Color(fStatusLabel.getDisplay(), Colors.blend(background.getRGB(), foreground.getRGB(), 0.56f)); fStatusLabel.setForeground(statusLabelForeground); fStatusLabel.setBackground(background); @@ -665,8 +678,9 @@ public boolean isFocusControl() { @Override public void setFocus() { boolean focusTaken= fShell.setFocus(); - if (!focusTaken) + if (!focusTaken) { fShell.forceFocus(); + } } /** @@ -734,10 +748,12 @@ public void setStatusText(String statusFieldText) { @Override public boolean containsControl(Control control) { do { - if (control == fShell) + if (control == fShell) { return true; - if (control instanceof Shell) + } + if (control instanceof Shell) { return false; + } control= control.getParent(); } while (control != null); return false; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControlManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControlManager.java index 43f5179c973..7cfd93de4f5 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControlManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractInformationControlManager.java @@ -450,8 +450,9 @@ protected void setCloser(IInformationControlCloser closer) { * @since 3.4 */ void setInformationControlReplacer(InformationControlReplacer replacer) { - if (fInformationControlReplacer != null) + if (fInformationControlReplacer != null) { fInformationControlReplacer.dispose(); + } fInformationControlReplacer= replacer; } @@ -599,8 +600,9 @@ public void setFallbackAnchors(Anchor[] fallbackAnchors) { if (fallbackAnchors != null) { fFallbackAnchors= new Anchor[fallbackAnchors.length]; System.arraycopy(fallbackAnchors, 0, fFallbackAnchors, 0, fallbackAnchors.length); - } else + } else { fFallbackAnchors= null; + } } /** @@ -611,8 +613,9 @@ public void setFallbackAnchors(Anchor[] fallbackAnchors) { */ protected void setCustomInformationControlCreator(IInformationControlCreator informationControlCreator) { if (informationControlCreator != null && fCustomInformationControlCreator instanceof IInformationControlCreatorExtension extension) { - if (extension.canReplace(informationControlCreator)) + if (extension.canReplace(informationControlCreator)) { return; + } } fCustomInformationControlCreator= informationControlCreator; } @@ -654,16 +657,19 @@ protected void handleSubjectControlDisposed() { * @param subjectControl the subject control */ public void install(Control subjectControl) { - if (fSubjectControl != null && !fSubjectControl.isDisposed() && fSubjectControlDisposeListener != null) + if (fSubjectControl != null && !fSubjectControl.isDisposed() && fSubjectControlDisposeListener != null) { fSubjectControl.removeDisposeListener(fSubjectControlDisposeListener); + } fSubjectControl= subjectControl; - if (fSubjectControl != null) + if (fSubjectControl != null) { fSubjectControl.addDisposeListener(getSubjectControlDisposeListener()); + } - if (fInformationControlCloser != null) + if (fInformationControlCloser != null) { fInformationControlCloser.setSubjectControl(subjectControl); + } setEnabled(true); fDisposed= false; @@ -735,11 +741,13 @@ protected Point computeSizeConstraints(Control subjectControl, IInformationContr if (fSizeConstraints == null) { if (informationControl instanceof IInformationControlExtension5 iControl5) { fSizeConstraints= iControl5.computeSizeConstraints(fWidthConstraint, fHeightConstraint); - if (fSizeConstraints != null) + if (fSizeConstraints != null) { return Geometry.copy(fSizeConstraints); + } } - if (subjectControl == null) + if (subjectControl == null) { return null; + } GC gc= new GC(subjectControl); gc.setFont(subjectControl.getFont()); @@ -774,8 +782,9 @@ protected void handleInformationControlDisposed() { storeInformationControlBounds(); - if (fInformationControl instanceof IInformationControlExtension5) + if (fInformationControl instanceof IInformationControlExtension5) { fSizeConstraints= null; + } fInformationControl= null; if (fInformationControlCloser != null) { fInformationControlCloser.setInformationControl(null); //XXX: null is against the spec @@ -791,16 +800,18 @@ protected void handleInformationControlDisposed() { */ protected IInformationControl getInformationControl() { - if (fDisposed) + if (fDisposed) { return fInformationControl; + } IInformationControlCreator creator= null; if (fCustomInformationControlCreator == null) { creator= fInformationControlCreator; if (fIsCustomInformationControl && fInformationControl != null) { - if (fInformationControl instanceof IInformationControlExtension5) + if (fInformationControl instanceof IInformationControlExtension5) { fSizeConstraints= null; + } fInformationControl.dispose(); fInformationControl= null; } @@ -810,12 +821,14 @@ protected IInformationControl getInformationControl() { creator= fCustomInformationControlCreator; if (creator instanceof IInformationControlCreatorExtension extension) { - if (fInformationControl != null && extension.canReuse(fInformationControl)) + if (fInformationControl != null && extension.canReuse(fInformationControl)) { return fInformationControl; + } } if (fInformationControl != null) { - if (fInformationControl instanceof IInformationControlExtension5) + if (fInformationControl instanceof IInformationControlExtension5) { fSizeConstraints= null; + } fInformationControl.dispose(); fInformationControl= null; } @@ -826,8 +839,9 @@ protected IInformationControl getInformationControl() { fInformationControl= creator.createInformationControl(fSubjectControl.getShell()); fInformationControl.addDisposeListener(e -> handleInformationControlDisposed()); - if (fInformationControlCloser != null) + if (fInformationControlCloser != null) { fInformationControlCloser.setInformationControl(fInformationControl); + } } return fInformationControl; @@ -870,8 +884,9 @@ protected Point computeLocation(Rectangle subjectArea, Point controlSize, Anchor } boolean isRTL= fSubjectControl != null && (fSubjectControl.getStyle() & SWT.RIGHT_TO_LEFT) != 0; - if (isRTL) + if (isRTL) { xShift += controlSize.x; + } return fSubjectControl.toDisplay(new Point(subjectArea.x + xShift, subjectArea.y + yShift)); } @@ -942,40 +957,48 @@ protected boolean updateLocation(Point location, Point size, Rectangle displayAr if (ANCHOR_BOTTOM == anchor || ANCHOR_TOP == anchor) { if (ANCHOR_BOTTOM == anchor) { - if (lowerRightY > displayLowerRightY) + if (lowerRightY > displayLowerRightY) { return false; + } } else { - if (location.y < displayArea.y) + if (location.y < displayArea.y) { return false; + } } - if (lowerRightX > displayLowerRightX) + if (lowerRightX > displayLowerRightX) { location.x= location.x - (lowerRightX - displayLowerRightX); + } return (location.x >= displayArea.x && location.y >= displayArea.y); } else if (ANCHOR_RIGHT == anchor || ANCHOR_LEFT == anchor) { if (ANCHOR_RIGHT == anchor) { - if (lowerRightX > displayLowerRightX) + if (lowerRightX > displayLowerRightX) { return false; + } } else { - if (location.x < displayArea.x) + if (location.x < displayArea.x) { return false; + } } - if (lowerRightY > displayLowerRightY) + if (lowerRightY > displayLowerRightY) { location.y= location.y - (lowerRightY - displayLowerRightY); + } return (location.x >= displayArea.x && location.y >= displayArea.y); } else if (ANCHOR_GLOBAL == anchor) { - if (lowerRightX > displayLowerRightX) + if (lowerRightX > displayLowerRightX) { location.x= location.x - (lowerRightX - displayLowerRightX); + } - if (lowerRightY > displayLowerRightY) + if (lowerRightY > displayLowerRightY) { location.y= location.y - (lowerRightY - displayLowerRightY); + } return (location.x >= displayArea.x && location.y >= displayArea.y); } @@ -1002,12 +1025,14 @@ protected boolean updateLocation(Point location, Point size, Rectangle displayAr */ protected Anchor getNextFallbackAnchor(Anchor anchor) { - if (anchor == null || fFallbackAnchors == null) + if (anchor == null || fFallbackAnchors == null) { return null; + } for (int i= 0; i < fFallbackAnchors.length; i++) { - if (fFallbackAnchors[i] == anchor) + if (fFallbackAnchors[i] == anchor) { return fFallbackAnchors[i + 1 == fFallbackAnchors.length ? 0 : i + 1]; + } } return null; @@ -1036,8 +1061,9 @@ protected Point computeInformationControlLocation(Rectangle subjectArea, Point c upperLeft= computeLocation(subjectArea, controlSize, testAnchor); Monitor monitor= getClosestMonitor(subjectAreaDisplayRelative, testAnchor); - if (updateLocation(upperLeft, controlSize, monitor.getClientArea(), testAnchor)) + if (updateLocation(upperLeft, controlSize, monitor.getClientArea(), testAnchor)) { return upperLeft; + } // compute available area for this anchor and update if better than best Rectangle available= computeAvailableArea(subjectAreaDisplayRelative, monitor.getClientArea(), testAnchor); @@ -1055,8 +1081,9 @@ protected Point computeInformationControlLocation(Rectangle subjectArea, Point c } while (testAnchor != fAnchor && testAnchor != null); // no anchor is perfect - select the one with larges area and set the size to not overlap with the subjectArea - if (bestAnchor != ANCHOR_GLOBAL) + if (bestAnchor != ANCHOR_GLOBAL) { Geometry.set(controlSize, Geometry.getSize(bestBounds)); + } return Geometry.getLocation(bestBounds); } @@ -1071,10 +1098,11 @@ protected Point computeInformationControlLocation(Rectangle subjectArea, Point c */ private Monitor getClosestMonitor(Rectangle area, Anchor anchor) { Point center; - if (ANCHOR_GLOBAL == anchor) + if (ANCHOR_GLOBAL == anchor) { center= Geometry.centerPoint(area); - else + } else { center= Geometry.centerPoint(Geometry.getExtrudedEdge(area, 0, anchor.getSWTFlag())); + } return Util.getClosestMonitor(fSubjectControl.getDisplay(), center); } @@ -1084,8 +1112,9 @@ private Monitor getClosestMonitor(Rectangle area, Anchor anchor) { * This happens only if this controller is enabled. */ public void showInformation() { - if (fEnabled) + if (fEnabled) { doShowInformation(); + } } /** @@ -1108,15 +1137,17 @@ protected void doShowInformation() { */ protected void presentInformation() { boolean hasContents= false; - if (fInformation instanceof String) + if (fInformation instanceof String) { hasContents= !((String)fInformation).trim().isEmpty(); - else + } else { hasContents= (fInformation != null); + } - if (fSubjectArea != null && hasContents) + if (fSubjectArea != null && hasContents) { internalShowInformationControl(fSubjectArea, fInformation); - else + } else { hideInformationControl(); + } } /** @@ -1143,14 +1174,16 @@ private void internalShowInformationControl(Rectangle subjectArea, Object inform } informationControl.setSizeConstraints(sizeConstraints.x, sizeConstraints.y); - if (informationControl instanceof IInformationControlExtension2) + if (informationControl instanceof IInformationControlExtension2) { ((IInformationControlExtension2)informationControl).setInput(information); - else + } else { informationControl.setInformation(information.toString()); + } if (informationControl instanceof IInformationControlExtension extension) { - if (!extension.hasContents()) + if (!extension.hasContents()) { return; + } } Point size= null; @@ -1158,23 +1191,29 @@ private void internalShowInformationControl(Rectangle subjectArea, Object inform Rectangle bounds= restoreInformationControlBounds(); if (bounds != null) { - if (bounds.x > -1 && bounds.y > -1) + if (bounds.x > -1 && bounds.y > -1) { location= Geometry.getLocation(bounds); + } - if (bounds.width > -1 && bounds.height > -1) + if (bounds.width > -1 && bounds.height > -1) { size= Geometry.getSize(bounds); + } } - if (size == null) + if (size == null) { size= informationControl.computeSizeHint(); + } - if (fEnforceAsMinimalSize) + if (fEnforceAsMinimalSize) { size= Geometry.max(size, sizeConstraints); - if (fEnforceAsMaximalSize) + } + if (fEnforceAsMaximalSize) { size= Geometry.min(size, sizeConstraints); + } - if (location == null) + if (location == null) { location= computeInformationControlLocation(subjectArea, size); + } Rectangle controlBounds= Geometry.createRectangle(location, size); cropToClosestMonitor(controlBounds); @@ -1205,8 +1244,9 @@ protected void hideInformationControl() { if (fInformationControl != null) { storeInformationControlBounds(); fInformationControl.setVisible(false); - if (fInformationControlCloser != null) + if (fInformationControlCloser != null) { fInformationControlCloser.stop(); + } } if (canClearDataOnHide()) { fSubjectArea= null; @@ -1234,14 +1274,17 @@ protected boolean canClearDataOnHide() { protected void showInformationControl(Rectangle subjectArea) { fInformationControl.setVisible(true); - if (fInformationControl == null) + if (fInformationControl == null) { return; // could already be disposed if setVisible(..) runs the display loop + } - if (fTakesFocusWhenVisible) + if (fTakesFocusWhenVisible) { fInformationControl.setFocus(); + } - if (fInformationControlCloser != null) + if (fInformationControlCloser != null) { fInformationControlCloser.start(subjectArea); + } } /** @@ -1292,8 +1335,9 @@ public void dispose() { fInformationControlReplacer= null; } - if (fSubjectControl != null && !fSubjectControl.isDisposed() && fSubjectControlDisposeListener != null) + if (fSubjectControl != null && !fSubjectControl.isDisposed() && fSubjectControlDisposeListener != null) { fSubjectControl.removeDisposeListener(fSubjectControlDisposeListener); + } fSubjectControl= null; fSubjectControlDisposeListener= null; @@ -1312,18 +1356,21 @@ public void dispose() { * @since 3.0 */ protected void storeInformationControlBounds() { - if (fDialogSettings == null || fInformationControl == null || !(fIsRestoringLocation || fIsRestoringSize)) + if (fDialogSettings == null || fInformationControl == null || !(fIsRestoringLocation || fIsRestoringSize)) { return; + } - if (!(fInformationControl instanceof IInformationControlExtension3)) + if (!(fInformationControl instanceof IInformationControlExtension3)) { throw new UnsupportedOperationException(); + } boolean controlRestoresSize= ((IInformationControlExtension3)fInformationControl).restoresSize(); boolean controlRestoresLocation= ((IInformationControlExtension3)fInformationControl).restoresLocation(); Rectangle bounds= ((IInformationControlExtension3)fInformationControl).getBounds(); - if (bounds == null) + if (bounds == null) { return; + } if (fIsRestoringSize && controlRestoresSize) { fDialogSettings.put(STORE_SIZE_WIDTH, bounds.width); @@ -1341,11 +1388,13 @@ protected void storeInformationControlBounds() { * @since 3.0 */ protected Rectangle restoreInformationControlBounds() { - if (fDialogSettings == null || !(fIsRestoringLocation || fIsRestoringSize)) + if (fDialogSettings == null || !(fIsRestoringLocation || fIsRestoringSize)) { return null; + } - if (!(fInformationControl instanceof IInformationControlExtension3)) + if (!(fInformationControl instanceof IInformationControlExtension3)) { throw new UnsupportedOperationException(); + } boolean controlRestoresSize= ((IInformationControlExtension3)fInformationControl).restoresSize(); boolean controlRestoresLocation= ((IInformationControlExtension3)fInformationControl).restoresLocation(); @@ -1373,19 +1422,22 @@ protected Rectangle restoreInformationControlBounds() { } // sanity check - if (bounds.x == -1 && bounds.y == -1 && bounds.width == -1 && bounds.height == -1) + if (bounds.x == -1 && bounds.y == -1 && bounds.width == -1 && bounds.height == -1) { return null; + } Rectangle maxBounds= null; - if (fSubjectControl != null && !fSubjectControl.isDisposed()) + if (fSubjectControl != null && !fSubjectControl.isDisposed()) { maxBounds= fSubjectControl.getDisplay().getBounds(); - else { + } else { // fallback Display display= Display.getCurrent(); - if (display == null) + if (display == null) { display= Display.getDefault(); - if (display != null && !display.isDisposed()) + } + if (display != null && !display.isDisposed()) { maxBounds= display.getBounds(); + } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java index cd679fde0c7..4f29ca83bf9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java @@ -29,7 +29,7 @@ */ public abstract class AbstractReusableInformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension, DisposeListener { - private Map fInformationControls= new HashMap<>(); + private final Map fInformationControls= new HashMap<>(); /** * Creates the control. @@ -53,10 +53,12 @@ public IInformationControl createInformationControl(Shell parent) { @Override public void widgetDisposed(DisposeEvent e) { Composite parent= null; - if (e.widget instanceof Shell) + if (e.widget instanceof Shell) { parent= ((Shell)e.widget).getParent(); - if (parent instanceof Shell) + } + if (parent instanceof Shell) { fInformationControls.remove(parent); + } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/Activator.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/Activator.java index b72814a9119..1e207f72696 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/Activator.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/Activator.java @@ -43,8 +43,9 @@ public static ExecutorService getExecutor() { } private void createExecutor() { - if (activator.executor != null) + if (activator.executor != null) { return; + } executor= new ThreadPoolExecutor( Runtime.getRuntime().availableProcessors(), diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/BlockTextSelection.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/BlockTextSelection.java index d75a296aaed..d04437926ae 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/BlockTextSelection.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/BlockTextSelection.java @@ -79,8 +79,9 @@ private static int computeOffset(IDocument document, int line, int column) { int offsetInLine= Math.min(column, lineInfo.getLength()); return lineInfo.getOffset() + offsetInLine; } catch (BadLocationException x) { - if (line < 0) + if (line < 0) { return 0; + } return document.getLength(); } } @@ -131,19 +132,25 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!super.equals(obj)) + } + if (!super.equals(obj)) { return false; + } final BlockTextSelection other= (BlockTextSelection) obj; - if (fEndColumn != other.fEndColumn) + if (fEndColumn != other.fEndColumn) { return false; - if (fEndLine != other.fEndLine) + } + if (fEndLine != other.fEndLine) { return false; - if (fStartColumn != other.fStartColumn) + } + if (fStartColumn != other.fStartColumn) { return false; - if (fStartLine != other.fStartLine) + } + if (fStartLine != other.fStartLine) { return false; + } return true; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/CursorLinePainter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/CursorLinePainter.java index 4b871900019..f963bb8b815 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/CursorLinePainter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/CursorLinePainter.java @@ -45,9 +45,9 @@ public class CursorLinePainter implements IPainter, LineBackgroundListener { private IPaintPositionManager fPositionManager; /** Keeps track of the line to be painted */ - private Position fCurrentLine= new Position(0, 0); + private final Position fCurrentLine= new Position(0, 0); /** Keeps track of the line to be cleared */ - private Position fLastLine= new Position(0, 0); + private final Position fLastLine= new Position(0, 0); /** Keeps track of the line number of the last painted line */ private int fLastLineNumber= -1; /** Indicates whether this painter is active */ @@ -81,8 +81,9 @@ public void lineGetBackground(LineBackgroundEvent event) { int caret= textWidget.getCaretOffset(); int length= event.lineText.length(); - if (event.lineOffset <= caret && caret <= event.lineOffset + length && !hasMultiLineSelection(textWidget)) + if (event.lineOffset <= caret && caret <= event.lineOffset + length && !hasMultiLineSelection(textWidget)) { event.lineBackground= fHighlightColor; + } } } @@ -113,10 +114,11 @@ private boolean updateHighlightLine() { } fCurrentLine.offset= document.getLineOffset(lineNumber); - if (lineNumber == document.getNumberOfLines() - 1) + if (lineNumber == document.getNumberOfLines() - 1) { fCurrentLine.length= document.getLength() - fCurrentLine.offset; - else + } else { fCurrentLine.length= document.getLineOffset(lineNumber + 1) - fCurrentLine.offset; + } fLastLineNumber= lineNumber; return true; @@ -152,22 +154,25 @@ private int getModelCaret() { private void drawHighlightLine(Position position) { // if the position that is about to be drawn was deleted then we can't - if (position.isDeleted()) + if (position.isDeleted()) { return; + } int widgetOffset= 0; if (fViewer instanceof ITextViewerExtension5 extension) { widgetOffset= extension.modelOffset2WidgetOffset(position.getOffset()); - if (widgetOffset == -1) + if (widgetOffset == -1) { return; + } } else { IRegion visible= fViewer.getVisibleRegion(); widgetOffset= position.getOffset() - visible.getOffset(); - if (widgetOffset < 0 || visible.getLength() < widgetOffset ) + if (widgetOffset < 0 || visible.getLength() < widgetOffset ) { return; + } } StyledText textWidget= fViewer.getTextWidget(); @@ -202,13 +207,15 @@ public void deactivate(boolean redraw) { /* on turning off the feature one has to paint the currently * highlighted line with the standard background color */ - if (redraw) + if (redraw) { drawHighlightLine(fCurrentLine); + } fViewer.getTextWidget().removeLineBackgroundListener(this); - if (fPositionManager != null) + if (fPositionManager != null) { fPositionManager.unmanagePosition(fCurrentLine); + } fLastLineNumber= -1; fCurrentLine.offset= 0; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java index 3114883ddd9..8388f31eff9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java @@ -49,7 +49,7 @@ class DefaultDocumentAdapter implements IDocumentAdapter, IDocumentListener, IDo */ private IDocument fActiveDocument; /** The registered text change listeners */ - private List fTextChangeListeners= new ArrayList<>(1); + private final List fTextChangeListeners= new ArrayList<>(1); /** * The remembered document event * @since 2.0 @@ -76,7 +76,7 @@ class DefaultDocumentAdapter implements IDocumentAdapter, IDocumentListener, IDo * The data of the event at receipt of documentAboutToBeChanged * @since 2.1 */ - private DocumentEvent fOriginalEvent= new DocumentEvent(); + private final DocumentEvent fOriginalEvent= new DocumentEvent(); /** @@ -94,22 +94,25 @@ public DefaultDocumentAdapter() { @Override public void setDocument(IDocument document) { - if (fDocument != null) + if (fDocument != null) { fDocument.removePrenotifiedDocumentListener(this); + } fDocument= document; fActiveDocument= fDocument; fLineDelimiter= null; - if (fDocument != null) + if (fDocument != null) { fDocument.addPrenotifiedDocumentListener(this); + } } @Override public void addTextChangeListener(TextChangeListener listener) { Assert.isNotNull(listener); - if (!fTextChangeListeners.contains(listener)) + if (!fTextChangeListeners.contains(listener)) { fTextChangeListeners.add(listener); + } } @Override @@ -237,23 +240,26 @@ public int getCharCount() { @Override public String getLineDelimiter() { - if (fLineDelimiter == null) + if (fLineDelimiter == null) { fLineDelimiter= TextUtilities.getDefaultLineDelimiter(fDocument); + } return fLineDelimiter; } @Override public void documentChanged(DocumentEvent event) { // check whether the given event is the one which was remembered - if (fEvent == null || event != fEvent) + if (fEvent == null || event != fEvent) { return; + } if (isPatchedEvent(event) || (event.getOffset() == 0 && event.getLength() == fRememberedLengthOfDocument)) { fLineDelimiter= null; fireTextSet(); } else { - if (event.getOffset() < fRememberedLengthOfFirstLine) + if (event.getOffset() < fRememberedLengthOfFirstLine) { fLineDelimiter= null; + } fireTextChanged(); } } @@ -303,15 +309,17 @@ private void rememberEventData(DocumentEvent event) { */ private void fireTextChanged() { - if (!fIsForwarding) + if (!fIsForwarding) { return; + } TextChangedEvent event= new TextChangedEvent(this); if (fTextChangeListeners != null && !fTextChangeListeners.isEmpty()) { Iterator e= new ArrayList<>(fTextChangeListeners).iterator(); - while (e.hasNext()) + while (e.hasNext()) { e.next().textChanged(event); + } } } @@ -320,15 +328,17 @@ private void fireTextChanged() { */ private void fireTextSet() { - if (!fIsForwarding) + if (!fIsForwarding) { return; + } TextChangedEvent event = new TextChangedEvent(this); if (fTextChangeListeners != null && !fTextChangeListeners.isEmpty()) { Iterator e= new ArrayList<>(fTextChangeListeners).iterator(); - while (e.hasNext()) + while (e.hasNext()) { e.next().textSet(event); + } } } @@ -337,13 +347,15 @@ private void fireTextSet() { */ private void fireTextChanging() { - if (!fIsForwarding) + if (!fIsForwarding) { return; + } try { IDocument document= fEvent.getDocument(); - if (document == null) + if (document == null) { return; + } TextChangingEvent event= new TextChangingEvent(this); event.start= fEvent.fOffset; @@ -355,8 +367,9 @@ private void fireTextChanging() { if (fTextChangeListeners != null && !fTextChangeListeners.isEmpty()) { Iterator e= new ArrayList<>(fTextChangeListeners).iterator(); - while (e.hasNext()) - e.next().textChanging(event); + while (e.hasNext()) { + e.next().textChanging(event); + } } } catch (BadLocationException e) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultIndentLineAutoEditStrategy.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultIndentLineAutoEditStrategy.java index 49b05ccec4a..89b781e6116 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultIndentLineAutoEditStrategy.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultIndentLineAutoEditStrategy.java @@ -60,8 +60,9 @@ protected int findEndOfWhiteSpace(IDocument document, int offset, int end) throw */ private void autoIndentAfterNewLine(IDocument d, DocumentCommand c) { - if (c.offset == -1 || d.getLength() == 0) + if (c.offset == -1 || d.getLength() == 0) { return; + } try { // find start of line @@ -87,7 +88,8 @@ private void autoIndentAfterNewLine(IDocument d, DocumentCommand c) { @Override public void customizeDocumentCommand(IDocument d, DocumentCommand c) { - if (c.length == 0 && c.text != null && TextUtilities.endsWith(d.getLegalLineDelimiters(), c.text) != -1) + if (c.length == 0 && c.text != null && TextUtilities.endsWith(d.getLegalLineDelimiters(), c.text) != -1) { autoIndentAfterNewLine(d, c); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java index 87dc5042bd3..84e8853c5a9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultInformationControl.java @@ -334,13 +334,15 @@ public void setInformation(String content) { maxHeight-= trim.height; maxWidth-= fText.getCaret().getSize().x; // StyledText adds a border at the end of the line for the caret. } - if (isResizable()) + if (isResizable()) { maxHeight= Integer.MAX_VALUE; + } - if (fPresenter instanceof IInformationPresenterExtension) + if (fPresenter instanceof IInformationPresenterExtension) { content= ((IInformationPresenterExtension)fPresenter).updatePresentation(fText, content, fPresentation, maxWidth, maxHeight); - else + } else { content= fPresenter.updatePresentation(getShell().getDisplay(), content, fPresentation, maxWidth, maxHeight); + } if (content != null) { fText.setText(content); @@ -358,8 +360,9 @@ public void setVisible(boolean visible) { Point currentSize= getShell().getSize(); getShell().pack(true); Point newSize= getShell().getSize(); - if (newSize.x > currentSize.x || newSize.y > currentSize.y) + if (newSize.x > currentSize.x || newSize.y > currentSize.y) { setSize(currentSize.x, currentSize.y); // restore previous size + } } } @@ -376,8 +379,9 @@ public Point computeSizeHint() { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=117602 int widthHint= SWT.DEFAULT; Point constraints= getSizeConstraints(); - if (constraints != null && fText.getWordWrap()) + if (constraints != null && fText.getWordWrap()) { widthHint= constraints.x; + } return getShell().computeSize(widthHint, SWT.DEFAULT, true); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextDoubleClickStrategy.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextDoubleClickStrategy.java index 58f7443d589..8f68662e31d 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextDoubleClickStrategy.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextDoubleClickStrategy.java @@ -104,11 +104,13 @@ public char next() { @Override public char previous() { - if (fIndex == fOffset) + if (fIndex == fOffset) { return DONE; + } - if (fIndex > fOffset) + if (fIndex > fOffset) { -- fIndex; + } return current(); } @@ -150,7 +152,7 @@ public Object clone() { * The document character iterator used by this strategy. * @since 2.0 */ - private DocumentCharacterIterator fDocIter= new DocumentCharacterIterator(); + private final DocumentCharacterIterator fDocIter= new DocumentCharacterIterator(); /** * The locale specific word break iterator. @@ -181,15 +183,18 @@ public void doubleClicked(ITextViewer text) { int offset= text.getSelectedRange().x; - if (offset < 0) + if (offset < 0) { return; + } final IDocument document= text.getDocument(); IRegion region= findExtendedDoubleClickSelection(document, offset); - if (region == null) + if (region == null) { region= findWord(document, offset); - if (region != null) + } + if (region != null) { text.setSelectedRange(region.getOffset(), region.getLength()); + } } @@ -228,8 +233,9 @@ protected IRegion findWord(IDocument document, int offset) { * @since 3.7 */ private BreakIterator getWordBreakIterator() { - if (fWordBreakIterator == null) + if (fWordBreakIterator == null) { fWordBreakIterator= BreakIterator.getWordInstance(); + } return fWordBreakIterator; } @@ -245,8 +251,9 @@ private BreakIterator getWordBreakIterator() { * @since 3.7 */ private BreakIterator getPOSIXWordBreakIterator() { - if (fPOSIXWordBreakIterator == null) + if (fPOSIXWordBreakIterator == null) { fPOSIXWordBreakIterator= BreakIterator.getWordInstance(new Locale("en", "US", "POSIX")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return fPOSIXWordBreakIterator; } @@ -267,30 +274,35 @@ private IRegion findWord(IDocument document, int offset, BreakIterator wordBreak return null; } - if (offset > line.getOffset() + line.getLength()) + if (offset > line.getOffset() + line.getLength()) { return null; + } fDocIter.setDocument(document, line); wordBreakIterator.setText(fDocIter); int start= wordBreakIterator.preceding(offset); - if (start == BreakIterator.DONE) + if (start == BreakIterator.DONE) { start= line.getOffset(); + } int end= wordBreakIterator.following(offset); - if (end == BreakIterator.DONE) + if (end == BreakIterator.DONE) { end= line.getOffset() + line.getLength(); + } if (wordBreakIterator.isBoundary(offset)) { - if (end - offset > offset - start) + if (end - offset > offset - start) { start= offset; - else + } else { end= offset; + } } - if (end == start) + if (end == start) { return null; + } int length= end - start; try { @@ -301,8 +313,9 @@ private IRegion findWord(IDocument document, int offset, BreakIterator wordBreak int wordStart= wordRegion.getOffset(); int wordEnd= wordStart + wordRegion.getLength(); // Check that no additional breaks besides '.' are introduced - if ((wordStart == start || wordStart > start && document.getChar(wordStart - 1) == '.') && (wordEnd == end || wordEnd < end && document.getChar(wordEnd) == '.')) + if ((wordStart == start || wordStart > start && document.getChar(wordStart - 1) == '.') && (wordEnd == end || wordEnd < end && document.getChar(wordEnd) == '.')) { return wordRegion; + } } } } catch (BadLocationException e) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java index 4482c6473c9..0f79c6d6fd9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java @@ -30,7 +30,7 @@ public class DefaultTextHover implements ITextHover { /** This hover's source viewer */ - private ISourceViewer fSourceViewer; + private final ISourceViewer fSourceViewer; /** * Creates a new annotation hover. @@ -51,8 +51,9 @@ public DefaultTextHover(ISourceViewer sourceViewer) { @Override public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { IAnnotationModel model= getAnnotationModel(fSourceViewer); - if (model == null) + if (model == null) { return null; + } Iterator e= model.getAnnotationIterator(); while (e.hasNext()) { @@ -61,8 +62,9 @@ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { Position p= model.getPosition(a); if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { String msg= a.getText(); - if (msg != null && !msg.trim().isEmpty()) + if (msg != null && !msg.trim().isEmpty()) { return msg; + } } } } @@ -104,8 +106,9 @@ private IRegion findWord(IDocument document, int offset) { while (pos >= 0) { c= document.getChar(pos); - if (!Character.isUnicodeIdentifierPart(c)) + if (!Character.isUnicodeIdentifierPart(c)) { break; + } --pos; } @@ -116,8 +119,9 @@ private IRegion findWord(IDocument document, int offset) { while (pos < length) { c= document.getChar(pos); - if (!Character.isUnicodeIdentifierPart(c)) + if (!Character.isUnicodeIdentifierPart(c)) { break; + } ++pos; } @@ -127,12 +131,13 @@ private IRegion findWord(IDocument document, int offset) { } if (start >= -1 && end > -1) { - if (start == offset && end == offset) + if (start == offset && end == offset) { return new Region(offset, 0); - else if (start == offset) + } else if (start == offset) { return new Region(start, end - start); - else + } else { return new Region(start + 1, end - start - 1); + } } return null; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java index e40932c70ea..5d019fda1c8 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java @@ -144,10 +144,11 @@ public void dispose() { protected void undoTextChange() { try { IDocument document= fTextViewer.getDocument(); - if (document instanceof IDocumentExtension4) + if (document instanceof IDocumentExtension4) { ((IDocumentExtension4)document).replace(fStart, fText.length(), fPreservedText, fUndoModificationStamp); - else + } else { document.replace(fStart, fText.length(), fPreservedText); + } } catch (BadLocationException x) { } } @@ -264,10 +265,11 @@ public IStatus undo(IProgressMonitor monitor, IAdaptable uiInfo) { protected void redoTextChange() { try { IDocument document= fTextViewer.getDocument(); - if (document instanceof IDocumentExtension4) + if (document instanceof IDocumentExtension4) { ((IDocumentExtension4)document).replace(fStart, fEnd - fStart, fText, fRedoModificationStamp); - else + } else { fTextViewer.getDocument().replace(fStart, fEnd - fStart, fText); + } } catch (BadLocationException x) { } } @@ -427,7 +429,7 @@ protected long getRedoModificationStamp() { class CompoundTextCommand extends TextCommand { /** The list of individual commands */ - private List fCommands= new ArrayList<>(); + private final List fCommands= new ArrayList<>(); /** * Creates a new compound text command. @@ -519,8 +521,9 @@ protected void updateCommand() { @Override protected TextCommand createCurrent() { - if (!fFoldingIntoCompoundChange) + if (!fFoldingIntoCompoundChange) { return new TextCommand(fUndoContext); + } reinitialize(); return this; @@ -529,8 +532,9 @@ protected TextCommand createCurrent() { @Override protected void commit() { // if there is pending data, update the command - if (fStart > -1) + if (fStart > -1) { updateCommand(); + } fCurrent= createCurrent(); resetProcessChangeSate(); } @@ -543,8 +547,9 @@ protected void commit() { */ @Override protected boolean isValid() { - if (isConnected()) + if (isConnected()) { return (fStart > -1 || !fCommands.isEmpty()); + } return false; } @@ -556,10 +561,11 @@ protected boolean isValid() { */ @Override protected long getUndoModificationStamp() { - if (fStart > -1) + if (fStart > -1) { return super.getUndoModificationStamp(); - else if (!fCommands.isEmpty()) + } else if (!fCommands.isEmpty()) { return fCommands.get(0).getUndoModificationStamp(); + } return fUndoModificationStamp; } @@ -572,10 +578,11 @@ else if (!fCommands.isEmpty()) */ @Override protected long getRedoModificationStamp() { - if (fStart > -1) + if (fStart > -1) { return super.getRedoModificationStamp(); - else if (!fCommands.isEmpty()) + } else if (!fCommands.isEmpty()) { return fCommands.get(fCommands.size()-1).getRedoModificationStamp(); + } return fRedoModificationStamp; } @@ -599,8 +606,9 @@ public void mouseDoubleClick(MouseEvent e) { */ @Override public void mouseDown(MouseEvent e) { - if (e.button == 1) + if (e.button == 1) { commit(); + } } /* @@ -659,8 +667,9 @@ public void documentChanged(DocumentEvent event) { // top operation but changes state. IUndoableOperation op= fHistory.getUndoOperation(fUndoContext); boolean wasValid= false; - if (op != null) + if (op != null) { wasValid= op.canUndo(); + } // Process the change, providing the before and after timestamps processChange(event.getOffset(), event.getOffset() + event.getLength(), event.getText(), fReplacedText, fPreservedUndoModificationStamp, fPreservedRedoModificationStamp); @@ -670,8 +679,9 @@ public void documentChanged(DocumentEvent event) { if (op == fCurrent) { // if the document change did not cause a new fCurrent to be created, then we should // notify the history that the current operation changed if its validity has changed. - if (wasValid != fCurrent.isValid()) + if (wasValid != fCurrent.isValid()) { fHistory.operationChanged(op); + } } else { // if the change created a new fCurrent that we did not yet add to the @@ -699,8 +709,9 @@ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput @Override public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput != null) { - if (fDocumentListener == null) + if (fDocumentListener == null) { fDocumentListener= new DocumentListener(); + } newInput.addDocumentListener(fDocumentListener); } } @@ -726,8 +737,9 @@ public void historyNotification(final OperationHistoryEvent event) { // if we are undoing/redoing a command we generated, then ignore // the document changes associated with this undo or redo. if (event.getOperation() instanceof TextCommand) { - if (fTextViewer instanceof TextViewer) + if (fTextViewer instanceof TextViewer) { ((TextViewer) fTextViewer).ignoreAutoEditStrategies(true); + } listenToTextChanges(false); // in the undo case only, make sure compounds are closed @@ -754,8 +766,9 @@ public void historyNotification(final OperationHistoryEvent event) { fTextViewer.getTextWidget().getDisplay().syncExec(() -> { listenToTextChanges(true); fOperation= null; - if (fTextViewer instanceof TextViewer) + if (fTextViewer instanceof TextViewer) { ((TextViewer) fTextViewer).ignoreAutoEditStrategies(false); + } }); } break; @@ -801,7 +814,7 @@ public void historyNotification(final OperationHistoryEvent event) { * The undo context. * @since 3.1 */ - private IOperationHistory fHistory; + private final IOperationHistory fHistory; /** * The operation history. * @since 3.1 @@ -812,7 +825,7 @@ public void historyNotification(final OperationHistoryEvent event) { * and after the individual commands are performed. * @since 3.1 */ - private IOperationHistoryListener fHistoryListener= new HistoryListener(); + private final IOperationHistoryListener fHistoryListener= new HistoryListener(); /** * The command last added to the operation history. This must be tracked @@ -929,8 +942,9 @@ private void disposeCommandStack() { * @since 3.1 */ private void initializeCommandStack() { - if (fHistory != null && fUndoContext != null) + if (fHistory != null && fUndoContext != null) { fHistory.dispose(fUndoContext, true, true, false); + } } @@ -962,8 +976,9 @@ private void commit() { // document change. if (fLastAddedCommand != fCurrent) { fCurrent.pretendCommit(); - if (fCurrent.isValid()) + if (fCurrent.isValid()) { addToCommandStack(fCurrent); + } } fCurrent.commit(); } @@ -988,8 +1003,9 @@ private void resetProcessChangeSate() { */ private boolean isWhitespaceText(String text) { - if (text == null || text.isEmpty()) + if (text == null || text.isEmpty()) { return false; + } String[] delimiters= fTextViewer.getDocument().getLegalLineDelimiters(); int index= TextUtilities.startsWith(delimiters, text); @@ -998,8 +1014,9 @@ private boolean isWhitespaceText(String text) { int length= text.length(); for (int i= delimiters[index].length(); i < length; i++) { c= text.charAt(i); - if (c != ' ' && c != '\t') + if (c != ' ' && c != '\t') { return false; + } } return true; } @@ -1009,17 +1026,20 @@ private boolean isWhitespaceText(String text) { private void processChange(int modelStart, int modelEnd, String insertedText, String replacedText, long beforeChangeModificationStamp, long afterChangeModificationStamp) { - if (insertedText == null) + if (insertedText == null) { insertedText= ""; //$NON-NLS-1$ + } - if (replacedText == null) + if (replacedText == null) { replacedText= ""; //$NON-NLS-1$ + } int length= insertedText.length(); int diff= modelEnd - modelStart; - if (fCurrent.fUndoModificationStamp == IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) + if (fCurrent.fUndoModificationStamp == IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } // normalize if (diff < 0) { @@ -1034,26 +1054,31 @@ private void processChange(int modelStart, int modelEnd, String insertedText, St // by typing or whitespace if (!fInserting || (modelStart != fCurrent.fStart + fTextBuffer.length())) { fCurrent.fRedoModificationStamp= beforeChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } fInserting= true; } - if (fCurrent.fStart < 0) + if (fCurrent.fStart < 0) { fCurrent.fStart= fCurrent.fEnd= modelStart; - if (length > 0) + } + if (length > 0) { fTextBuffer.append(insertedText); + } } else if (length >= 0) { // by pasting or model manipulation fCurrent.fRedoModificationStamp= beforeChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } fCurrent.fStart= fCurrent.fEnd= modelStart; fTextBuffer.append(insertedText); fCurrent.fRedoModificationStamp= afterChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= afterChangeModificationStamp; + } } } else { @@ -1089,8 +1114,9 @@ private void processChange(int modelStart, int modelEnd, String insertedText, St // either DEL or backspace for the first time fCurrent.fRedoModificationStamp= beforeChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } // as we can not decide whether it was DEL or backspace we initialize for backspace fPreservedTextBuffer.append(replacedText); @@ -1103,8 +1129,9 @@ private void processChange(int modelStart, int modelEnd, String insertedText, St } else if (length > 0) { // whereby selection is not empty fCurrent.fRedoModificationStamp= beforeChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } fCurrent.fStart= modelStart; fCurrent.fEnd= modelEnd; @@ -1121,14 +1148,16 @@ private void processChange(int modelStart, int modelEnd, String insertedText, St // because of overwrite mode or model manipulation if (!fOverwriting || (modelStart != fCurrent.fStart + fTextBuffer.length())) { fCurrent.fRedoModificationStamp= beforeChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } fOverwriting= true; } - if (fCurrent.fStart < 0) + if (fCurrent.fStart < 0) { fCurrent.fStart= modelStart; + } fCurrent.fEnd= modelEnd; fTextBuffer.append(insertedText); @@ -1139,8 +1168,9 @@ private void processChange(int modelStart, int modelEnd, String insertedText, St } // because of typing or pasting whereby selection is not empty fCurrent.fRedoModificationStamp= beforeChangeModificationStamp; - if (fCurrent.attemptCommit()) + if (fCurrent.attemptCommit()) { fCurrent.fUndoModificationStamp= beforeChangeModificationStamp; + } fCurrent.fStart= modelStart; fCurrent.fEnd= modelEnd; @@ -1163,18 +1193,20 @@ private void openErrorDialog(final String title, final Exception ex) { Shell shell= null; if (isConnected()) { StyledText st= fTextViewer.getTextWidget(); - if (st != null && !st.isDisposed()) + if (st != null && !st.isDisposed()) { shell= st.getShell(); + } } - if (Display.getCurrent() != null) + if (Display.getCurrent() != null) { MessageDialog.openError(shell, title, ex.getLocalizedMessage()); - else { + } else { Display display; final Shell finalShell= shell; - if (finalShell != null) + if (finalShell != null) { display= finalShell.getDisplay(); - else + } else { display= Display.getDefault(); + } display.syncExec(() -> MessageDialog.openError(finalShell, title, ex.getLocalizedMessage())); } } @@ -1193,8 +1225,9 @@ public void connect(ITextViewer textViewer) { fTextViewer= textViewer; fTextBuffer= new StringBuilder(); fPreservedTextBuffer= new StringBuilder(); - if (fUndoContext == null) + if (fUndoContext == null) { fUndoContext= new ObjectUndoContext(this); + } fHistory.setLimit(fUndoContext, fUndoLevel); @@ -1280,8 +1313,9 @@ public void undo() { protected void selectAndReveal(int offset, int length) { if (fTextViewer instanceof ITextViewerExtension5 extension) { extension.exposeModelRange(new Region(offset, length)); - } else if (!fTextViewer.overlapsWithVisibleRegion(offset, length)) + } else if (!fTextViewer.overlapsWithVisibleRegion(offset, length)) { fTextViewer.resetVisibleRegion(); + } fTextViewer.setSelectedRange(offset, length); fTextViewer.revealRange(offset, length); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentClone.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentClone.java index 5dc45ba0210..4e3ac45e581 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentClone.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentClone.java @@ -28,7 +28,7 @@ class DocumentClone extends AbstractDocument { private static class StringTextStore implements ITextStore { - private String fContent; + private final String fContent; /** * Creates a new string text store with the given content. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java index 43782181eb6..ce1545b516c 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java @@ -60,8 +60,9 @@ private static class Command implements Comparable { * @since 3.0 */ public Command(int offset, int length, String text, IDocumentListener owner) { - if (offset < 0 || length < 0) + if (offset < 0 || length < 0) { throw new IllegalArgumentException(); + } fOffset= offset; fLength= length; fText= text; @@ -76,40 +77,47 @@ public Command(int offset, int length, String text, IDocumentListener owner) { */ public void execute(IDocument document) throws BadLocationException { - if (fLength == 0 && fText == null) + if (fLength == 0 && fText == null) { return; + } - if (fOwner != null) + if (fOwner != null) { document.removeDocumentListener(fOwner); + } document.replace(fOffset, fLength, fText); - if (fOwner != null) + if (fOwner != null) { document.addDocumentListener(fOwner); + } } @Override public int compareTo(Command object) { - if (isEqual(object)) + if (isEqual(object)) { return 0; + } Command command= object; // diff middle points if not intersecting if (fOffset + fLength <= command.fOffset || command.fOffset + command.fLength <= fOffset) { int value= (2 * fOffset + fLength) - (2 * command.fOffset + command.fLength); - if (value != 0) + if (value != 0) { return value; + } } // the answer return 42; } private boolean isEqual(Object object) { - if (object == this) + if (object == this) { return true; - if (!(object instanceof final Command command)) + } + if (!(object instanceof final Command command)) { return false; + } return command.fOffset == fOffset && command.fLength == fLength; } } @@ -129,8 +137,9 @@ private static class ReverseListIterator implements Iterator { * @param listIterator the iterator that this reverse iterator is based upon */ public ReverseListIterator(ListIterator listIterator) { - if (listIterator == null) + if (listIterator == null) { throw new IllegalArgumentException(); + } fListIterator= listIterator; } @@ -162,7 +171,7 @@ private static class CommandIterator implements Iterator { private Command fCommand; /** A flag indicating the direction of iteration. */ - private boolean fForward; + private final boolean fForward; /** * Creates a command iterator. @@ -172,8 +181,9 @@ private static class CommandIterator implements Iterator { * @param forward the direction */ public CommandIterator(final List commands, final Command command, final boolean forward) { - if (commands == null || command == null) + if (commands == null || command == null) { throw new IllegalArgumentException(); + } fIterator= forward ? commands.iterator() : new ReverseListIterator<>(commands.listIterator(commands.size())); fCommand= command; fForward= forward; @@ -187,11 +197,13 @@ public boolean hasNext() { @Override public Command next() { - if (!hasNext()) + if (!hasNext()) { throw new NoSuchElementException(); + } - if (fCommand == null) + if (fCommand == null) { return fIterator.next(); + } if (!fIterator.hasNext()) { final Command tempCommand= fCommand; @@ -308,25 +320,29 @@ boolean fillEvent(VerifyEvent event, IRegion modelRange) { public void addCommand(int commandOffset, int commandLength, String commandText, IDocumentListener commandOwner) throws BadLocationException { final Command command= new Command(commandOffset, commandLength, commandText, commandOwner); - if (intersects(command)) + if (intersects(command)) { throw new BadLocationException(); + } final int index= Collections.binarySearch(fCommands, command); // a command with exactly the same ranges exists already - if (index >= 0) + if (index >= 0) { throw new BadLocationException(); + } // binary search result is defined as (-(insertionIndex) - 1) final int insertionIndex= -(index + 1); // overlaps to the right? - if (insertionIndex != fCommands.size() && intersects(fCommands.get(insertionIndex), command)) + if (insertionIndex != fCommands.size() && intersects(fCommands.get(insertionIndex), command)) { throw new BadLocationException(); + } // overlaps to the left? - if (insertionIndex != 0 && intersects(fCommands.get(insertionIndex - 1), command)) + if (insertionIndex != 0 && intersects(fCommands.get(insertionIndex - 1), command)) { throw new BadLocationException(); + } fCommands.add(insertionIndex, command); } @@ -363,8 +379,9 @@ public int getCommandCount() { */ private boolean intersects(Command command0, Command command1) { // diff middle points if not intersecting - if (command0.fOffset + command0.fLength <= command1.fOffset || command1.fOffset + command1.fLength <= command0.fOffset) + if (command0.fOffset + command0.fLength <= command1.fOffset || command1.fOffset + command1.fLength <= command0.fOffset) { return (2 * command0.fOffset + command0.fLength) - (2 * command1.fOffset + command1.fLength) == 0; + } return true; } @@ -377,8 +394,9 @@ private boolean intersects(Command command0, Command command1) { */ private boolean intersects(Command command) { // diff middle points if not intersecting - if (offset + length <= command.fOffset || command.fOffset + command.fLength <= offset) + if (offset + length <= command.fOffset || command.fOffset + command.fLength <= offset) { return (2 * offset + length) - (2 * command.fOffset + command.fLength) == 0; + } return true; } @@ -391,8 +409,9 @@ private boolean intersects(Command command) { */ void execute(IDocument document) throws BadLocationException { - if (length == 0 && text == null && fCommands.isEmpty()) + if (length == 0 && text == null && fCommands.isEmpty()) { return; + } DefaultPositionUpdater updater= new DefaultPositionUpdater(getCategory()); Position caretPosition= null; @@ -405,8 +424,9 @@ void execute(IDocument document) throws BadLocationException { } final Command originalCommand= new Command(offset, length, text, owner); - for (final Iterator iterator= new CommandIterator(fCommands, originalCommand, false); iterator.hasNext(); ) + for (final Iterator iterator= new CommandIterator(fCommands, originalCommand, false); iterator.hasNext(); ) { iterator.next().execute(document); + } } catch (BadLocationException e) { // ignore diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java index de047a91b57..65e95c6da50 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java @@ -78,10 +78,11 @@ public ProposalComputer(String contents, int position) { boolean isEscape= false; esc: for (int i= position - 1; i >= 0; i--) { - if (fExpression.charAt(i) == '\\') + if (fExpression.charAt(i) == '\\') { isEscape= !isEscape; - else + } else { break esc; + } } fIsEscape= isEscape; } @@ -105,8 +106,9 @@ public IContentProposal[] computeFindProposals() { addBsProposal("\\e", RegExMessages.getString("displayString_bs_e"), RegExMessages.getString("additionalInfo_bs_e")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addBracketProposal("\\c", 2, RegExMessages.getString("displayString_bs_c"), RegExMessages.getString("additionalInfo_bs_c")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (! fIsEscape) + if (! fIsEscape) { addBracketProposal(".", 1, RegExMessages.getString("displayString_dot"), RegExMessages.getString("additionalInfo_dot")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } addBsProposal("\\d", RegExMessages.getString("displayString_bs_d"), RegExMessages.getString("additionalInfo_bs_d")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addBsProposal("\\D", RegExMessages.getString("displayString_bs_D"), RegExMessages.getString("additionalInfo_bs_D")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addBsProposal("\\s", RegExMessages.getString("displayString_bs_s"), RegExMessages.getString("additionalInfo_bs_s")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ @@ -211,8 +213,9 @@ public IContentProposal[] computeReplaceProposals() { if (fDocumentOffset > 0 && '$' == fExpression.charAt(fDocumentOffset - 1)) { addProposal("", RegExMessages.getString("displayString_dollar"), RegExMessages.getString("additionalInfo_dollar")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { - if (! fIsEscape) + if (! fIsEscape) { addProposal("$", RegExMessages.getString("displayString_dollar"), RegExMessages.getString("additionalInfo_dollar")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } addBsProposal("\\", RegExMessages.getString("displayString_replace_cap"), RegExMessages.getString("additionalInfo_replace_cap")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addBsProposal("\\", RegExMessages.getString("displayString_replace_bs"), RegExMessages.getString("additionalInfo_replace_bs")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addBsProposal("\\R", RegExMessages.getString("displayString_replace_bs_R"), RegExMessages.getString("additionalInfo_replace_bs_R")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ @@ -333,8 +336,9 @@ public FindReplaceDocumentAdapterContentProposalProvider(boolean isFind) { @Override public IContentProposal [] getProposals(String contents, int position) { - if (fIsFind) + if (fIsFind) { return new ProposalComputer(contents, position).computeFindProposals(); + } return new ProposalComputer(contents, position).computeReplaceProposals(); } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/ITextViewerExtension8.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/ITextViewerExtension8.java index 698391b86aa..205b793d04a 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/ITextViewerExtension8.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/ITextViewerExtension8.java @@ -75,7 +75,7 @@ public static final class EnrichMode { public static final EnrichMode ON_CLICK= new EnrichMode("on click"); //$NON-NLS-1$; - private String fName; + private final String fName; private EnrichMode(String name) { fName= name; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/JFaceTextUtil.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/JFaceTextUtil.java index 86d8cab3533..2f94fa3ac86 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/JFaceTextUtil.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/JFaceTextUtil.java @@ -100,19 +100,22 @@ public static int getBottomIndex(StyledText widget) { int bottom= widget.getLineIndex(lastPixel); // bottom is the first line - no more checking - if (bottom == 0) + if (bottom == 0) { return bottom; + } int pixel= widget.getLinePixel(bottom); // bottom starts on or before the client area start - bottom is the only visible line - if (pixel <= 0) + if (pixel <= 0) { return bottom; + } int height= computeLineHeight(widget, bottom); // bottom is not showing entirely - use the previous line - if (pixel + height - 1 > lastPixel) + if (pixel + height - 1 > lastPixel) { return bottom - 1; + } // bottom is fully visible and its last line is exactly the last pixel return bottom; @@ -129,8 +132,9 @@ public static int getPartialTopIndex(StyledText widget) { int top= widget.getTopIndex(); int pixels= widget.getLinePixel(top); - if (pixels > 0) + if (pixels > 0) { top--; + } return top; } @@ -199,8 +203,9 @@ public static int getPartialBottomIndex(ITextViewer viewer) { public static ILineRange getVisibleModelLines(ITextViewer viewer) { int top= getPartialTopIndex(viewer); int bottom= getPartialBottomIndex(viewer); - if (top == -1 || bottom == -1) + if (top == -1 || bottom == -1) { return null; + } return new LineRange(top, bottom - top + 1); } @@ -222,8 +227,9 @@ public static int widgetLine2ModelLine(ITextViewer viewer, int widgetLine) { try { IRegion r= viewer.getVisibleRegion(); IDocument d= viewer.getDocument(); - if (d == null) + if (d == null) { return -1; + } modelLine= widgetLine + d.getLineOfOffset(r.getOffset()); } catch (BadLocationException x) { modelLine= widgetLine; @@ -249,15 +255,17 @@ public static int modelLineToWidgetLine(ITextViewer viewer, final int modelLine) } else { IRegion region= viewer.getVisibleRegion(); IDocument document= viewer.getDocument(); - if (document == null) + if (document == null) { return -1; + } try { int visibleStartLine= document.getLineOfOffset(region.getOffset()); int visibleEndLine= document.getLineOfOffset(region.getOffset() + region.getLength()); - if (modelLine < visibleStartLine || modelLine > visibleEndLine) + if (modelLine < visibleStartLine || modelLine > visibleEndLine) { widgetLine= -1; - else - widgetLine= modelLine - visibleStartLine; + } else { + widgetLine= modelLine - visibleStartLine; + } } catch (BadLocationException x) { // ignore and return -1 widgetLine= -1; @@ -341,9 +349,9 @@ public static Rectangle computeArea(IRegion region, ITextViewer textViewer) { StyledText styledText= textViewer.getTextWidget(); Rectangle bounds; - if (end > 0 && start < end) + if (end > 0 && start < end) { bounds= styledText.getTextBounds(start, end - 1); - else { + } else { Point loc= styledText.getLocationAtOffset(start); bounds= new Rectangle(loc.x, loc.y, getAverageCharWidth(textViewer.getTextWidget()), computeLineHeight(styledText, styledText.getLineAtOffset(start))); @@ -370,8 +378,9 @@ private static IRegion modelRange2WidgetRange(IRegion region, ITextViewer textVi IRegion visibleRegion= textViewer.getVisibleRegion(); int start= region.getOffset() - visibleRegion.getOffset(); int end= start + region.getLength(); - if (end > visibleRegion.getLength()) + if (end > visibleRegion.getLength()) { end= visibleRegion.getLength(); + } return new Region(start, end - start); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/MarginPainter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/MarginPainter.java index b4430051a92..8798f167858 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/MarginPainter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/MarginPainter.java @@ -88,8 +88,9 @@ public void setMarginRulerStyle(int lineStyle) { * @param lineWidth the line width */ public void setMarginRulerWidth(int lineWidth) { - if (lineWidth == 1) + if (lineWidth == 1) { lineWidth= 0; // NOTE: 0 means width is 1 but with optimized performance + } fLineWidth= lineWidth; } @@ -130,8 +131,9 @@ public void deactivate(boolean redraw) { fIsActive= false; fCachedWidgetX= -1; fTextWidget.removePaintListener(this); - if (redraw) + if (redraw) { fTextWidget.redraw(); + } } } @@ -145,11 +147,13 @@ public void paint(int reason) { if (!fIsActive) { fIsActive= true; fTextWidget.addPaintListener(this); - if (fCachedWidgetX == -1) + if (fCachedWidgetX == -1) { computeWidgetX(); + } fTextWidget.redraw(); - } else if (CONFIGURATION == reason || INTERNAL == reason) + } else if (CONFIGURATION == reason || INTERNAL == reason) { fTextWidget.redraw(); + } } @Override diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java index e9c38bbd20f..ec3508caecf 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java @@ -70,13 +70,15 @@ protected void adaptToInsert() { int yoursStart= fOffset; - if (myEnd < yoursStart) + if (myEnd < yoursStart) { return; + } - if (myStart <= yoursStart) + if (myStart <= yoursStart) { fPosition.length += fReplaceLength; - else + } else { fPosition.offset += fReplaceLength; + } } } @@ -90,9 +92,9 @@ static class PositionManager implements IPaintPositionManager { // /** The document this position manager works on */ private IDocument fDocument; /** The position updater used for the managing position category */ - private IPositionUpdater fPositionUpdater; + private final IPositionUpdater fPositionUpdater; /** The managing position category */ - private String fCategory; + private final String fCategory; /** * Creates a new position manager. Initializes the managing @@ -175,11 +177,11 @@ public void unmanagePosition(Position position) { /** The painters managed by this paint manager. */ - private List fPainters= new ArrayList<>(2); + private final List fPainters= new ArrayList<>(2); /** The position manager used by this paint manager */ private PositionManager fManager; /** The associated text viewer */ - private ITextViewer fTextViewer; + private final ITextViewer fTextViewer; /** * Creates a new paint manager for the given text viewer. @@ -201,8 +203,9 @@ public PaintManager(ITextViewer textViewer) { public void addPainter(IPainter painter) { if (!fPainters.contains(painter)) { fPainters.add(painter); - if (fPainters.size() == 1) + if (fPainters.size() == 1) { install(); + } painter.setPositionManager(fManager); painter.paint(IPainter.INTERNAL); } @@ -220,8 +223,9 @@ public void removePainter(IPainter painter) { painter.deactivate(true); painter.setPositionManager(null); } - if (fPainters.isEmpty()) + if (fPainters.isEmpty()) { dispose(); + } } /** @@ -267,8 +271,9 @@ public void dispose() { fManager= null; } - for (IPainter iPainter : fPainters) + for (IPainter iPainter : fPainters) { iPainter.dispose(); + } fPainters.clear(); fTextViewer.removeTextInputListener(this); @@ -282,8 +287,9 @@ public void dispose() { */ private void removeListeners() { ISelectionProvider provider= fTextViewer.getSelectionProvider(); - if (provider != null) + if (provider != null) { provider.removeSelectionChangedListener(this); + } fTextViewer.removeTextListener(this); @@ -301,8 +307,9 @@ private void removeListeners() { * @see IPainter */ private void paint(int reason) { - for (IPainter iPainter : fPainters) + for (IPainter iPainter : fPainters) { iPainter.paint(reason); + } } @Override @@ -335,14 +342,16 @@ public void selectionChanged(SelectionChangedEvent event) { @Override public void textChanged(TextEvent event) { - if (!event.getViewerRedrawState()) + if (!event.getViewerRedrawState()) { return; + } Control control= fTextViewer.getTextWidget(); if (control != null) { control.getDisplay().asyncExec(() -> { - if (fTextViewer != null) + if (fTextViewer != null) { paint(IPainter.TEXT_CHANGE); + } }); } } @@ -350,8 +359,9 @@ public void textChanged(TextEvent event) { @Override public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput != null) { - for (IPainter iPainter : fPainters) + for (IPainter iPainter : fPainters) { iPainter.deactivate(false); + } fManager.uninstall(oldInput); removeListeners(); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PropagatingFontFieldEditor.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PropagatingFontFieldEditor.java index fbd6eee7881..65e9ae19623 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PropagatingFontFieldEditor.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/PropagatingFontFieldEditor.java @@ -41,9 +41,9 @@ public class PropagatingFontFieldEditor extends FontFieldEditor { /** The editor's parent widget */ - private Composite fParent; + private final Composite fParent; /** The representation of the default font choice */ - private String fDefaultFontLabel; + private final String fDefaultFontLabel; /** * Creates a new font field editor with the given parameters. @@ -61,8 +61,9 @@ public PropagatingFontFieldEditor(String name, String labelText, Composite paren @Override protected void doLoad() { - if (getPreferenceStore().isDefault(getPreferenceName())) + if (getPreferenceStore().isDefault(getPreferenceName())) { loadDefault(); + } super.doLoad(); checkForDefault(); } @@ -117,8 +118,9 @@ private static void propagateFont(IPreferenceStore source, String sourceKey, IPr */ public static void startPropagate(final IPreferenceStore source, final String sourceKey, final IPreferenceStore target, final String targetKey) { source.addPropertyChangeListener(event -> { - if (sourceKey.equals(event.getProperty())) + if (sourceKey.equals(event.getProperty())) { propagateFont(source, sourceKey, target, targetKey); + } }); propagateFont(source, sourceKey, target, targetKey); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/SurroundWithBracketsStrategy.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/SurroundWithBracketsStrategy.java index 41dee55d993..dbbfa62eb43 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/SurroundWithBracketsStrategy.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/SurroundWithBracketsStrategy.java @@ -25,7 +25,7 @@ */ public class SurroundWithBracketsStrategy implements IAutoEditStrategy { - private ISourceViewer sourceViewer; + private final ISourceViewer sourceViewer; @SuppressWarnings("nls") private final Map bracketsMap= Map.of("(", ")", "[", "]", "{", "}", "<", ">", "\"", "\"", "'", "'", "`", "`"); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TabsToSpacesConverter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TabsToSpacesConverter.java index c342a3039ba..258749783fa 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TabsToSpacesConverter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TabsToSpacesConverter.java @@ -49,21 +49,24 @@ public void setLineTracker(ILineTracker lineTracker) { private int insertTabString(StringBuilder buffer, int offsetInLine) { - if (fTabRatio == 0) + if (fTabRatio == 0) { return 0; + } int remainder= offsetInLine % fTabRatio; remainder= fTabRatio - remainder; - for (int i= 0; i < remainder; i++) + for (int i= 0; i < remainder; i++) { buffer.append(' '); + } return remainder; } @Override public void customizeDocumentCommand(IDocument document, DocumentCommand command) { String text= command.text; - if (text == null) + if (text == null) { return; + } if (text.isEmpty()) { @@ -112,14 +115,17 @@ public void customizeDocumentCommand(IDocument document, DocumentCommand command } private void replaceDeleteSpaceByDeleteTab(IDocument document, DocumentCommand command) { - if (!fDeleteSpacesAsTab || fTabRatio == 0 || command.length != 1) + if (!fDeleteSpacesAsTab || fTabRatio == 0 || command.length != 1) { return; + } ITextSelection selection= command.fSelection; - if (selection == null || selection.getLength() != 0) + if (selection == null || selection.getLength() != 0) { return; + } try { - if (document.getChar(command.offset) != ' ') + if (document.getChar(command.offset) != ' ') { return; + } IRegion line= document.getLineInformationOfOffset(command.offset); int offsetInLine= command.offset - line.getOffset(); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextAttribute.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextAttribute.java index ac4aea7da22..ddfa0b4ce18 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextAttribute.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextAttribute.java @@ -43,13 +43,13 @@ public class TextAttribute { /** Foreground color */ - private Color foreground; + private final Color foreground; /** Background color */ - private Color background; + private final Color background; /** The text style */ - private int style; + private final int style; /** * The text font. @@ -105,11 +105,13 @@ public TextAttribute(Color foreground) { @Override public boolean equals(Object object) { - if (object == this) + if (object == this) { return true; + } - if (!(object instanceof TextAttribute a)) + if (!(object instanceof TextAttribute a)) { return false; + } return (a.style == style && equals(a.foreground, foreground) && equals(a.background, background) && equals(a.font, font)); } @@ -122,8 +124,9 @@ public boolean equals(Object object) { * @since 2.0 */ private boolean equals(Object o1, Object o2) { - if (o1 != null) + if (o1 != null) { return o1.equals(o2); + } return (o2 == null); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextEvent.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextEvent.java index 05d80cfca0c..851053bf272 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextEvent.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextEvent.java @@ -36,20 +36,20 @@ public class TextEvent { /** Start offset of the change */ - private int fOffset; + private final int fOffset; /** The length of the change */ - private int fLength; + private final int fLength; /** Inserted text */ - private String fText; + private final String fText; /** Replaced text */ - private String fReplacedText; + private final String fReplacedText; /** The original document event, may by null */ - private DocumentEvent fDocumentEvent; + private final DocumentEvent fDocumentEvent; /** * The redraw state of the viewer issuing this event * @since 2.0 */ - private boolean fViewerRedrawState; + private final boolean fViewerRedrawState; /** * Creates a new TextEvent based on the specification. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java index d7e3cd766d2..e2e50ba2864 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java @@ -52,8 +52,9 @@ public static void applyTextPresentation(TextPresentation presentation, StyledTe int i= 0; Iterator e= presentation.getAllStyleRangeIterator(); - while (e.hasNext()) + while (e.hasNext()) { ranges[i++]= e.next(); + } text.setStyleRanges(ranges); } @@ -89,8 +90,9 @@ protected FilterIterator(boolean skipDefaults) { fIndex= getFirstIndexInWindow(fWindow); fLength= getFirstIndexAfterWindow(fWindow); - if (fSkipDefaults) + if (fSkipDefaults) { computeIndex(); + } } @Override @@ -101,8 +103,9 @@ public StyleRange next() { } catch (IndexOutOfBoundsException x) { throw new NoSuchElementException(); } finally { - if (fSkipDefaults) + if (fSkipDefaults) { computeIndex(); + } } } @@ -126,8 +129,9 @@ protected boolean skip(Object o) { * Computes the index of the styled range that is the next to be enumerated. */ protected void computeIndex() { - while (fIndex < fLength && skip(fRanges.get(fIndex))) + while (fIndex < fLength && skip(fRanges.get(fIndex))) { ++fIndex; + } } } @@ -208,8 +212,9 @@ public void setDefaultStyleRange(StyleRange range) { */ public StyleRange getDefaultStyleRange() { StyleRange range= createWindowRelativeRange(fResultWindow, fDefaultRange); - if (range == null) + if (range == null) { return null; + } return (StyleRange)range.clone(); } @@ -256,8 +261,9 @@ public void mergeStyleRange(StyleRange range) { * @since 3.0 */ private void applyStyleRange(StyleRange range, boolean merge) { - if (range.length == 0) + if (range.length == 0) { return; + } checkConsistency(range); @@ -267,8 +273,9 @@ private void applyStyleRange(StyleRange range, boolean merge) { if (fRanges.isEmpty()) { StyleRange defaultRange= getDefaultStyleRange(); - if (defaultRange == null) + if (defaultRange == null) { defaultRange= range; + } defaultRange.start= start; defaultRange.length= length; @@ -280,8 +287,9 @@ private void applyStyleRange(StyleRange range, boolean merge) { if (first == fRanges.size()) { StyleRange defaultRange= getDefaultStyleRange(); - if (defaultRange == null) + if (defaultRange == null) { defaultRange= range; + } defaultRange.start= start; defaultRange.length= length; applyStyle(range, defaultRange, merge); @@ -301,15 +309,17 @@ private void applyStyleRange(StyleRange range, boolean merge) { return; } - if (start >= currentEnd) + if (start >= currentEnd) { continue; + } StyleRange currentCopy= (end < currentEnd) ? (StyleRange) current.clone() : null; if (start < currentStart) { // Apply style to new default range and add it StyleRange defaultRange= getDefaultStyleRange(); - if (defaultRange == null) + if (defaultRange == null) { defaultRange= new StyleRange(); + } defaultRange.start= start; defaultRange.length= currentStart - start; @@ -355,8 +365,9 @@ private void applyStyleRange(StyleRange range, boolean merge) { if (length > 0) { // Apply style to new default range and add it StyleRange defaultRange= getDefaultStyleRange(); - if (defaultRange == null) + if (defaultRange == null) { defaultRange= range; + } defaultRange.start= start; defaultRange.length= end - start; applyStyle(range, defaultRange, merge); @@ -404,13 +415,15 @@ private void applyStyleRanges(StyleRange[] ranges, boolean merge) { ArrayList newRanges= new ArrayList<>(2*ranges.length + oldRanges.size()); for (StyleRange range : ranges) { fRanges= oldRanges; // for getFirstIndexAfterWindow(...) - for (int m= getFirstIndexAfterWindow(new Region(range.start, range.length)); j < m; j++) + for (int m= getFirstIndexAfterWindow(new Region(range.start, range.length)); j < m; j++) { newRanges.add(oldRanges.get(j)); + } fRanges= newRanges; // for mergeStyleRange(...) applyStyleRange(range, merge); } - for (int m= oldRanges.size(); j < m; j++) + for (int m= oldRanges.size(); j < m; j++) { newRanges.add(oldRanges.get(j)); + } fRanges= newRanges; } @@ -424,33 +437,42 @@ private void applyStyleRanges(StyleRange[] ranges, boolean merge) { */ private void applyStyle(StyleRange template, StyleRange target, boolean merge) { if (merge) { - if (template.font != null) + if (template.font != null) { target.font= template.font; + } target.fontStyle|= template.fontStyle; - if (template.metrics != null) + if (template.metrics != null) { target.metrics= template.metrics; + } - if (template.foreground != null || template.underlineStyle == SWT.UNDERLINE_LINK) + if (template.foreground != null || template.underlineStyle == SWT.UNDERLINE_LINK) { target.foreground= template.foreground; - if (template.background != null) + } + if (template.background != null) { target.background= template.background; + } target.strikeout|= template.strikeout; - if (template.strikeoutColor != null) + if (template.strikeoutColor != null) { target.strikeoutColor= template.strikeoutColor; + } target.underline|= template.underline; - if (template.underlineStyle != SWT.NONE && target.underlineStyle != SWT.UNDERLINE_LINK) + if (template.underlineStyle != SWT.NONE && target.underlineStyle != SWT.UNDERLINE_LINK) { target.underlineStyle= template.underlineStyle; + } - if (template.underlineColor != null) + if (template.underlineColor != null) { target.underlineColor= template.underlineColor; + } - if (template.borderStyle != SWT.NONE) + if (template.borderStyle != SWT.NONE) { target.borderStyle= template.borderStyle; - if (template.borderColor != null) + } + if (template.borderColor != null) { target.borderColor= template.borderColor; + } } else { target.font= template.font; @@ -477,18 +499,21 @@ private void applyStyle(StyleRange template, StyleRange target, boolean merge) { */ private void checkConsistency(StyleRange range) { - if (range == null) + if (range == null) { throw new IllegalArgumentException(); + } if (fDefaultRange != null) { - if (range.start < fDefaultRange.start) + if (range.start < fDefaultRange.start) { range.start= fDefaultRange.start; + } int defaultEnd= fDefaultRange.start + fDefaultRange.length; int end= range.start + range.length; - if (end > defaultEnd) + if (end > defaultEnd) { range.length -= (end - defaultEnd); + } } } @@ -506,10 +531,11 @@ private int getFirstIndexInWindow(IRegion window) { while (j - i > 1) { int k= (i + j) >> 1; StyleRange r= fRanges.get(k); - if (r.start + r.length > start) + if (r.start + r.length > start) { j= k; - else + } else { i= k; + } } return j; } @@ -530,10 +556,11 @@ private int getFirstIndexAfterWindow(IRegion window) { while (j - i > 1) { int k= (i + j) >> 1; StyleRange r= fRanges.get(k); - if (r.start < end) + if (r.start < end) { i= k; - else + } else { j= k; + } } return j; } @@ -550,12 +577,14 @@ private int getFirstIndexAfterWindow(IRegion window) { * @return the window relative range based on the absolute range */ private StyleRange createWindowRelativeRange(IRegion window, StyleRange range) { - if (window == null || range == null) + if (window == null || range == null) { return range; + } int start= range.start - window.getOffset(); - if (start < 0) + if (start < 0) { start= 0; + } int rangeEnd= range.start + range.length; int windowEnd= window.getOffset() + window.getLength(); @@ -577,12 +606,14 @@ private StyleRange createWindowRelativeRange(IRegion window, StyleRange range) { * @since 3.0 */ private IRegion createWindowRelativeRegion(IRegion coverage) { - if (fResultWindow == null || coverage == null) + if (fResultWindow == null || coverage == null) { return coverage; + } int start= coverage.getOffset() - fResultWindow.getOffset(); - if (start < 0) + if (start < 0) { start= 0; + } int rangeEnd= coverage.getOffset() + coverage.getLength(); int windowEnd= fResultWindow.getOffset() + fResultWindow.getLength(); @@ -680,8 +711,9 @@ public IRegion getCoverage() { StyleRange first= getFirstStyleRange(); StyleRange last= getLastStyleRange(); - if (first == null || last == null) + if (first == null || last == null) { return null; + } return new Region(first.start, last.start - first. start + last.length); } @@ -694,8 +726,9 @@ public IRegion getCoverage() { * @since 3.0 */ public IRegion getExtent() { - if (fExtent != null) + if (fExtent != null) { return createWindowRelativeRegion(fExtent); + } return getCoverage(); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextSelection.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextSelection.java index ebaa434231f..f00e89c62d8 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextSelection.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextSelection.java @@ -49,9 +49,9 @@ public static ITextSelection emptySelection() { /** Document which delivers the data of the selection, possibly null. */ private final IDocument fDocument; /** Offset of the selection */ - private int fOffset; + private final int fOffset; /** Length of the selection */ - private int fLength; + private final int fLength; /** @@ -123,8 +123,9 @@ public int getLength() { public int getStartLine() { try { - if (fDocument != null) + if (fDocument != null) { return fDocument.getLineOfOffset(fOffset); + } } catch (BadLocationException x) { // ignore } @@ -137,8 +138,9 @@ public int getEndLine() { try { if (fDocument != null) { int endOffset= fOffset + fLength; - if (fLength != 0) + if (fLength != 0) { endOffset--; + } return fDocument.getLineOfOffset(endOffset); } } catch (BadLocationException x) { @@ -151,8 +153,9 @@ public int getEndLine() { @Override public String getText() { try { - if (fDocument != null) + if (fDocument != null) { return fDocument.get(fOffset, fLength); + } } catch (BadLocationException x) { // ignore } @@ -162,20 +165,24 @@ public String getText() { @Override public boolean equals(Object obj) { - if (obj == this) + if (obj == this) { return true; + } - if (obj == null || getClass() != obj.getClass()) + if (obj == null || getClass() != obj.getClass()) { return false; + } TextSelection s= (TextSelection) obj; boolean sameRange= (s.fOffset == fOffset && s.fLength == fLength); if (sameRange) { - if (s.fDocument == null && fDocument == null) + if (s.fDocument == null && fDocument == null) { return true; - if (s.fDocument == null || fDocument == null) + } + if (s.fDocument == null || fDocument == null) { return false; + } try { String sContent= s.fDocument.get(fOffset, fLength); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java index 6174d4451fa..ca86c49b3ab 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java @@ -174,19 +174,22 @@ public void setEvent(DocumentEvent e) { if (e instanceof SlaveDocumentEvent slave) { DocumentEvent master= slave.getMasterEvent(); - if (master != null) + if (master != null) { preservedText= master.getDocument().get(master.getOffset(), master.getLength()); + } } else { preservedText= e.getDocument().get(e.getOffset(), e.getLength()); } } catch (BadLocationException x) { preservedText= null; - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.WidgetCommand.setEvent")); //$NON-NLS-1$ + } } - } else + } else { preservedText= null; + } } } @@ -208,8 +211,9 @@ public void mouseUp(MouseEvent e) { @Override public void getNextOffset(MovementEvent event) { - if (event.movement != SWT.MOVEMENT_WORD_END) + if (event.movement != SWT.MOVEMENT_WORD_END) { return; + } if (TRACE_DOUBLE_CLICK) { System.out.println("\n+++"); //$NON-NLS-1$ @@ -217,15 +221,17 @@ public void getNextOffset(MovementEvent event) { } if (fDoubleClickSelection != null) { - if (fDoubleClickSelection.x <= event.offset && event.offset <= fDoubleClickSelection.y) + if (fDoubleClickSelection.x <= event.offset && event.offset <= fDoubleClickSelection.y) { event.newOffset= fDoubleClickSelection.y; + } } } @Override public void getPreviousOffset(MovementEvent event) { - if (event.movement != SWT.MOVEMENT_WORD_START) + if (event.movement != SWT.MOVEMENT_WORD_START) { return; + } if (TRACE_DOUBLE_CLICK) { System.out.println("\n---"); //$NON-NLS-1$ @@ -238,12 +244,14 @@ public void getPreviousOffset(MovementEvent event) { s.doubleClicked(TextViewer.this); fDoubleClickSelection= textWidget.getSelection(); event.newOffset= fDoubleClickSelection.x; - if (TRACE_DOUBLE_CLICK) + if (TRACE_DOUBLE_CLICK) { System.out.println("- setting selection: x= " + fDoubleClickSelection.x + ", y= " + fDoubleClickSelection.y); //$NON-NLS-1$ //$NON-NLS-2$ + } } } else { - if (fDoubleClickSelection.x <= event.offset && event.offset <= fDoubleClickSelection.y) + if (fDoubleClickSelection.x <= event.offset && event.offset <= fDoubleClickSelection.y) { event.newOffset= fDoubleClickSelection.x; + } } } } @@ -301,8 +309,9 @@ public void keyPressed(KeyEvent e) { */ @Override public void mouseUp(MouseEvent e) { - if (fTextWidget != null) + if (fTextWidget != null) { fTextWidget.removeSelectionListener(this); + } updateViewportListeners(MOUSE_END); } @@ -311,8 +320,9 @@ public void mouseUp(MouseEvent e) { */ @Override public void mouseDown(MouseEvent e) { - if (fTextWidget != null) + if (fTextWidget != null) { fTextWidget.addSelectionListener(this); + } } /* @@ -320,10 +330,11 @@ public void mouseDown(MouseEvent e) { */ @Override public void widgetSelected(SelectionEvent e) { - if (e.widget == fScroller) + if (e.widget == fScroller) { updateViewportListeners(SCROLLER); - else + } else { updateViewportListeners(MOUSE); + } } /* @@ -360,16 +371,18 @@ protected void adaptToInsert() { int yoursStart= fOffset; - if (myEnd < yoursStart) + if (myEnd < yoursStart) { return; + } if (myStart <= yoursStart) { fPosition.length += fReplaceLength; return; } - if (myStart > yoursStart) + if (myStart > yoursStart) { fPosition.offset += fReplaceLength; + } } } @@ -383,8 +396,9 @@ class VisibleDocumentListener implements IDocumentListener { */ @Override public void documentAboutToBeChanged(DocumentEvent e) { - if (e.getDocument() == getVisibleDocument()) + if (e.getDocument() == getVisibleDocument()) { fWidgetCommand.setEvent(e); + } handleVisibleDocumentAboutToBeChanged(e); } @@ -393,8 +407,9 @@ public void documentAboutToBeChanged(DocumentEvent e) { */ @Override public void documentChanged(DocumentEvent e) { - if (fWidgetCommand.event == e) + if (fWidgetCommand.event == e) { updateTextListeners(fWidgetCommand); + } fLastSentSelectionChange= null; handleVisibleDocumentChanged(e); } @@ -423,8 +438,9 @@ public void forward(boolean forward) { @Override public void verifyText(VerifyEvent e) { - if (fForward) + if (fForward) { handleVerifyEvent(e); + } } } @@ -462,16 +478,17 @@ public Batch(VerifyKeyListener l, int i) { } /** List of registered verify key listeners. */ - private List fListeners= new ArrayList<>(); + private final List fListeners= new ArrayList<>(); /** List of pending batches. */ - private List fBatched= new ArrayList<>(); + private final List fBatched= new ArrayList<>(); /** The reentrance count. */ private int fReentranceCount= 0; @Override public void verifyKey(VerifyEvent event) { - if (fListeners.isEmpty()) + if (fListeners.isEmpty()) { return; + } try { fReentranceCount++; @@ -483,8 +500,9 @@ public void verifyKey(VerifyEvent event) { } finally { fReentranceCount--; } - if (fReentranceCount == 0) + if (fReentranceCount == 0) { processBatchedRequests(); + } } /** @@ -543,17 +561,20 @@ public void insertListener(VerifyKeyListener listener, int index) { // move or add it if (idx != index) { - if (idx != -1) + if (idx != -1) { fListeners.remove(idx); + } - if (index > fListeners.size()) + if (index > fListeners.size()) { fListeners.add(listener); - else + } else { fListeners.add(index, listener); + } } - if (size == 0) // checking old size, i.e. current size == size + 1 + if (size == 0) { // checking old size, i.e. current size == size + 1 install(); + } } } } @@ -564,8 +585,9 @@ public void insertListener(VerifyKeyListener listener, int index) { * @param listener the listener to be removed */ public void removeListener(VerifyKeyListener listener) { - if (listener == null) + if (listener == null) { return; + } if (fReentranceCount > 0) { @@ -577,8 +599,9 @@ public void removeListener(VerifyKeyListener listener) { for (int i= 0; i < size; i++) { if (listener == fListeners.get(i)) { fListeners.remove(i); - if (size == 1) // checking old size, i.e. current size == size - 1 + if (size == 1) { // checking old size, i.e. current size == size - 1 uninstall(); + } return; } } @@ -590,8 +613,9 @@ public void removeListener(VerifyKeyListener listener) { */ private void install() { StyledText textWidget= getTextWidget(); - if (textWidget != null && !textWidget.isDisposed()) + if (textWidget != null && !textWidget.isDisposed()) { textWidget.addVerifyKeyListener(this); + } } /** @@ -599,8 +623,9 @@ private void install() { */ private void uninstall() { StyledText textWidget= getTextWidget(); - if (textWidget != null && !textWidget.isDisposed()) + if (textWidget != null && !textWidget.isDisposed()) { textWidget.removeVerifyKeyListener(this); + } } } @@ -663,8 +688,9 @@ public void lineGetBackground(LineBackgroundEvent event) { if (fTextWidget != null) { int offset= widgetOffset2ModelOffset(event.lineOffset); - if (fPosition.includes(offset)) + if (fPosition.includes(offset)) { event.lineBackground= fHighlightColor; + } } } @@ -705,8 +731,9 @@ public void uninstall() { document.removePosition(fPosition); } - if (fTextWidget != null && !fTextWidget.isDisposed()) + if (fTextWidget != null && !fTextWidget.isDisposed()) { fTextWidget.removeLineBackgroundListener(this); + } TextViewer.this.removeTextListener(this); @@ -717,8 +744,9 @@ public void uninstall() { * Clears the highlighting of this range. */ private void clear() { - if (fTextWidget != null && !fTextWidget.isDisposed()) + if (fTextWidget != null && !fTextWidget.isDisposed()) { fTextWidget.redraw(); + } } /** @@ -746,8 +774,9 @@ private void paint() { @Override public void textChanged(TextEvent event) { - if (event.getViewerRedrawState()) + if (event.getViewerRedrawState()) { paint(); + } } @Override @@ -756,10 +785,11 @@ public void update(DocumentEvent event) { int length= event.getLength(); int delta= event.getText().length() - length; - if (offset < fPosition.getOffset()) + if (offset < fPosition.getOffset()) { fPosition.setOffset(fPosition.getOffset() + delta); - else if (offset < fPosition.getOffset() + fPosition.getLength()) + } else if (offset < fPosition.getOffset() + fPosition.getLength()) { fPosition.setLength(fPosition.getLength() + delta); + } } } @@ -805,11 +835,13 @@ public void replaceSelection(String text, boolean regExReplace) { try { IRegion matchRegion= TextViewer.this.getFindReplaceDocumentAdapter().replace(text, regExReplace); int length= -1; - if (matchRegion != null) + if (matchRegion != null) { length= matchRegion.getLength(); + } - if (text != null && length > 0) + if (text != null && length > 0) { TextViewer.this.setSelectedRange(s.x, length); + } } catch (BadLocationException x) { } } @@ -926,8 +958,9 @@ public void setSelection(IRegion[] widgetRegions) { @Override public void setScope(IRegion scope) { - if (fRange != null) + if (fRange != null) { fRange.uninstall(); + } if (scope == null) { fRange= null; @@ -941,8 +974,9 @@ public void setScope(IRegion scope) { @Override public void setScopeHighlightColor(Color color) { - if (fRange != null) + if (fRange != null) { fRange.setHighlightColor(color); + } fScopeHighlightColor= color; } @@ -961,8 +995,9 @@ public void setReplaceAllMode(boolean replaceAll) { TextViewer.this.setRedraw(false); TextViewer.this.startSequentialRewriteMode(false); - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.beginCompoundChange(); + } fRememberedPartitioners= TextUtilities.removeDocumentPartitioners(document); } @@ -975,11 +1010,13 @@ public void setReplaceAllMode(boolean replaceAll) { TextViewer.this.setRedraw(true); TextViewer.this.stopSequentialRewriteMode(); - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.endCompoundChange(); + } - if (fRememberedPartitioners != null) + if (fRememberedPartitioners != null) { TextUtilities.addDocumentPartitioners(document, fRememberedPartitioners); + } } } } @@ -994,14 +1031,16 @@ class RewriteTarget implements IRewriteTarget { @Override public void beginCompoundChange() { - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.beginCompoundChange(); + } } @Override public void endCompoundChange() { - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.endCompoundChange(); + } } @Override @@ -1025,7 +1064,7 @@ public void setRedraw(boolean redraw) { protected class TextHoverKey { /** The content type this key belongs to */ - private String fContentType; + private final String fContentType; /** The state mask */ private int fStateMask; @@ -1043,8 +1082,9 @@ protected TextHoverKey(String contentType, int stateMask) { @Override public boolean equals(Object obj) { - if (obj == null || obj.getClass() != getClass()) + if (obj == null || obj.getClass() != getClass()) { return false; + } TextHoverKey textHoverKey= (TextHoverKey)obj; return textHoverKey.fContentType.equals(fContentType) && textHoverKey.fStateMask == fStateMask; } @@ -1113,8 +1153,9 @@ private final class ViewerState { */ public ViewerState() { IDocument document= getDocument(); - if (document != null) + if (document != null) { connect(document); + } } /** @@ -1123,8 +1164,9 @@ public ViewerState() { * @return the normalized selection */ public Point[] getSelection() { - if (fSelections == null) + if (fSelections == null) { return new Point[0]; + } return Arrays.stream(fSelections).map(position -> new Point(position.getOffset(), position.getLength())).toArray(Point[]::new); } @@ -1156,8 +1198,9 @@ public void updateSelection(Position[] selections) { * false to only restore the selection */ public void restore(boolean restoreViewport) { - if (isConnected()) + if (isConnected()) { disconnect(); + } if (fSelections != null && fSelections.length > 0) { if (fSelections[0] instanceof ColumnPosition cp) { IDocument document= fDocument; @@ -1182,8 +1225,9 @@ public void restore(boolean restoreViewport) { : new Region(position.getOffset(), position.getLength())) .toArray(IRegion[]::new)); } - if (restoreViewport) + if (restoreViewport) { updateViewport(); + } } } @@ -1204,8 +1248,9 @@ private void updateViewport() { return; } int stableWidgetLine= getClosestWidgetLineForModelLine(stableLine); - if (stableWidgetLine == -1) + if (stableWidgetLine == -1) { return; + } int linePixel= getTextWidget().getLinePixel(stableWidgetLine); int delta= fStablePixel - linePixel; int topPixel= getTextWidget().getTopPixel(); @@ -1381,8 +1426,9 @@ public void mouseDown(MouseEvent e) { @Override public void mouseUp(MouseEvent event) { - if (!fTextWidget.isTextSelected()) + if (!fTextWidget.isTextSelected()) { queuePostSelectionChanged(false); + } } } @@ -1396,25 +1442,29 @@ private class DocumentRewriteSessionListener implements IDocumentRewriteSessionL public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { IRewriteTarget target= TextViewer.this.getRewriteTarget(); final boolean toggleRedraw; - if (REDRAW_BUG_158746) + if (REDRAW_BUG_158746) { toggleRedraw= true; - else + } else { toggleRedraw= event.getSession().getSessionType() != DocumentRewriteSessionType.UNRESTRICTED_SMALL; + } final boolean viewportStabilize= !toggleRedraw; if (DocumentRewriteSessionEvent.SESSION_START == event.getChangeType()) { - if (toggleRedraw) + if (toggleRedraw) { target.setRedraw(false); + } target.beginCompoundChange(); - if (viewportStabilize && fViewerState == null) + if (viewportStabilize && fViewerState == null) { fViewerState= new ViewerState(); + } } else if (DocumentRewriteSessionEvent.SESSION_STOP == event.getChangeType()) { if (viewportStabilize && fViewerState != null) { fViewerState.restore(true); fViewerState= null; } target.endCompoundChange(); - if (toggleRedraw) + if (toggleRedraw) { target.setRedraw(true); + } } } } @@ -1479,15 +1529,15 @@ public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { /** Caches the graphical coordinate of the first visible line */ private int fTopInset= 0; /** The most recent document modification as widget command */ - private WidgetCommand fWidgetCommand= new WidgetCommand(); + private final WidgetCommand fWidgetCommand= new WidgetCommand(); /** The SWT control's scrollbars */ private ScrollBar fScroller; /** Listener on the visible document */ private VisibleDocumentListener fVisibleDocumentListener= new VisibleDocumentListener(); /** Verify listener */ - private TextVerifyListener fVerifyListener= new TextVerifyListener(); + private final TextVerifyListener fVerifyListener= new TextVerifyListener(); /** The most recent widget modification as document command */ - private DocumentCommand fDocumentCommand= new DocumentCommand(); + private final DocumentCommand fDocumentCommand= new DocumentCommand(); /** The viewer's find/replace target */ private IFindReplaceTarget fFindReplaceTarget; /** @@ -1504,7 +1554,7 @@ public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { * The viewer's manager of verify key listeners * @since 2.0 */ - private VerifyKeyListenersManager fVerifyKeyListenersManager= new VerifyKeyListenersManager(); + private final VerifyKeyListenersManager fVerifyKeyListenersManager= new VerifyKeyListenersManager(); /** * The mark position. * @since 2.0 @@ -1559,12 +1609,12 @@ public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { * The set of registered editor helpers. * @since 3.1 */ - private Set fEditorHelpers= new HashSet<>(); + private final Set fEditorHelpers= new HashSet<>(); /** * The internal rewrite session listener. * @since 3.1 */ - private DocumentRewriteSessionListener fDocumentRewriteSessionListener= new DocumentRewriteSessionListener(); + private final DocumentRewriteSessionListener fDocumentRewriteSessionListener= new DocumentRewriteSessionListener(); /** Should the auto indent strategies ignore the next edit operation */ protected boolean fIgnoreAutoIndent= false; @@ -1724,16 +1774,18 @@ protected void createControl(Composite parent, int styles) { // Support scroll page upon MOD1+MouseWheel fTextWidget.addListener(SWT.MouseVerticalWheel, event -> { - if (((event.stateMask & SWT.MOD1) == 0)) + if (((event.stateMask & SWT.MOD1) == 0)) { return; + } int topIndex= fTextWidget.getTopIndex(); int bottomIndex= JFaceTextUtil.getBottomIndex(fTextWidget); - if (event.count > 0) + if (event.count > 0) { fTextWidget.setTopIndex(2 * topIndex - bottomIndex); - else + } else { fTextWidget.setTopIndex(bottomIndex); + } updateViewportListeners(INTERNAL); }); @@ -1753,8 +1805,9 @@ protected void createControl(Composite parent, int styles) { * 1GIYQ9K: ITPUI:WINNT - StyledText swallows Shift+TAB */ fTextWidget.addTraverseListener(e -> { - if ((SWT.SHIFT == e.stateMask) && ('\t' == e.character)) + if ((SWT.SHIFT == e.stateMask) && ('\t' == e.character)) { e.doit= !fTextWidget.getEditable(); + } }); // where does the first line start @@ -1817,8 +1870,9 @@ private void ensureHoverControlManagerInstalled() { @Override public void resetPlugins() { - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.reset(); + } } /** @@ -1885,8 +1939,9 @@ protected void handleDispose() { } if (fVisibleDocumentListener !=null) { - if (fVisibleDocument != null) + if (fVisibleDocument != null) { fVisibleDocument.removeDocumentListener(fVisibleDocumentListener); + } fVisibleDocumentListener= null; } @@ -1896,8 +1951,9 @@ protected void handleDispose() { } if (fSlaveDocumentManager != null) { - if (fVisibleDocument != null) + if (fVisibleDocument != null) { fSlaveDocumentManager.freeSlaveDocument(fVisibleDocument); + } fSlaveDocumentManager= null; } @@ -1966,14 +2022,16 @@ public void setAutoIndentStrategy(IAutoIndentStrategy strategy, String contentTy * @since 3.1 */ protected final void setAutoEditStrategies(IAutoEditStrategy[] strategies, String contentType) { - if (fAutoIndentStrategies == null) + if (fAutoIndentStrategies == null) { fAutoIndentStrategies= new HashMap<>(); + } List autoEditStrategies= fAutoIndentStrategies.get(contentType); if (strategies == null) { - if (autoEditStrategies == null) + if (autoEditStrategies == null) { return; + } fAutoIndentStrategies.put(contentType, null); @@ -1991,11 +2049,13 @@ protected final void setAutoEditStrategies(IAutoEditStrategy[] strategies, Strin @Override public void prependAutoEditStrategy(IAutoEditStrategy strategy, String contentType) { - if (strategy == null || contentType == null) + if (strategy == null || contentType == null) { throw new IllegalArgumentException(); + } - if (fAutoIndentStrategies == null) + if (fAutoIndentStrategies == null) { fAutoIndentStrategies= new HashMap<>(); + } List autoEditStrategies= fAutoIndentStrategies.get(contentType); if (autoEditStrategies == null) { @@ -2008,12 +2068,14 @@ public void prependAutoEditStrategy(IAutoEditStrategy strategy, String contentTy @Override public void removeAutoEditStrategy(IAutoEditStrategy strategy, String contentType) { - if (fAutoIndentStrategies == null) + if (fAutoIndentStrategies == null) { return; + } List autoEditStrategies= fAutoIndentStrategies.get(contentType); - if (autoEditStrategies == null) + if (autoEditStrategies == null) { return; + } for (final Iterator iterator= autoEditStrategies.iterator(); iterator.hasNext(); ) { if (iterator.next().equals(strategy)) { @@ -2022,8 +2084,9 @@ public void removeAutoEditStrategy(IAutoEditStrategy strategy, String contentTyp } } - if (autoEditStrategies.isEmpty()) + if (autoEditStrategies.isEmpty()) { fAutoIndentStrategies.put(contentType, null); + } } @Override @@ -2059,15 +2122,17 @@ public int getTopInset() { @Override public boolean isEditable() { - if (fTextWidget == null) + if (fTextWidget == null) { return false; + } return fTextWidget.getEditable(); } @Override public void setEditable(boolean editable) { - if (fTextWidget != null) + if (fTextWidget != null) { fTextWidget.setEditable(editable); + } } /* @@ -2078,11 +2143,13 @@ public void setEditable(boolean editable) { public void setDefaultPrefixes(String[] defaultPrefixes, String contentType) { if (defaultPrefixes != null && defaultPrefixes.length > 0) { - if (fDefaultPrefixChars == null) + if (fDefaultPrefixChars == null) { fDefaultPrefixChars= new HashMap<>(); + } fDefaultPrefixChars.put(contentType, defaultPrefixes); - } else if (fDefaultPrefixChars != null) + } else if (fDefaultPrefixChars != null) { fDefaultPrefixChars.remove(contentType); + } } @Override @@ -2108,22 +2175,25 @@ public void setTextHover(ITextHover hover, String contentType, int stateMask) { fTextHovers= new HashMap<>(); } fTextHovers.put(key, hover); - } else if (fTextHovers != null) + } else if (fTextHovers != null) { fTextHovers.remove(key); + } ensureHoverControlManagerInstalled(); } @Override public void removeTextHovers(String contentType) { - if (fTextHovers == null) + if (fTextHovers == null) { return; + } Iterator iter= new HashSet<>(fTextHovers.keySet()).iterator(); while (iter.hasNext()) { TextHoverKey key= iter.next(); - if (key.fContentType.equals(contentType)) + if (key.fContentType.equals(contentType)) { fTextHovers.remove(key); + } } } @@ -2146,12 +2216,14 @@ protected ITextHover getTextHover(int offset) { * @since 2.1 */ protected ITextHover getTextHover(int offset, int stateMask) { - if (fTextHovers == null) + if (fTextHovers == null) { return null; + } IDocument document= getDocument(); - if (document == null) + if (document == null) { return null; + } try { TextHoverKey key= new TextHoverKey(TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true), stateMask); @@ -2163,8 +2235,9 @@ protected ITextHover getTextHover(int offset, int stateMask) { } return (ITextHover) textHover; } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.selectContentTypePlugin")); //$NON-NLS-1$ + } } return null; } @@ -2196,8 +2269,9 @@ public void setHoverControlCreator(IInformationControlCreator creator) { */ @Override public void setHoverEnrichMode(ITextViewerExtension8.EnrichMode mode) { - if (fTextHoverManager == null) + if (fTextHoverManager == null) { return; + } fTextHoverManager.setHoverEnrichMode(mode); } @@ -2205,8 +2279,9 @@ public void setHoverEnrichMode(ITextViewerExtension8.EnrichMode mode) { public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (fTextWidget != null) { if (fWidgetTokenKeeper != null) { - if (fWidgetTokenKeeper == requester) - return true; + if (fWidgetTokenKeeper == requester) { + return true; + } if (fWidgetTokenKeeper.requestWidgetToken(this)) { fWidgetTokenKeeper= requester; return true; @@ -2224,8 +2299,9 @@ public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) { if (fTextWidget != null) { if (fWidgetTokenKeeper != null) { - if (fWidgetTokenKeeper == requester) + if (fWidgetTokenKeeper == requester) { return true; + } boolean accepted= false; if (fWidgetTokenKeeper instanceof IWidgetTokenKeeperExtension extension) { @@ -2249,8 +2325,9 @@ public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) { @Override public void releaseWidgetToken(IWidgetTokenKeeper tokenKeeper) { - if (fWidgetTokenKeeper == tokenKeeper) + if (fWidgetTokenKeeper == tokenKeeper) { fWidgetTokenKeeper= null; + } } @@ -2284,8 +2361,9 @@ public Point getSelectedRange() { if (fTextWidget != null) { Point p= fTextWidget.getSelectionRange(); p= widgetSelection2ModelSelection(p); - if (p != null) + if (p != null) { return p; + } } return new Point(-1, -1); @@ -2306,13 +2384,15 @@ private static Position toPosition(IRegion region) { */ private void setSelectedRanges(IRegion[] modelRanges) { if (!redraws()) { - if (fViewerState != null) + if (fViewerState != null) { fViewerState.updateSelection(Arrays.stream(modelRanges).map(TextViewer::toPosition).toArray(Position[]::new)); + } return; } - if (fTextWidget == null) + if (fTextWidget == null) { return; + } IRegion[] widgetSelection= Arrays.stream(modelRanges) .map(range -> new Region(range.getOffset(), range.getLength())) @@ -2370,15 +2450,18 @@ protected void validateSelectionRange(int[] selectionRange) { offset -= length; } - if (offset <0) + if (offset <0) { offset= 0; + } - if (offset > documentLength) + if (offset > documentLength) { offset= documentLength; + } int delta= (offset + length) - documentLength; - if (delta > 0) + if (delta > 0) { length -= delta; + } try { @@ -2460,8 +2543,9 @@ public void setSelection(ISelection selection, boolean reveal) { // fall back to linear selection mode setSelectedRange(s.getOffset(), s.getLength()); } - if (reveal) + if (reveal) { revealRange(s.getOffset(), s.getLength()); + } } else if (selection instanceof IMultiTextSelection multiSelection && multiSelection.getRegions().length > 1) { setSelectedRanges(Arrays.stream(multiSelection.getRegions()) .map(region -> new Region(region.getOffset(), region.getLength())) @@ -2471,8 +2555,9 @@ public void setSelection(ISelection selection, boolean reveal) { } } else if (selection instanceof ITextSelection s) { setSelectedRange(s.getOffset(), s.getLength()); - if (reveal) + if (reveal) { revealRange(s.getOffset(), s.getLength()); + } } } @@ -2500,8 +2585,9 @@ private ITextSelection computeSelection() { IDocument document= getDocument(); Point modelSelection= widgetSelection2ModelSelection(new Point(startOffset, endOffset - startOffset)); - if (modelSelection == null) + if (modelSelection == null) { return TextSelection.emptySelection(); + } startOffset= modelSelection.x; endOffset= modelSelection.x + modelSelection.y; @@ -2511,8 +2597,9 @@ private ITextSelection computeSelection() { int startColumn= startOffset - document.getLineOffset(startLine) + startVirtuals; int endColumn= endOffset - document.getLineOffset(endLine) + endVirtuals; - if (startLine == -1 || endLine == -1) + if (startLine == -1 || endLine == -1) { return TextSelection.emptySelection(); + } return new BlockTextSelection(document, startLine, startColumn, endLine, endColumn, fTextWidget.getTabs()); } catch (BadLocationException e) { return TextSelection.emptySelection(); @@ -2523,8 +2610,9 @@ private ITextSelection computeSelection() { return toSelection(Arrays.stream(fViewerState.getSelection()).map(point -> new Region(point.x, point.y)).toArray(IRegion[]::new)); } - if (fTextWidget == null) + if (fTextWidget == null) { return TextSelection.emptySelection(); + } int[] ranges= fTextWidget.getSelectionRanges(); IRegion[] selectedRanges= new IRegion[ranges.length / 2]; @@ -2562,11 +2650,13 @@ public void addPostSelectionChangedListener(ISelectionChangedListener listener) Assert.isNotNull(listener); - if (fPostSelectionChangedListeners == null) + if (fPostSelectionChangedListeners == null) { fPostSelectionChangedListeners= new ArrayList<>(); + } - if (!fPostSelectionChangedListeners.contains(listener)) + if (!fPostSelectionChangedListeners.contains(listener)) { fPostSelectionChangedListeners.add(listener); + } } @Override @@ -2576,8 +2666,9 @@ public void removePostSelectionChangedListener(ISelectionChangedListener listene if (fPostSelectionChangedListeners != null) { fPostSelectionChangedListeners.remove(listener); - if (fPostSelectionChangedListeners.isEmpty()) + if (fPostSelectionChangedListeners.isEmpty()) { fPostSelectionChangedListeners= null; + } } } @@ -2588,12 +2679,14 @@ public void removePostSelectionChangedListener(ISelectionChangedListener listene * @since 3.0 */ private Display getDisplay() { - if (fTextWidget == null || fTextWidget.isDisposed()) + if (fTextWidget == null || fTextWidget.isDisposed()) { return null; + } Display display= fTextWidget.getDisplay(); - if (display != null && display.isDisposed()) + if (display != null && display.isDisposed()) { return null; + } return display; } @@ -2606,8 +2699,9 @@ private Display getDisplay() { */ private void queuePostSelectionChanged(final boolean fireEqualSelection) { Display display= getDisplay(); - if (display == null) + if (display == null) { return; + } // no synchronization or volatile access needed // because postSelectionChanged() will also run in the same (UI) thread, just later: fFireEqualPostSelectionChange|= fireEqualSelection; @@ -2746,11 +2840,13 @@ public void addTextListener(ITextListener listener) { Assert.isNotNull(listener); - if (fTextListeners == null) + if (fTextListeners == null) { fTextListeners= new ArrayList<>(); + } - if (!fTextListeners.contains(listener)) + if (!fTextListeners.contains(listener)) { fTextListeners.add(listener); + } } @Override @@ -2760,8 +2856,9 @@ public void removeTextListener(ITextListener listener) { if (fTextListeners != null) { fTextListeners.remove(listener); - if (fTextListeners.isEmpty()) + if (fTextListeners.isEmpty()) { fTextListeners= null; + } } } @@ -2776,8 +2873,9 @@ protected void updateTextListeners(WidgetCommand cmd) { if (textListeners != null) { textListeners= new ArrayList<>(textListeners); DocumentEvent event= cmd.event; - if (event instanceof SlaveDocumentEvent) + if (event instanceof SlaveDocumentEvent) { event= ((SlaveDocumentEvent) event).getMasterEvent(); + } TextEvent e= new TextEvent(cmd.start, cmd.length, cmd.text, cmd.preservedText, event, redraws()); for (ITextListener l : textListeners) { @@ -2793,11 +2891,13 @@ public void addTextInputListener(ITextInputListener listener) { Assert.isNotNull(listener); - if (fTextInputListeners == null) + if (fTextInputListeners == null) { fTextInputListeners= new ArrayList<>(); + } - if (!fTextInputListeners.contains(listener)) + if (!fTextInputListeners.contains(listener)) { fTextInputListeners.add(listener); + } } @Override @@ -2807,8 +2907,9 @@ public void removeTextInputListener(ITextInputListener listener) { if (fTextInputListeners != null) { fTextInputListeners.remove(listener); - if (fTextInputListeners.isEmpty()) + if (fTextInputListeners.isEmpty()) { fTextInputListeners= null; + } } } @@ -2862,8 +2963,9 @@ public IDocument getDocument() { public void setInput(Object input) { IDocument document= null; - if (input instanceof IDocument) + if (input instanceof IDocument) { document= (IDocument) input; + } setDocument(document); } @@ -2925,8 +3027,9 @@ public void setDocument(IDocument document, int modelRangeOffset, int modelRange protected IDocument createSlaveDocument(IDocument document) { ISlaveDocumentManager manager= getSlaveDocumentManager(); if (manager != null) { - if (manager.isSlaveDocument(document)) + if (manager.isSlaveDocument(document)) { return document; + } return manager.createSlaveDocument(document); } return document; @@ -2987,8 +3090,9 @@ protected boolean updateSlaveDocument(IDocument slaveDocument, int modelRangeOff */ private void initializeViewportUpdate() { - if (fViewportGuard != null) + if (fViewportGuard != null) { return; + } if (fTextWidget != null) { @@ -2999,8 +3103,9 @@ private void initializeViewportUpdate() { fTextWidget.addMouseListener(fViewportGuard); fScroller= fTextWidget.getVerticalBar(); - if (fScroller != null) + if (fScroller != null) { fScroller.addSelectionListener(fViewportGuard); + } } } @@ -3031,14 +3136,16 @@ public void addViewportListener(IViewportListener listener) { initializeViewportUpdate(); } - if (!fViewportListeners.contains(listener)) + if (!fViewportListeners.contains(listener)) { fViewportListeners.add(listener); + } } @Override public void removeViewportListener(IViewportListener listener) { - if (fViewportListeners != null) + if (fViewportListeners != null) { fViewportListeners.remove(listener); + } } /** @@ -3084,8 +3191,9 @@ public void setTopIndex(int index) { if (fTextWidget != null) { int widgetLine= modelLine2WidgetLine(index); - if (widgetLine == -1) + if (widgetLine == -1) { widgetLine= getClosestWidgetLineForModelLine(index); + } if (widgetLine > -1) { fTextWidget.setTopIndex(widgetLine); @@ -3108,8 +3216,9 @@ public void setTopIndex(int index) { protected int getVisibleLinesInViewport() { if (fTextWidget != null) { Rectangle clArea= fTextWidget.getClientArea(); - if (!clArea.isEmpty()) + if (!clArea.isEmpty()) { return clArea.height / fTextWidget.getLineHeight(); + } } return -1; } @@ -3117,8 +3226,9 @@ protected int getVisibleLinesInViewport() { @Override public int getBottomIndex() { - if (fTextWidget == null) + if (fTextWidget == null) { return -1; + } int widgetBottom= JFaceTextUtil.getBottomIndex(fTextWidget); return widgetLine2ModelLine(widgetBottom); @@ -3133,8 +3243,9 @@ public int getTopIndexStartOffset() { top= getVisibleDocument().getLineOffset(top); return widgetOffset2ModelOffset(top); } catch (BadLocationException ex) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getTopIndexStartOffset")); //$NON-NLS-1$ + } } } @@ -3149,15 +3260,17 @@ public int getBottomIndexEndOffset() { int bottomEndOffset= line.getOffset() + line.getLength() - 1; IRegion coverage= getModelCoverage(); - if (coverage == null) + if (coverage == null) { return -1; + } int coverageEndOffset= coverage.getOffset() + coverage.getLength() - 1; return Math.min(coverageEndOffset, bottomEndOffset); } catch (BadLocationException ex) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getBottomIndexEndOffset")); //$NON-NLS-1$ + } return getDocument().getLength() - 1; } } @@ -3165,8 +3278,9 @@ public int getBottomIndexEndOffset() { @Override public void revealRange(int start, int length) { - if (fTextWidget == null || !redraws()) + if (fTextWidget == null || !redraws()) { return; + } IRegion modelRange= new Region(start, length); IRegion widgetRange= modelRange2ClosestWidgetRange(modelRange); @@ -3174,8 +3288,9 @@ public void revealRange(int start, int length) { int[] range= new int[] { widgetRange.getOffset(), widgetRange.getLength() }; validateSelectionRange(range); - if (range[0] >= 0) + if (range[0] >= 0) { internalRevealRangeWithWorkaround(range[0], range[0] + range[1]); + } } else { @@ -3202,13 +3317,15 @@ private void internalRevealRangeWithWorkaround(int start, int end) { // XXX: Workaround for https://bugs.eclipse.org/375576 final Shell shell= fTextWidget.getShell(); // only the shell layout is deferred int d= 0; - for (; shell.isLayoutDeferred(); d++) + for (; shell.isLayoutDeferred(); d++) { shell.setLayoutDeferred(false); + } try { internalRevealRange(start, end); } finally { - for (; d > 0; d--) + for (; d > 0; d--) { shell.setLayoutDeferred(true); + } } } @@ -3286,12 +3403,13 @@ protected void internalRevealRange(int start, int end) { int visibleWidth= visibleEnd - visibleStart; int selectionPixelWidth= endPixel - startPixel; - if (startPixel < visibleStart) + if (startPixel < visibleStart) { newOffset= startPixel; - else if (selectionPixelWidth + bufferZone < visibleWidth) + } else if (selectionPixelWidth + bufferZone < visibleWidth) { newOffset= endPixel + bufferZone - visibleWidth; - else + } else { newOffset= startPixel; + } float index= ((float)newOffset) / ((float)getAverageCharWidth()); @@ -3376,8 +3494,9 @@ public void refresh() { * @since 2.1 */ protected ISlaveDocumentManager getSlaveDocumentManager() { - if (fSlaveDocumentManager == null) + if (fSlaveDocumentManager == null) { fSlaveDocumentManager= createSlaveDocumentManager(); + } return fSlaveDocumentManager; } @@ -3440,8 +3559,9 @@ private void initializeWidgetContents() { if (fTextWidget != null && fVisibleDocument != null) { // set widget content - if (fDocumentAdapter == null) + if (fDocumentAdapter == null) { fDocumentAdapter= createDocumentAdapter(); + } fDocumentAdapter.setDocument(fVisibleDocument); fTextWidget.setContent(fDocumentAdapter); @@ -3459,8 +3579,9 @@ private void initializeWidgetContents() { */ protected void freeSlaveDocument(IDocument slave) { ISlaveDocumentManager manager= getSlaveDocumentManager(); - if (manager != null && manager.isSlaveDocument(slave)) + if (manager != null && manager.isSlaveDocument(slave)) { manager.freeSlaveDocument(slave); + } } /** @@ -3477,10 +3598,12 @@ protected void setVisibleDocument(IDocument document) { } if (fVisibleDocument != null) { - if (fVisibleDocumentListener != null) + if (fVisibleDocumentListener != null) { fVisibleDocument.removeDocumentListener(fVisibleDocumentListener); - if (fVisibleDocument != document) + } + if (fVisibleDocument != document) { freeSlaveDocument(fVisibleDocument); + } } fVisibleDocument= document; @@ -3489,8 +3612,9 @@ protected void setVisibleDocument(IDocument document) { initializeWidgetContents(); fFindReplaceDocumentAdapter= null; - if (fVisibleDocument != null && fVisibleDocumentListener != null) + if (fVisibleDocument != null && fVisibleDocumentListener != null) { fVisibleDocument.addDocumentListener(fVisibleDocumentListener); + } } /** @@ -3588,8 +3712,9 @@ public void setVisibleRegion(int start, int length) { try { IDocument slaveDocument= createSlaveDocument(getVisibleDocument()); - if (updateSlaveDocument(slaveDocument, start, length)) + if (updateSlaveDocument(slaveDocument, start, length)) { setVisibleDocument(slaveDocument); + } } catch (BadLocationException x) { throw new IllegalArgumentException(JFaceTextMessages.getString("TextViewer.error.invalid_visible_region_2")); //$NON-NLS-1$ @@ -3618,11 +3743,13 @@ public void resetVisibleRegion() { public void setTextDoubleClickStrategy(ITextDoubleClickStrategy strategy, String contentType) { if (strategy != null) { - if (fDoubleClickStrategies == null) + if (fDoubleClickStrategies == null) { fDoubleClickStrategies= new HashMap<>(); + } fDoubleClickStrategies.put(contentType, strategy); - } else if (fDoubleClickStrategies != null) + } else if (fDoubleClickStrategies != null) { fDoubleClickStrategies.remove(contentType); + } } /** @@ -3635,13 +3762,15 @@ public void setTextDoubleClickStrategy(ITextDoubleClickStrategy strategy, String */ protected Object selectContentTypePlugin(int offset, Map plugins) { final IDocument document= getDocument(); - if (document == null) + if (document == null) { return null; + } try { return selectContentTypePlugin(TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true), plugins); } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.selectContentTypePlugin")); //$NON-NLS-1$ + } } return null; } @@ -3656,8 +3785,9 @@ protected Object selectContentTypePlugin(int offset, Map plugins) { */ private Object selectContentTypePlugin(String type, Map plugins) { - if (plugins == null) + if (plugins == null) { return null; + } return plugins.get(type); } @@ -3671,18 +3801,21 @@ private Object selectContentTypePlugin(String type, Map plugins) { * @param command the document command representing the verify event */ protected void customizeDocumentCommand(DocumentCommand command) { - if (isIgnoringAutoEditStrategies()) + if (isIgnoringAutoEditStrategies()) { return; + } IDocument document= getDocument(); - if (fTabsToSpacesConverter != null) + if (fTabsToSpacesConverter != null) { fTabsToSpacesConverter.customizeDocumentCommand(document, command); + } @SuppressWarnings("unchecked") List strategies= (List) selectContentTypePlugin(command.offset, fAutoIndentStrategies); - if (strategies == null) + if (strategies == null) { return; + } switch (strategies.size()) { // optimization @@ -3696,8 +3829,9 @@ protected void customizeDocumentCommand(DocumentCommand command) { // make iterator robust against adding/removing strategies from within strategies default: strategies= new ArrayList<>(strategies); - for (IAutoEditStrategy iAutoEditStrategy : strategies) + for (IAutoEditStrategy iAutoEditStrategy : strategies) { iAutoEditStrategy.customizeDocumentCommand(document, command); + } break; } @@ -3713,8 +3847,9 @@ protected void handleVerifyEvent(VerifyEvent e) { if (fEventConsumer != null) { fEventConsumer.processEvent(e); - if (!e.doit) + if (!e.doit) { return; + } } ITextSelection selection= (ITextSelection)getSelection(); @@ -3740,8 +3875,9 @@ protected void handleVerifyEvent(VerifyEvent e) { fVerifyListener.forward(false); - if (compoundChange && fUndoManager != null) + if (compoundChange && fUndoManager != null) { fUndoManager.beginCompoundChange(); + } fDocumentCommand.execute(getDocument()); @@ -3757,10 +3893,11 @@ protected void handleVerifyEvent(VerifyEvent e) { // try to move it to the closest spot IRegion region= getModelCoverage(); if (region != null) { - if (documentCaret <= region.getOffset()) + if (documentCaret <= region.getOffset()) { widgetCaret= 0; - else if (documentCaret >= region.getOffset() + region.getLength()) + } else if (documentCaret >= region.getOffset() + region.getLength()) { widgetCaret= getVisibleRegion().getLength(); + } } } @@ -3773,13 +3910,15 @@ else if (documentCaret >= region.getOffset() + region.getLength()) } } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.verifyText")); //$NON-NLS-1$ + } } finally { - if (compoundChange && fUndoManager != null) + if (compoundChange && fUndoManager != null) { fUndoManager.endCompoundChange(); + } fVerifyListener.forward(true); @@ -3828,8 +3967,9 @@ private void verifyEventInMultiOrBlockSelection(final VerifyEvent e) { processor.doReplace(selection, e.text); } } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.verifyText")); //$NON-NLS-1$ + } } }); } @@ -3854,8 +3994,9 @@ private boolean isMarkedRegionEmpty() { @Override public boolean canDoOperation(int operation) { - if (fTextWidget == null || !redraws()) + if (fTextWidget == null || !redraws()) { return false; + } switch (operation) { case CUT: @@ -3894,8 +4035,9 @@ public boolean canDoOperation(int operation) { @Override public void doOperation(int operation) { - if (fTextWidget == null || !redraws()) + if (fTextWidget == null || !redraws()) { return; + } Point selection= null; @@ -3916,20 +4058,22 @@ public void doOperation(int operation) { } break; case CUT: - if (!fTextWidget.isTextSelected()) + if (!fTextWidget.isTextSelected()) { copyMarkedRegion(true); - else + } else { wrapCompoundChange(() -> fTextWidget.cut()); + } selection= fTextWidget.getSelectionRange(); fireSelectionChanged(selection.x, selection.y); break; case COPY: - if (!fTextWidget.isTextSelected()) + if (!fTextWidget.isTextSelected()) { copyMarkedRegion(false); - else + } else { fTextWidget.copy(); + } break; case PASTE: paste(); @@ -3940,11 +4084,12 @@ public void doOperation(int operation) { case SELECT_ALL: { IDocument doc= getDocument(); if (doc != null) { - if (fTextWidget.getBlockSelection()) + if (fTextWidget.getBlockSelection()) { // XXX: performance hack: use 1000 for the endColumn - StyledText will not select more than what's possible in the viewport. setSelection(new BlockTextSelection(doc, 0, 0, doc.getNumberOfLines() - 1, 1000, fTextWidget.getTabs())); - else + } else { setSelectedRange(0, doc.getLength()); + } } break; } @@ -3965,9 +4110,10 @@ public void doOperation(int operation) { break; case HyperlinkManager.OPEN_HYPERLINK: boolean atleastOneLinkOpened= fHyperlinkManager.openHyperlink(); - if (!atleastOneLinkOpened) + if (!atleastOneLinkOpened) { MessageDialog.openInformation(getControl().getShell(), JFaceTextMessages.getString("TextViewer.open_hyperlink_error_title"), JFaceTextMessages.getString("TextViewer.open_hyperlink_error_message")); //$NON-NLS-1$ //$NON-NLS-2$ + } return; // Workaround to fix bug 434791 during 4.4 RC2. Will be replaced by official API during 4.5. @@ -3988,8 +4134,9 @@ private void delete() { try { new SelectionProcessor(TextViewer.this).doDelete(getSelection()); } catch (BadLocationException e) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.delete")); //$NON-NLS-1$ + } } }); } @@ -4044,8 +4191,9 @@ private void paste() { } processor.doReplace(selection, toInsert); } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.paste")); //$NON-NLS-1$ + } } finally { clipboard.dispose(); } @@ -4087,17 +4235,19 @@ private void wrapCompoundChange(Runnable runnable) { * @since 2.1 */ protected void ignoreAutoEditStrategies(boolean ignore) { - if (fIgnoreAutoIndent == ignore) + if (fIgnoreAutoIndent == ignore) { return; + } fIgnoreAutoIndent= ignore; IDocument document= getDocument(); if (document instanceof IDocumentExtension2 extension) { - if (ignore) + if (ignore) { extension.ignorePostNotificationReplaces(); - else + } else { extension.acceptPostNotificationReplaces(); + } } } @@ -4127,18 +4277,21 @@ public void enableOperation(int operation, boolean enable) { */ protected void copyMarkedRegion(boolean delete) { - if (fTextWidget == null) + if (fTextWidget == null) { return; + } - if (fMarkPosition == null || fMarkPosition.isDeleted() || modelRange2WidgetRange(fMarkPosition) == null) + if (fMarkPosition == null || fMarkPosition.isDeleted() || modelRange2WidgetRange(fMarkPosition) == null) { return; + } int widgetMarkOffset= modelOffset2WidgetOffset(fMarkPosition.offset); Point selection= fTextWidget.getSelection(); - if (selection.x <= widgetMarkOffset) + if (selection.x <= widgetMarkOffset) { fTextWidget.setSelection(selection.x, widgetMarkOffset); - else + } else { fTextWidget.setSelection(widgetMarkOffset, selection.x); + } if (delete) { wrapCompoundChange(() -> fTextWidget.cut()); @@ -4169,8 +4322,9 @@ protected void deleteText() { protected boolean isBlockSelected() { Point s= getSelectedRange(); - if (s.y == 0) + if (s.y == 0) { return false; + } try { @@ -4195,8 +4349,9 @@ protected boolean isBlockSelected() { */ protected boolean areMultipleLinesSelected() { Point s= getSelectedRange(); - if (s.y == 0) + if (s.y == 0) { return false; + } try { @@ -4227,15 +4382,17 @@ private int getFirstCompleteLineOfRegion(IRegion region) { int startLine= d.getLineOfOffset(region.getOffset()); int offset= d.getLineOffset(startLine); - if (offset >= region.getOffset()) + if (offset >= region.getOffset()) { return startLine; + } offset= d.getLineOffset(startLine + 1); return (offset > region.getOffset() + region.getLength() ? -1 : startLine + 1); } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getFirstCompleteLineOfRegion")); //$NON-NLS-1$ + } } return -1; @@ -4288,8 +4445,9 @@ protected void shift(boolean useDefaultPrefixes, boolean right) { * @since 2.0 */ protected void shift(boolean useDefaultPrefixes, boolean right, boolean ignoreWhitespace) { - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.beginCompoundChange(); + } IDocument d= getDocument(); Map partitioners= null; @@ -4307,8 +4465,9 @@ protected void shift(boolean useDefaultPrefixes, boolean right, boolean ignoreWh // end line of region int length= regions[i].getLength(); int offset= regions[i].getOffset() + length; - if (length > 0) + if (length > 0) { offset--; + } lines[j + 1]= (lines[j] == -1 ? -1 : d.getLineOfOffset(offset)); lineCount += lines[j + 1] - lines[j] + 1; } @@ -4319,29 +4478,33 @@ protected void shift(boolean useDefaultPrefixes, boolean right, boolean ignoreWh setRedraw(false); startSequentialRewriteMode(true); } - if (lineCount >= 20) + if (lineCount >= 20) { partitioners= TextUtilities.removeDocumentPartitioners(d); + } // Perform the shift operation. Map map= (useDefaultPrefixes ? fDefaultPrefixChars : fIndentChars); for (int i= 0, j= 0; i < regions.length; i++, j += 2) { String[] prefixes= (String[]) selectContentTypePlugin(regions[i].getType(), map); if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0) { - if (right) + if (right) { shiftRight(lines[j], lines[j + 1], prefixes[0]); - else + } else { shiftLeft(lines[j], lines[j + 1], prefixes, ignoreWhitespace); + } } } } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.shift_1")); //$NON-NLS-1$ + } } finally { - if (partitioners != null) + if (partitioners != null) { TextUtilities.addDocumentPartitioners(d, partitioners); + } if (d instanceof IDocumentExtension4 extension) { extension.stopRewriteSession(rewriteSession); @@ -4350,8 +4513,9 @@ protected void shift(boolean useDefaultPrefixes, boolean right, boolean ignoreWh setRedraw(true); } - if (fUndoManager != null) + if (fUndoManager != null) { fUndoManager.endCompoundChange(); + } } } @@ -4374,8 +4538,9 @@ private void shiftRight(int startLine, int endLine, String prefix) { } } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println("TextViewer.shiftRight: BadLocationException"); //$NON-NLS-1$ + } } } @@ -4422,10 +4587,12 @@ private void shiftLeft(int startLine, int endLine, String[] prefixes, boolean ig if (ignoreWhitespace) { String s= d.get(line.getOffset(), matchOffset); s= s.trim(); - if (s.isEmpty()) + if (s.isEmpty()) { index= line.getOffset() + matchOffset; - } else if (matchOffset == 0) + } + } else if (matchOffset == 0) { index= line.getOffset(); + } } if (index > -1) { @@ -4450,8 +4617,9 @@ private void shiftLeft(int startLine, int endLine, String[] prefixes, boolean ig } } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println("TextViewer.shiftLeft: BadLocationException"); //$NON-NLS-1$ + } } } @@ -4568,8 +4736,9 @@ protected int findAndSelect(int startPosition, String findString, boolean forwar * @return the model offset of the first match */ protected int findAndSelect(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) { - if (fTextWidget == null) + if (fTextWidget == null) { return -1; + } try { @@ -4585,8 +4754,9 @@ protected int findAndSelect(int startPosition, String findString, boolean forwar char endChar= adapter.charAt(widgetPos+length-1); boolean borderHasLineDelimiter= startChar == '\n' || startChar == '\r' || endChar == '\n' || endChar == '\r'; boolean redraws= redraws(); - if (borderHasLineDelimiter && redraws) + if (borderHasLineDelimiter && redraws) { setRedraw(false); + } if (redraws()) { fTextWidget.setSelectionRange(widgetPos, length); @@ -4594,16 +4764,18 @@ protected int findAndSelect(int startPosition, String findString, boolean forwar selectionChanged(widgetPos, length); } else { setSelectedRange(widgetOffset2ModelOffset(widgetPos), length); - if (redraws) + if (redraws) { setRedraw(true); + } } return widgetOffset2ModelOffset(widgetPos); } } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.findAndSelect")); //$NON-NLS-1$ + } } return -1; @@ -4624,8 +4796,9 @@ protected int findAndSelect(int startPosition, String findString, boolean forwar * @since 3.0 */ protected int findAndSelectInRange(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, int rangeOffset, int rangeLength, boolean regExSearch) { - if (fTextWidget == null) + if (fTextWidget == null) { return -1; + } try { @@ -4639,8 +4812,9 @@ protected int findAndSelectInRange(int startPosition, String findString, boolean } int widgetOffset= modelOffset2WidgetOffset(modelOffset); - if (widgetOffset == -1) + if (widgetOffset == -1) { return -1; + } FindReplaceDocumentAdapter adapter= getFindReplaceDocumentAdapter(); IRegion matchRegion= adapter.find(widgetOffset, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); @@ -4652,8 +4826,9 @@ protected int findAndSelectInRange(int startPosition, String findString, boolean } int modelPos= widgetPos == -1 ? -1 : widgetOffset2ModelOffset(widgetPos); - if (widgetPos != -1 && (modelPos < rangeOffset || modelPos + length > rangeOffset + rangeLength)) + if (widgetPos != -1 && (modelPos < rangeOffset || modelPos + length > rangeOffset + rangeLength)) { widgetPos= -1; + } if (widgetPos > -1) { @@ -4662,8 +4837,9 @@ protected int findAndSelectInRange(int startPosition, String findString, boolean char endChar= adapter.charAt(widgetPos+length-1); boolean borderHasLineDelimiter= startChar == '\n' || startChar == '\r' || endChar == '\n' || endChar == '\r'; boolean redraws= redraws(); - if (borderHasLineDelimiter && redraws) + if (borderHasLineDelimiter && redraws) { setRedraw(false); + } if (redraws()) { fTextWidget.setSelectionRange(widgetPos, length); @@ -4671,8 +4847,9 @@ protected int findAndSelectInRange(int startPosition, String findString, boolean selectionChanged(widgetPos, length); } else { setSelectedRange(modelPos, length); - if (redraws) + if (redraws) { setRedraw(true); + } } return modelPos; @@ -4680,8 +4857,9 @@ protected int findAndSelectInRange(int startPosition, String findString, boolean } catch (BadLocationException x) { - if (TRACE_ERRORS) + if (TRACE_ERRORS) { System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.findAndSelect")); //$NON-NLS-1$ + } } return -1; @@ -4691,8 +4869,9 @@ protected int findAndSelectInRange(int startPosition, String findString, boolean @Override public void setTextColor(Color color) { - if (color != null) + if (color != null) { setTextColor(color, 0, getDocument().getLength(), true); + } } @Override @@ -4706,13 +4885,15 @@ public void setTextColor(Color color, int start, int length, boolean controlRedr s= modelStyleRange2WidgetStyleRange(s); if (s != null) { - if (controlRedraw) + if (controlRedraw) { fTextWidget.setRedraw(false); + } try { fTextWidget.setStyleRange(s); } finally { - if (controlRedraw) + if (controlRedraw) { fTextWidget.setRedraw(true); + } } } } @@ -4729,33 +4910,38 @@ private void addPresentation(TextPresentation presentation) { if (range != null) { range= modelStyleRange2WidgetStyleRange(range); - if (range != null) + if (range != null) { fTextWidget.setStyleRange(range); + } ArrayList ranges= new ArrayList<>(presentation.getDenumerableRanges()); Iterator e= presentation.getNonDefaultStyleRangeIterator(); while (e.hasNext()) { range= e.next(); range= modelStyleRange2WidgetStyleRange(range); - if (range != null) + if (range != null) { ranges.add(range); + } } - if (!ranges.isEmpty()) + if (!ranges.isEmpty()) { fTextWidget.replaceStyleRanges(0, 0, ranges.toArray(new StyleRange[ranges.size()])); + } } else { IRegion region= modelRange2WidgetRange(presentation.getCoverage()); - if (region == null) + if (region == null) { return; + } List list= new ArrayList<>(presentation.getDenumerableRanges()); Iterator e= presentation.getAllStyleRangeIterator(); while (e.hasNext()) { range= e.next(); range= modelStyleRange2WidgetStyleRange(range); - if (range != null) + if (range != null) { list.add(range); + } } if (!list.isEmpty()) { @@ -4779,8 +4965,9 @@ private void applyTextPresentation(TextPresentation presentation) { while (e.hasNext()) { StyleRange range= e.next(); range= modelStyleRange2WidgetStyleRange(range); - if (range != null) + if (range != null) { list.add(range); + } } if (!list.isEmpty()) { @@ -4810,11 +4997,13 @@ protected IRegion _internalGetVisibleRegion() { @Override public void changeTextPresentation(TextPresentation presentation, boolean controlRedraw) { - if (presentation == null || !redraws()) + if (presentation == null || !redraws()) { return; + } - if (fTextWidget == null) + if (fTextWidget == null) { return; + } /* @@ -4829,25 +5018,30 @@ public void changeTextPresentation(TextPresentation presentation, boolean contro } } - if (presentation.isEmpty()) + if (presentation.isEmpty()) { return; + } - if (controlRedraw) + if (controlRedraw) { fTextWidget.setRedraw(false); + } - if (fReplaceTextPresentation) + if (fReplaceTextPresentation) { applyTextPresentation(presentation); - else + } else { addPresentation(presentation); + } - if (controlRedraw) + if (controlRedraw) { fTextWidget.setRedraw(true); + } } @Override public IFindReplaceTarget getFindReplaceTarget() { - if (fFindReplaceTarget == null) + if (fFindReplaceTarget == null) { fFindReplaceTarget= new FindReplaceTarget(); + } return fFindReplaceTarget; } @@ -4858,8 +5052,9 @@ public IFindReplaceTarget getFindReplaceTarget() { * @since 3.0 */ protected FindReplaceDocumentAdapter getFindReplaceDocumentAdapter() { - if (fFindReplaceDocumentAdapter == null) + if (fFindReplaceDocumentAdapter == null) { fFindReplaceDocumentAdapter= new FindReplaceDocumentAdapter(getVisibleDocument()); + } return fFindReplaceDocumentAdapter; } @@ -4898,8 +5093,9 @@ public void setMark(int offset) { if (fMarkPosition != null && !fMarkPosition.isDeleted()) { IDocument document= getDocument(); - if (document != null) + if (document != null) { document.removePosition(fMarkPosition); + } } fMarkPosition= null; @@ -4915,8 +5111,9 @@ public void setMark(int offset) { return; } - if (fMarkPosition != null) + if (fMarkPosition != null) { document.removePosition(fMarkPosition); + } fMarkPosition= null; @@ -4942,8 +5139,9 @@ protected void inputChanged(Object newInput, Object oldInput) { IDocument oldDocument= (IDocument) oldInput; if (oldDocument != null) { - if (fMarkPosition != null && !fMarkPosition.isDeleted()) + if (fMarkPosition != null && !fMarkPosition.isDeleted()) { oldDocument.removePosition(fMarkPosition); + } try { oldDocument.removePositionUpdater(fMarkPositionUpdater); @@ -5017,8 +5215,9 @@ protected void enabledRedrawing(int topIndex) { fViewerState= null; } - if (fTextWidget != null && !fTextWidget.isDisposed()) + if (fTextWidget != null && !fTextWidget.isDisposed()) { fTextWidget.setRedraw(true); + } fireRedrawChanged(); } @@ -5028,15 +5227,17 @@ protected void enabledRedrawing(int topIndex) { * @since 2.0 */ protected void disableRedrawing() { - if (fViewerState == null) + if (fViewerState == null) { fViewerState= new ViewerState(); + } if (fDocumentAdapter instanceof IDocumentAdapterExtension extension) { extension.stopForwardingDocumentChanges(); } - if (fTextWidget != null && !fTextWidget.isDisposed()) + if (fTextWidget != null && !fTextWidget.isDisposed()) { fTextWidget.setRedraw(false); + } fireRedrawChanged(); } @@ -5062,16 +5263,18 @@ protected final void setRedraw(boolean redraw, int topIndex) { if (!redraw) { ++ fRedrawCounter; - if (fRedrawCounter == 1) + if (fRedrawCounter == 1) { disableRedrawing(); + } } else { -- fRedrawCounter; if (fRedrawCounter == 0) { - if (topIndex == -1) + if (topIndex == -1) { enabledRedrawing(); - else + } else { enabledRedrawing(topIndex); + } } } } @@ -5117,22 +5320,25 @@ protected final void stopSequentialRewriteMode() { @Override public IRewriteTarget getRewriteTarget() { - if (fRewriteTarget == null) + if (fRewriteTarget == null) { fRewriteTarget= new RewriteTarget(); + } return fRewriteTarget; } @Override public ITextHover getCurrentTextHover() { - if (fTextHoverManager == null) + if (fTextHoverManager == null) { return null; + } return fTextHoverManager.getCurrentTextHover(); } @Override public Point getHoverEventLocation() { - if (fTextHoverManager == null) + if (fTextHoverManager == null) { return null; + } return fTextHoverManager.getHoverEventLocation(); } @@ -5143,8 +5349,9 @@ public Point getHoverEventLocation() { * @since 2.1 */ protected PaintManager getPaintManager() { - if (fPaintManager == null) + if (fPaintManager == null) { fPaintManager= new PaintManager(this); + } return fPaintManager; } @@ -5182,8 +5389,9 @@ public void removePainter(IPainter painter) { * @since 2.1 */ public int modelLine2WidgetLine(int modelLine) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return modelLine; + } try { return fInformationMapping.toImageLine(modelLine); @@ -5201,8 +5409,9 @@ public int modelLine2WidgetLine(int modelLine) { * @since 2.1 */ public int modelOffset2WidgetOffset(int modelOffset) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return modelOffset; + } try { return fInformationMapping.toImageOffset(modelOffset); @@ -5220,16 +5429,18 @@ public int modelOffset2WidgetOffset(int modelOffset) { * @since 2.1 */ public IRegion modelRange2WidgetRange(IRegion modelRange) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return modelRange; + } try { if (modelRange.getLength() < 0) { Region reversed= new Region(modelRange.getOffset() + modelRange.getLength(), -modelRange.getLength()); IRegion result= fInformationMapping.toImageRegion(reversed); - if (result != null) + if (result != null) { return new Region(result.getOffset() + result.getLength(), -result.getLength()); + } } return fInformationMapping.toImageRegion(modelRange); @@ -5250,15 +5461,17 @@ public IRegion modelRange2WidgetRange(IRegion modelRange) { * @since 3.1 */ protected IRegion modelRange2ClosestWidgetRange(IRegion modelRange) { - if (!(fInformationMapping instanceof IDocumentInformationMappingExtension2)) + if (!(fInformationMapping instanceof IDocumentInformationMappingExtension2)) { return modelRange2WidgetRange(modelRange); + } try { if (modelRange.getLength() < 0) { Region reversed= new Region(modelRange.getOffset() + modelRange.getLength(), -modelRange.getLength()); IRegion result= ((IDocumentInformationMappingExtension2) fInformationMapping).toClosestImageRegion(reversed); - if (result != null) + if (result != null) { return new Region(result.getOffset() + result.getLength(), -result.getLength()); + } } return ((IDocumentInformationMappingExtension2) fInformationMapping).toClosestImageRegion(modelRange); @@ -5287,8 +5500,9 @@ public int widgetlLine2ModelLine(int widgetLine) { * @since 3.0 */ public int widgetLine2ModelLine(int widgetLine) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return widgetLine; + } try { return fInformationMapping.toOriginLine(widgetLine); @@ -5306,8 +5520,9 @@ public int widgetLine2ModelLine(int widgetLine) { * @since 2.1 */ public int widgetOffset2ModelOffset(int widgetOffset) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return widgetOffset; + } try { return fInformationMapping.toOriginOffset(widgetOffset); @@ -5329,8 +5544,9 @@ public int widgetOffset2ModelOffset(int widgetOffset) { * @since 2.1 */ public IRegion widgetRange2ModelRange(IRegion widgetRange) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return widgetRange; + } try { @@ -5346,8 +5562,9 @@ public IRegion widgetRange2ModelRange(IRegion widgetRange) { int modelOffset= widgetOffset2ModelOffset(widgetRange.getOffset()); if (modelOffset > -1) { int modelEndOffset= widgetOffset2ModelOffset(widgetRange.getOffset() + widgetRange.getLength()); - if (modelEndOffset > -1) + if (modelEndOffset > -1) { return new Region(modelOffset, modelEndOffset - modelOffset); + } } } @@ -5363,8 +5580,9 @@ public IRegion widgetRange2ModelRange(IRegion widgetRange) { public IRegion getModelCoverage() { if (fInformationMapping == null) { IDocument document= getDocument(); - if (document == null) + if (document == null) { return null; + } return new Region(0, document.getLength()); } @@ -5380,8 +5598,9 @@ public IRegion getModelCoverage() { * @since 2.1 */ protected int getClosestWidgetLineForModelLine(int modelLine) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return modelLine; + } try { return fInformationMapping.toClosestImageLine(modelLine); @@ -5432,10 +5651,11 @@ protected IRegion modelRange2WidgetRange(Position modelPosition) { protected IRegion event2ModelRange(VerifyEvent event) { Region region= null; - if (event.start <= event.end) + if (event.start <= event.end) { region= new Region(event.start, event.end - event.start); - else + } else { region= new Region(event.end, event.start - event.end); + } return widgetRange2ModelRange(region); } @@ -5463,14 +5683,16 @@ protected Point widgetSelection2ModelSelection(Point widgetSelection) { * @since 2.1 */ protected Point modelSelection2WidgetSelection(Point modelSelection) { - if (fInformationMapping == null) + if (fInformationMapping == null) { return modelSelection; + } try { IRegion region= new Region(modelSelection.x, modelSelection.y); region= fInformationMapping.toImageRegion(region); - if (region != null) + if (region != null) { return new Point(region.getOffset(), region.getLength()); + } } catch (BadLocationException x) { } @@ -5531,11 +5753,13 @@ public void addTextPresentationListener(ITextPresentationListener listener) { Assert.isNotNull(listener); - if (fTextPresentationListeners == null) + if (fTextPresentationListeners == null) { fTextPresentationListeners= new ArrayList<>(); + } - if (!fTextPresentationListeners.contains(listener)) + if (!fTextPresentationListeners.contains(listener)) { fTextPresentationListeners.add(listener); + } } @Override @@ -5545,8 +5769,9 @@ public void removeTextPresentationListener(ITextPresentationListener listener) { if (fTextPresentationListeners != null) { fTextPresentationListeners.remove(listener); - if (fTextPresentationListeners.isEmpty()) + if (fTextPresentationListeners.isEmpty()) { fTextPresentationListeners= null; + } } } @@ -5582,8 +5807,9 @@ public IEditingSupport[] getRegisteredSupports() { public void setHyperlinkDetectors(IHyperlinkDetector[] hyperlinkDetectors, int eventStateMask) { if (fHyperlinkDetectors != null) { for (IHyperlinkDetector fHyperlinkDetector : fHyperlinkDetectors) { - if (fHyperlinkDetector instanceof IHyperlinkDetectorExtension) + if (fHyperlinkDetector instanceof IHyperlinkDetectorExtension) { ((IHyperlinkDetectorExtension)fHyperlinkDetector).dispose(); + } } } @@ -5597,8 +5823,9 @@ public void setHyperlinkDetectors(IHyperlinkDetector[] hyperlinkDetectors, int e } ensureHyperlinkManagerInstalled(); } else { - if (fHyperlinkManager != null) + if (fHyperlinkManager != null) { fHyperlinkManager.uninstall(); + } fHyperlinkManager= null; } } @@ -5615,8 +5842,9 @@ public void setHyperlinkDetectors(IHyperlinkDetector[] hyperlinkDetectors, int e * @since 3.1 */ public void setHyperlinkPresenter(IHyperlinkPresenter hyperlinkPresenter) throws IllegalStateException { - if (fHyperlinkManager != null) + if (fHyperlinkManager != null) { throw new IllegalStateException(); + } fHyperlinkPresenter= hyperlinkPresenter; ensureHyperlinkManagerInstalled(); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerHoverManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerHoverManager.java index 3f3136e121d..ad1783e6c22 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerHoverManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerHoverManager.java @@ -49,13 +49,13 @@ class TextViewerHoverManager extends AbstractHoverInformationControlManager impl /** The text viewer */ - private TextViewer fTextViewer; + private final TextViewer fTextViewer; /** The hover information computation thread */ private Thread fThread; /** The stopper of the computation thread */ - private ITextListener fStopper; + private final ITextListener fStopper; /** Internal monitor */ - private Object fMutex= new Object(); + private final Object fMutex= new Object(); /** The currently shown text hover. */ private volatile ITextHover fTextHover; /** @@ -151,10 +151,11 @@ public void run() { if (fThread != null) { Object information; try { - if (hover instanceof ITextHoverExtension2) + if (hover instanceof ITextHoverExtension2) { information= ((ITextHoverExtension2)hover).getHoverInfo2(fTextViewer, region); - else + } else { information= hover.getHoverInfo(fTextViewer, region); + } } catch (ArrayIndexOutOfBoundsException x) { /* * This code runs in a separate thread which can @@ -164,14 +165,16 @@ public void run() { information= null; } - if (hover instanceof ITextHoverExtension) + if (hover instanceof ITextHoverExtension) { setCustomInformationControlCreator(((ITextHoverExtension) hover).getHoverControlCreator()); - else + } else { setCustomInformationControlCreator(null); + } setInformation(information, area); - if (information != null) + if (information != null) { fTextHover= hover; + } } else { setInformation(null, null); } @@ -184,12 +187,14 @@ public void run() { log.log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, "Unexpected runtime error while computing a text hover", ex)); //$NON-NLS-1$ } finally { synchronized (fMutex) { - if (fTextViewer != null) + if (fTextViewer != null) { fTextViewer.removeTextListener(fStopper); + } fThread= null; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=44756 - if (!hasFinished) + if (!hasFinished) { setInformation(null, null); + } } } } @@ -271,11 +276,12 @@ private int computeOffsetAtLocation(int x, int y) { @Override protected void showInformationControl(Rectangle subjectArea) { - if (fTextViewer != null && fTextViewer.requestWidgetToken(this, WIDGET_PRIORITY)) + if (fTextViewer != null && fTextViewer.requestWidgetToken(this, WIDGET_PRIORITY)) { super.showInformationControl(subjectArea); - else - if (DEBUG) + } else + if (DEBUG) { System.out.println("TextViewerHoverManager#showInformationControl(..) did not get widget token"); //$NON-NLS-1$ + } } @Override @@ -284,15 +290,17 @@ protected void hideInformationControl() { fTextHover= null; super.hideInformationControl(); } finally { - if (fTextViewer != null) + if (fTextViewer != null) { fTextViewer.releaseWidgetToken(this); + } } } @Override void replaceInformationControl(boolean takeFocus) { - if (fTextViewer != null) + if (fTextViewer != null) { fTextViewer.releaseWidgetToken(this); + } super.replaceInformationControl(takeFocus); } @@ -301,8 +309,9 @@ protected void handleInformationControlDisposed() { try { super.handleInformationControlDisposed(); } finally { - if (fTextViewer != null) + if (fTextViewer != null) { fTextViewer.releaseWidgetToken(this); + } } } @@ -325,13 +334,15 @@ public boolean requestWidgetToken(IWidgetTokenOwner owner, int priority) { @Override public boolean setFocus(IWidgetTokenOwner owner) { - if (! hasInformationControlReplacer()) + if (! hasInformationControlReplacer()) { return false; + } IInformationControl iControl= getCurrentInformationControl(); if (canReplace(iControl)) { - if (cancelReplacingDelay()) + if (cancelReplacingDelay()) { replaceInformationControl(true); + } return true; } @@ -359,8 +370,9 @@ public void dispose() { fViewportListener= null; StyledText st= fTextViewer.getTextWidget(); - if (st != null && !st.isDisposed()) + if (st != null && !st.isDisposed()) { st.removeMouseMoveListener(fMouseMoveListener); + } fMouseMoveListener= null; } super.dispose(); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerUndoManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerUndoManager.java index 722b95c2dfc..d0c99509293 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerUndoManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewerUndoManager.java @@ -78,9 +78,11 @@ public void mouseDoubleClick(MouseEvent e) { */ @Override public void mouseDown(MouseEvent e) { - if (e.button == 1) - if (isConnected()) + if (e.button == 1) { + if (isConnected()) { fDocumentUndoManager.commit(); + } + } } /* @@ -141,42 +143,51 @@ private class DocumentUndoListener implements IDocumentUndoListener { @Override public void documentUndoNotification(DocumentUndoEvent event ){ - if (!isConnected()) return; + if (!isConnected()) { + return; + } int eventType= event.getEventType(); if (((eventType & DocumentUndoEvent.ABOUT_TO_UNDO) != 0) || ((eventType & DocumentUndoEvent.ABOUT_TO_REDO) != 0)) { if (event.isCompound()) { ITextViewerExtension extension= null; - if (fTextViewer instanceof ITextViewerExtension) + if (fTextViewer instanceof ITextViewerExtension) { extension= (ITextViewerExtension) fTextViewer; + } - if (extension != null) + if (extension != null) { extension.setRedraw(false); + } } fTextViewer.getTextWidget().getDisplay().syncExec(() -> { - if (fTextViewer instanceof TextViewer) + if (fTextViewer instanceof TextViewer) { ((TextViewer) fTextViewer).ignoreAutoEditStrategies(true); + } }); } else if (((eventType & DocumentUndoEvent.UNDONE) != 0) || ((eventType & DocumentUndoEvent.REDONE) != 0)) { fTextViewer.getTextWidget().getDisplay().syncExec(() -> { - if (fTextViewer instanceof TextViewer) + if (fTextViewer instanceof TextViewer) { ((TextViewer) fTextViewer).ignoreAutoEditStrategies(false); + } }); if (event.isCompound()) { ITextViewerExtension extension= null; - if (fTextViewer instanceof ITextViewerExtension) + if (fTextViewer instanceof ITextViewerExtension) { extension= (ITextViewerExtension) fTextViewer; + } - if (extension != null) + if (extension != null) { extension.setRedraw(true); + } } // Reveal the change if this manager's viewer has the focus. if (fTextViewer != null) { StyledText widget= fTextViewer.getTextWidget(); - if (widget != null && !widget.isDisposed() && (widget.isFocusControl()) && (widget.getSelectionRanges().length <= 2))// || fTextViewer.getTextWidget() == control)) + if (widget != null && !widget.isDisposed() && (widget.isFocusControl()) && (widget.getSelectionRanges().length <= 2)) { // || fTextViewer.getTextWidget() == control)) selectAndReveal(event.getOffset(), event.getText() == null ? 0 : event.getText().length()); + } } } } @@ -285,18 +296,20 @@ private void openErrorDialog(final String title, final Exception ex) { Shell shell= null; if (isConnected()) { StyledText st= fTextViewer.getTextWidget(); - if (st != null && !st.isDisposed()) + if (st != null && !st.isDisposed()) { shell= st.getShell(); + } } - if (Display.getCurrent() != null) + if (Display.getCurrent() != null) { MessageDialog.openError(shell, title, ex.getLocalizedMessage()); - else { + } else { Display display; final Shell finalShell= shell; - if (finalShell != null) + if (finalShell != null) { display= finalShell.getDisplay(); - else + } else { display= Display.getDefault(); + } display.syncExec(() -> MessageDialog.openError(finalShell, title, ex.getLocalizedMessage())); } } @@ -330,22 +343,25 @@ public void disconnect() { @Override public void reset() { - if (isConnected()) + if (isConnected()) { fDocumentUndoManager.reset(); + } } @Override public boolean redoable() { - if (isConnected()) + if (isConnected()) { return fDocumentUndoManager.redoable(); + } return false; } @Override public boolean undoable() { - if (isConnected()) + if (isConnected()) { return fDocumentUndoManager.undoable(); + } return false; } @@ -380,8 +396,9 @@ public void undo() { private void selectAndReveal(int offset, int length) { if (fTextViewer instanceof ITextViewerExtension5 extension) { extension.exposeModelRange(new Region(offset, length)); - } else if (!fTextViewer.overlapsWithVisibleRegion(offset, length)) + } else if (!fTextViewer.overlapsWithVisibleRegion(offset, length)) { fTextViewer.resetVisibleRegion(); + } fTextViewer.setSelectedRange(offset, length); fTextViewer.revealRange(offset, length); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMiningProvider.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMiningProvider.java index 87cd90d9239..c6a2715586e 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMiningProvider.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/AbstractCodeMiningProvider.java @@ -41,8 +41,9 @@ public abstract class AbstractCodeMiningProvider implements ICodeMiningProvider */ public final void setContext(IAdaptable context) throws IllegalStateException, IllegalArgumentException { Assert.isLegal(context != null); - if (this.context != null) + if (this.context != null) { throw new IllegalStateException(); + } this.context= context; } @@ -61,8 +62,9 @@ public void dispose() { */ protected final T getAdapter(Class adapterClass) { Assert.isLegal(adapterClass != null); - if (context != null) + if (context != null) { return context.getAdapter(adapterClass); + } return null; } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/CodeMiningStrategy.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/CodeMiningStrategy.java index be2e49bdc98..3033463667e 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/CodeMiningStrategy.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/codemining/CodeMiningStrategy.java @@ -34,7 +34,7 @@ class CodeMiningStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension { - private Supplier fViewerSupplier; + private final Supplier fViewerSupplier; public CodeMiningStrategy(Supplier viewerSupplier) { fViewerSupplier= viewerSupplier; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AdditionalInfoController.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AdditionalInfoController.java index 4ffe8063a06..4ca2368b215 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AdditionalInfoController.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AdditionalInfoController.java @@ -287,16 +287,19 @@ public synchronized final void reset(ICompletionProposal p) { long oldWakeup= fNextWakeup; Task task= taskOnReset(p); schedule(task, System.currentTimeMillis()); - if (fNextWakeup < oldWakeup) + if (fNextWakeup < oldWakeup) { notifyAll(); + } } } private Task taskOnReset(ICompletionProposal p) { - if (p == null) + if (p == null) { return IDLE; - if (isExt5(p)) + } + if (isExt5(p)) { return FIRST_WAIT; + } return LEGACY_WAIT; } @@ -325,10 +328,11 @@ private Task currentTask() { private void schedule(Task task, long current) { fTask= task; long nextWakeup= current + task.delay(); - if (nextWakeup <= current) + if (nextWakeup <= current) { fNextWakeup= Long.MAX_VALUE; - else + } else { fNextWakeup= nextWakeup; + } } private boolean isExt5(ICompletionProposal p) { @@ -408,7 +412,7 @@ public IInformationControl doCreateInformationControl(Shell shell) { /** The proposal table. */ private volatile Table fProposalTable; /** The table selection listener */ - private SelectionListener fSelectionListener= new TableSelectionListener(); + private final SelectionListener fSelectionListener= new TableSelectionListener(); /** The delay after which additional information is displayed */ private final int fDelay; /** @@ -473,8 +477,9 @@ public void install(Control control) { @Override protected void showInformation(ICompletionProposal proposal, Object info) { InformationControlReplacer replacer= getInternalAccessor().getInformationControlReplacer(); - if (replacer != null) + if (replacer != null) { replacer.hideInformationControl(); + } AdditionalInfoController.this.showInformation(proposal, info); } }; @@ -601,10 +606,12 @@ protected Point computeSizeConstraints(Control subjectControl, IInformationContr size.y -= shellTrim.height; } - if (sizeConstraint.x < size.x) + if (sizeConstraint.x < size.x) { sizeConstraint.x= size.x; - if (sizeConstraint.y < size.y) + } + if (sizeConstraint.y < size.y) { sizeConstraint.y= size.y; + } return sizeConstraint; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AsyncCompletionProposalPopup.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AsyncCompletionProposalPopup.java index 86b79ea32ce..fa2cb337629 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AsyncCompletionProposalPopup.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/AsyncCompletionProposalPopup.java @@ -70,9 +70,9 @@ class AsyncCompletionProposalPopup extends CompletionProposalPopup { */ private CompletableFuture fAggregatedPopulateFuture; - private Collection> toCancelFutures= new LinkedList<>(); + private final Collection> toCancelFutures= new LinkedList<>(); - private PopupVisibleTimer fPopupVisibleTimer= new PopupVisibleTimer(); + private final PopupVisibleTimer fPopupVisibleTimer= new PopupVisibleTimer(); private static final class ComputingProposal implements ICompletionProposal, ICompletionProposalExtension { @@ -113,10 +113,10 @@ public String getDisplayString() { @Override public String getAdditionalProposalInfo() { - return NLS.bind(JFaceTextMessages.getString("AsyncCompletionProposalPopup.computingDetails"), new Object[] { //$NON-NLS-1$; - Integer.valueOf(fSize), - Integer.valueOf(fSize - fRemaining), - Integer.valueOf(fRemaining) }); + return NLS.bind(JFaceTextMessages.getString("AsyncCompletionProposalPopup.computingDetails"), //$NON-NLS-1$; + Integer.valueOf(fSize), + Integer.valueOf(fSize - fRemaining), + Integer.valueOf(fRemaining)); } @Override @@ -159,8 +159,9 @@ public AsyncCompletionProposalPopup(ContentAssistant contentAssistant, ITextView */ @Override public String showProposals(boolean autoActivated) { - if (fKeyListener == null) + if (fKeyListener == null) { fKeyListener= new ProposalSelectionListener(); + } final Control control= fContentAssistSubjectControlAdapter.getControl(); @@ -304,11 +305,13 @@ public String incrementalComplete() { } final Control control= fContentAssistSubjectControlAdapter.getControl(); - if (fKeyListener == null) + if (fKeyListener == null) { fKeyListener= new ProposalSelectionListener(); + } - if (!isValid(fProposalShell) && !control.isDisposed()) + if (!isValid(fProposalShell) && !control.isDisposed()) { fContentAssistSubjectControlAdapter.addKeyListener(fKeyListener); + } fInvocationOffset= fContentAssistSubjectControlAdapter.getSelectedRange().x; fFilterOffset= fInvocationOffset; @@ -444,9 +447,9 @@ private String getTokenContentType(int invocationOffset) throws BadLocationExcep private class PopupVisibleTimer implements Runnable { private Thread fThread; - private Object fMutex= new Object(); + private final Object fMutex= new Object(); - private int fAutoActivationDelay= 500; + private final int fAutoActivationDelay= 500; protected void start() { fThread= new Thread(this, JFaceTextMessages.getString("ContentAssistant.assist_delay_timer_name")); //$NON-NLS-1$ @@ -458,8 +461,9 @@ public void run() { try { while (true) { synchronized (fMutex) { - if (fAutoActivationDelay != 0) + if (fAutoActivationDelay != 0) { fMutex.wait(fAutoActivationDelay); + } } Optional display= Optional.ofNullable(fContentAssistSubjectControlAdapter.getControl()).map(Control::getDisplay); display.ifPresent(d -> d.asyncExec(() -> displayProposals(true))); @@ -472,8 +476,9 @@ public void run() { protected void stop() { Thread threadToStop= fThread; - if (threadToStop != null && threadToStop.isAlive()) + if (threadToStop != null && threadToStop.isAlive()) { threadToStop.interrupt(); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/BoldStylerProvider.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/BoldStylerProvider.java index 294b6f18ef3..2c980ac1cfc 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/BoldStylerProvider.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/BoldStylerProvider.java @@ -28,7 +28,7 @@ */ public final class BoldStylerProvider { - private Font fFont; + private final Font fFont; private Font fBoldFont; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposal.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposal.java index e9493849bc2..e00b37f06e5 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposal.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposal.java @@ -28,21 +28,21 @@ public final class CompletionProposal implements ICompletionProposal { /** The string to be displayed in the completion proposal popup. */ - private String fDisplayString; + private final String fDisplayString; /** The replacement string. */ - private String fReplacementString; + private final String fReplacementString; /** The replacement offset. */ - private int fReplacementOffset; + private final int fReplacementOffset; /** The replacement length. */ - private int fReplacementLength; + private final int fReplacementLength; /** The cursor position after this proposal has been applied. */ - private int fCursorPosition; + private final int fCursorPosition; /** The image to be displayed in the completion proposal popup. */ - private Image fImage; + private final Image fImage; /** The context information of this proposal. */ - private IContextInformation fContextInformation; + private final IContextInformation fContextInformation; /** The additional info of this proposal. */ - private String fAdditionalProposalInfo; + private final String fAdditionalProposalInfo; /** * Creates a new completion proposal based on the provided information. The replacement string is @@ -111,8 +111,9 @@ public Image getImage() { @Override public String getDisplayString() { - if (fDisplayString != null) + if (fDisplayString != null) { return fDisplayString; + } return fReplacementString; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java index d87fe7aaee1..3333fe01085 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java @@ -151,13 +151,15 @@ public Object execute(ExecutionEvent event) throws ExecutionException { switch (fOperationCode) { case SELECT_NEXT: selectionIndex+= 1; - if (selectionIndex > itemCount - 1) + if (selectionIndex > itemCount - 1) { selectionIndex= 0; + } break; case SELECT_PREVIOUS: selectionIndex-= 1; - if (selectionIndex < 0) + if (selectionIndex < 0) { selectionIndex= itemCount - 1; + } break; default: break; @@ -230,27 +232,31 @@ public int getContextInformationPosition() { final class ProposalSelectionListener implements KeyListener { @Override public void keyPressed(KeyEvent e) { - if (!isValid(fProposalShell)) + if (!isValid(fProposalShell)) { return; + } if (e.character == 0 && e.keyCode == SWT.CTRL) { // http://dev.eclipse.org/bugs/show_bug.cgi?id=34754 int index= fProposalTable.getSelectionIndex(); - if (index >= 0) + if (index >= 0) { selectProposal(index, true); + } } } @Override public void keyReleased(KeyEvent e) { - if (!isValid(fProposalShell)) + if (!isValid(fProposalShell)) { return; + } if (e.character == 0 && e.keyCode == SWT.CTRL) { // http://dev.eclipse.org/bugs/show_bug.cgi?id=34754 int index= fProposalTable.getSelectionIndex(); - if (index >= 0) + if (index >= 0) { selectProposal(index, false); + } } } } @@ -264,16 +270,19 @@ private CommandKeyListener(KeySequence keySequence) { @Override public void keyPressed(KeyEvent e) { - if (!isValid(fProposalShell)) + if (!isValid(fProposalShell)) { return; + } int accelerator= SWTKeySupport.convertEventToUnmodifiedAccelerator(e); KeySequence sequence= KeySequence.getInstance(SWTKeySupport.convertAcceleratorToKeyStroke(accelerator)); - if (sequence.equals(fCommandSequence)) - if (fContentAssistant.isPrefixCompletionEnabled()) + if (sequence.equals(fCommandSequence)) { + if (fContentAssistant.isPrefixCompletionEnabled()) { incrementalComplete(); - else + } else { showProposals(false); + } + } } } @@ -352,11 +361,13 @@ public void keyPressed(KeyEvent e) { private final Runnable fFilterRunnable= new Runnable() { @Override public void run() { - if (!fIsFilterPending.compareAndSet(true, false)) + if (!fIsFilterPending.compareAndSet(true, false)) { return; + } - if (!isValid(fContentAssistSubjectControlAdapter.getControl())) + if (!isValid(fContentAssistSubjectControlAdapter.getControl())) { return; + } int offset= fContentAssistSubjectControlAdapter.getSelectedRange().x; List proposals= null; @@ -371,9 +382,9 @@ public void run() { } fFilterOffset= offset; - if (proposals != null && !proposals.isEmpty()) + if (proposals != null && !proposals.isEmpty()) { setProposals(proposals, fIsFilteredSubset); - else { + } else { hide(); if (fContentAssistant.isAutoActivation() && offset > 0 && event != null) { try { @@ -489,8 +500,9 @@ public CompletionProposalPopup(ContentAssistant contentAssistant, IContentAssist */ public String showProposals(final boolean autoActivated) { - if (fKeyListener == null) + if (fKeyListener == null) { fKeyListener= new ProposalSelectionListener(); + } final Control control= fContentAssistSubjectControlAdapter.getControl(); @@ -507,8 +519,9 @@ public String showProposals(final boolean autoActivated) { fComputedProposals= computeProposals(fInvocationOffset); int count= (fComputedProposals == null ? 0 : fComputedProposals.size()); - if (count == 0 && hideWhenNoProposals(autoActivated)) + if (count == 0 && hideWhenNoProposals(autoActivated)) { return; + } if (count == 1 && !autoActivated && canAutoInsert(fComputedProposals.get(0))) { insertProposal(fComputedProposals.get(0), (char) 0, 0, fInvocationOffset); @@ -539,8 +552,9 @@ boolean hideWhenNoProposals(boolean autoActivated) { if (autoActivated || !fContentAssistant.isShowEmptyList()) { if (!autoActivated) { Control control= fContentAssistSubjectControlAdapter.getControl(); - if (control != null && !control.isDisposed()) + if (control != null && !control.isDisposed()) { control.getDisplay().beep(); + } } hide(); return true; @@ -600,8 +614,9 @@ String getErrorMessage() { * Creates the proposal selector. */ void createProposalSelector() { - if (isValid(fProposalShell)) + if (isValid(fProposalShell)) { return; + } Control control= fContentAssistSubjectControlAdapter.getControl(); fProposalShell= new Shell(control.getShell(), SWT.ON_TOP | SWT.RESIZE ); @@ -612,12 +627,14 @@ void createProposalSelector() { fProposalTable.addListener(SWT.SetData, listener); fIsColoredLabelsSupportEnabled= fContentAssistant.isColoredLabelsSupportEnabled(); - if (fIsColoredLabelsSupportEnabled) + if (fIsColoredLabelsSupportEnabled) { TableOwnerDrawSupport.install(fProposalTable); + } fProposalTable.setLocation(0, 0); - if (fAdditionalInfoController != null) + if (fAdditionalInfoController != null) { fAdditionalInfoController.setSizeConstraints(50, 10, true, true); + } GridLayout layout= new GridLayout(); layout.marginWidth= 0; @@ -721,8 +738,9 @@ int getMinimalHeight() { Rectangle trim= fProposalTable.computeTrim(0, 0, SWT.DEFAULT, items); height= trim.height; } - if (isValid(fMessageText)) + if (isValid(fMessageText)) { height+= fMessageText.getSize().y + 1; + } return height; } @@ -795,8 +813,9 @@ public void focusLost(FocusEvent e) { */ private Color getBackgroundColor(Control control) { Color c= fContentAssistant.getProposalSelectorBackground(); - if (c == null) + if (c == null) { c= JFaceResources.getColorRegistry().get(JFacePreferences.CONTENT_ASSIST_BACKGROUND_COLOR); + } return c; } @@ -809,8 +828,9 @@ private Color getBackgroundColor(Control control) { */ private Color getForegroundColor(Control control) { Color c= fContentAssistant.getProposalSelectorForeground(); - if (c == null) + if (c == null) { c= JFaceResources.getColorRegistry().get(JFacePreferences.CONTENT_ASSIST_FOREGROUND_COLOR); + } return c; } @@ -829,8 +849,9 @@ private void createMessageText() { Font font= fMessageText.getFont(); Display display= fProposalShell.getDisplay(); FontData[] fontDatas= font.getFontData(); - for (FontData fontData : fontDatas) + for (FontData fontData : fontDatas) { fontData.setHeight(fontData.getHeight() * 9 / 10); + } fMessageTextFont= new Font(display, fontDatas); } fMessageText.setFont(fMessageTextFont); @@ -903,8 +924,9 @@ private void handleSetData(Event event) { } item.setText(displayString); - if (fIsColoredLabelsSupportEnabled) + if (fIsColoredLabelsSupportEnabled) { TableOwnerDrawSupport.storeStyleRanges(item, 0, styleRanges); + } item.setImage(image); item.setData(current); @@ -923,12 +945,14 @@ private ICompletionProposal getSelectedProposal() { /* Make sure that there is no filter runnable pending. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=31427 */ - if (fIsFilterPending.get()) + if (fIsFilterPending.get()) { fFilterRunnable.run(); + } // filter runnable may have hidden the proposals - if (!isValid(fProposalTable)) + if (!isValid(fProposalTable)) { return null; + } int i= fProposalTable.getSelectionIndex(); List proposals= fFilteredProposals; @@ -947,8 +971,9 @@ private ICompletionProposal getSelectedProposal() { private void insertSelectedProposalWithMask(int stateMask) { ICompletionProposal p= getSelectedProposal(); hide(); - if (p != null) + if (p != null) { insertProposal(p, (char) 0, stateMask, fContentAssistSubjectControlAdapter.getSelectedRange().x); + } } /** @@ -984,8 +1009,9 @@ public boolean ownsFocusShell() { target= extension.getRewriteTarget(); } - if (target != null) + if (target != null) { target.beginCompoundChange(); + } if (fViewer instanceof IEditingSupportRegistry registry) { registry.register(helper); @@ -1014,19 +1040,22 @@ public boolean ownsFocusShell() { if (p instanceof ICompletionProposalExtension e) { contextInformationOffset= e.getContextInformationPosition(); } else { - if (selection == null) + if (selection == null) { selection= fContentAssistSubjectControlAdapter.getSelectedRange(); + } contextInformationOffset= selection.x + selection.y; } fContentAssistant.showContextInformation(info, contextInformationOffset); - } else + } else { fContentAssistant.showContextInformation(null, -1); + } } finally { - if (target != null) + if (target != null) { target.endCompoundChange(); + } if (fViewer instanceof IEditingSupportRegistry registry) { registry.unregister(helper); @@ -1042,8 +1071,9 @@ public boolean ownsFocusShell() { */ public boolean hasFocus() { if (isValid(fProposalShell)) { - if ((fProposalShell.getDisplay().getActiveShell() == fProposalShell)) + if ((fProposalShell.getDisplay().getActiveShell() == fProposalShell)) { return true; + } /* * We have to delegate this query to the additional info controller * as well, since the content assistant is the widget token owner @@ -1052,13 +1082,15 @@ public boolean hasFocus() { */ if (fAdditionalInfoController != null) { IInformationControl informationControl= fAdditionalInfoController.getCurrentInformationControl2(); - if (informationControl != null && informationControl.isFocusControl()) + if (informationControl != null && informationControl.isFocusControl()) { return true; + } InformationControlReplacer replacer= fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer(); if (replacer != null) { informationControl= replacer.getCurrentInformationControl2(); - if (informationControl != null && informationControl.isFocusControl()) + if (informationControl != null && informationControl.isFocusControl()) { return true; + } } } } @@ -1111,8 +1143,9 @@ public void hide() { private void unregister() { if (fDocumentListener != null) { IDocument document= fContentAssistSubjectControlAdapter.getDocument(); - if (document != null) + if (document != null) { document.removeDocumentListener(fDocumentListener); + } fDocumentListener= null; } fDocumentEvents.clear(); @@ -1156,12 +1189,14 @@ public boolean isActive() { void setProposals(List proposals, boolean isFilteredSubset) { List oldProposals= fFilteredProposals; ICompletionProposal oldProposal= getSelectedProposal(); // may trigger filtering and a reentrant call to setProposals() - if (oldProposals != fFilteredProposals) // reentrant call was first - abort + if (oldProposals != fFilteredProposals) { // reentrant call was first - abort return; + } if (isValid(fProposalTable)) { - if (oldProposal instanceof ICompletionProposalExtension2 && fViewer != null) + if (oldProposal instanceof ICompletionProposalExtension2 && fViewer != null) { ((ICompletionProposalExtension2) oldProposal).unselected(fViewer); + } if (proposals == null || proposals.isEmpty()) { fEmptyProposal.fOffset= fFilterOffset; @@ -1182,8 +1217,9 @@ void setProposals(List proposals, boolean isFilteredSubset) Point currentLocation= fProposalShell.getLocation(); Point newLocation= getLocation(); - if ((newLocation.x < currentLocation.x && newLocation.y == currentLocation.y) || newLocation.y < currentLocation.y) + if ((newLocation.x < currentLocation.x && newLocation.y == currentLocation.y) || newLocation.y < currentLocation.y) { fProposalShell.setLocation(newLocation); + } selectProposal(0, false); } @@ -1227,8 +1263,9 @@ void displayProposals() { */ void displayProposals(boolean showPopup) { - if (!isValid(fProposalShell) || !isValid(fProposalTable)) + if (!isValid(fProposalShell) || !isValid(fProposalTable)) { return; + } if (fContentAssistant.addContentAssistListener(this, ContentAssistant.PROPOSAL_SELECTOR)) { @@ -1237,8 +1274,9 @@ void displayProposals(boolean showPopup) { if (showPopup) { configureAndMakeVisible(); } - } else + } else { hide(); + } } private void configureAndMakeVisible() { @@ -1272,8 +1310,9 @@ public boolean ownsFocusShell() { */ fProposalShell.setVisible(true); // may run event loop on GTK // transfer focus since no verify key listener can be attached - if (!fContentAssistSubjectControlAdapter.supportsVerifyKeyListener() && isValid(fProposalShell)) + if (!fContentAssistSubjectControlAdapter.supportsVerifyKeyListener() && isValid(fProposalShell)) { fProposalShell.setFocus(); // may run event loop on GTK ?? + } if (fAdditionalInfoController != null && isValid(fProposalTable)) { fAdditionalInfoController.install(fProposalTable); @@ -1291,19 +1330,22 @@ void ensureDocumentListenerInstalled() { fDocumentListener= new IDocumentListener() { @Override public void documentAboutToBeChanged(DocumentEvent event) { - if (!fInserting) + if (!fInserting) { fDocumentEvents.add(event); + } } @Override public void documentChanged(DocumentEvent event) { - if (!fInserting) + if (!fInserting) { filterProposals(); + } } }; IDocument document= fContentAssistSubjectControlAdapter.getDocument(); - if (document != null) + if (document != null) { document.addDocumentListener(fDocumentListener); + } } } @@ -1313,8 +1355,9 @@ public boolean verifyKey(VerifyEvent e) { return false; } - if (!isValid(fProposalShell)) + if (!isValid(fProposalShell)) { return true; + } char key= e.character; if (key == 0) { @@ -1330,26 +1373,30 @@ public boolean verifyKey(VerifyEvent e) { case SWT.ARROW_UP : newSelection -= 1; - if (newSelection < 0) + if (newSelection < 0) { newSelection= itemCount - 1; + } break; case SWT.ARROW_DOWN : newSelection += 1; - if (newSelection > itemCount - 1) + if (newSelection > itemCount - 1) { newSelection= 0; + } break; case SWT.PAGE_DOWN : newSelection += visibleRows; - if (newSelection >= itemCount) + if (newSelection >= itemCount) { newSelection= itemCount - 1; + } break; case SWT.PAGE_UP : newSelection -= visibleRows; - if (newSelection < 0) + if (newSelection < 0) { newSelection= 0; + } break; case SWT.HOME : @@ -1361,8 +1408,9 @@ public boolean verifyKey(VerifyEvent e) { break; default : - if (e.keyCode != SWT.CAPS_LOCK && e.keyCode != SWT.MOD1 && e.keyCode != SWT.MOD2 && e.keyCode != SWT.MOD3 && e.keyCode != SWT.MOD4) + if (e.keyCode != SWT.CAPS_LOCK && e.keyCode != SWT.MOD1 && e.keyCode != SWT.MOD2 && e.keyCode != SWT.MOD3 && e.keyCode != SWT.MOD4) { hide(); + } return true; } @@ -1393,8 +1441,9 @@ public boolean verifyKey(VerifyEvent e) { case SWT.BS: { try { - if (fFilterOffset > 0 && fContentAssistSubjectControlAdapter.getDocument().getChar(fFilterOffset - 1) == SWT.SPACE) + if (fFilterOffset > 0 && fContentAssistSubjectControlAdapter.getDocument().getChar(fFilterOffset - 1) == SWT.SPACE) { hide(); + } } catch (BadLocationException e1) { // ignore error } @@ -1429,8 +1478,9 @@ public boolean verifyKey(VerifyEvent e) { private void selectProposal(int index, boolean smartToggle) { ICompletionProposal oldProposal= getSelectedProposal(); - if (oldProposal instanceof ICompletionProposalExtension2 && fViewer != null) + if (oldProposal instanceof ICompletionProposalExtension2 && fViewer != null) { ((ICompletionProposalExtension2) oldProposal).unselected(fViewer); + } List proposals= fFilteredProposals; if (proposals == null || index >= proposals.size()) { @@ -1439,8 +1489,9 @@ private void selectProposal(int index, boolean smartToggle) { } ICompletionProposal proposal= proposals.get(index); - if (proposal instanceof ICompletionProposalExtension2 && fViewer != null) + if (proposal instanceof ICompletionProposalExtension2 && fViewer != null) { ((ICompletionProposalExtension2) proposal).selected(fViewer, smartToggle); + } fireSelectionEvent(proposal, smartToggle); @@ -1448,8 +1499,9 @@ private void selectProposal(int index, boolean smartToggle) { fProposalTable.setSelection(index); fProposalTable.showSelection(); - if (fAdditionalInfoController != null) + if (fAdditionalInfoController != null) { fAdditionalInfoController.handleTableSelectionChanged(); + } } /** @@ -1483,12 +1535,14 @@ private void fireAppliedEvent(ICompletionProposal proposal) { */ private boolean contains(char[] characters, char c) { - if (characters == null) + if (characters == null) { return false; + } for (char character : characters) { - if (c == character) + if (c == character) { return true; + } } return false; @@ -1556,16 +1610,18 @@ List computeFilteredProposals(int offset, DocumentEvent eve if (proposal instanceof ICompletionProposalExtension2 p) { try { - if (p.validate(document, offset, event)) + if (p.validate(document, offset, event)) { filtered.add(proposal); + } } catch (RuntimeException e) { // Make sure that poorly behaved completion proposers do not break filtering. } } else if (proposal instanceof ICompletionProposalExtension p) { try { - if (p.isValidFor(document, offset)) + if (p.isValidFor(document, offset)) { filtered.add(proposal); + } } catch (RuntimeException e) { // Make sure that poorly behaved completion proposers do not break filtering. } @@ -1630,11 +1686,13 @@ public String incrementalComplete() { } else { final Control control= fContentAssistSubjectControlAdapter.getControl(); - if (fKeyListener == null) + if (fKeyListener == null) { fKeyListener= new ProposalSelectionListener(); + } - if (!isValid(fProposalShell) && !control.isDisposed()) + if (!isValid(fProposalShell) && !control.isDisposed()) { fContentAssistSubjectControlAdapter.addKeyListener(fKeyListener); + } BusyIndicator.showWhile(control.getDisplay(), () -> { @@ -1645,17 +1703,18 @@ public String incrementalComplete() { List proposals= fFilteredProposals; int count= (proposals == null ? 0 : proposals.size()); - if (count == 0 && hideWhenNoProposals(false)) + if (count == 0 && hideWhenNoProposals(false)) { return; + } if (proposals != null && proposals.size() == 1 && canAutoInsert(proposals.get(0))) { insertProposal(proposals.get(0), (char) 0, 0, fInvocationOffset); hide(); } else { ensureDocumentListenerInstalled(); - if (count > 0 && completeCommonPrefix()) + if (count > 0 && completeCommonPrefix()) { hide(); - else { + } else { fComputedProposals= proposals; createProposalSelector(); setProposals(fComputedProposals, false); @@ -1710,13 +1769,15 @@ boolean completeCommonPrefix() { for (int i= 0; i < fFilteredProposals.size(); i++) { ICompletionProposal proposal= fFilteredProposals.get(i); - if (!(proposal instanceof ICompletionProposalExtension3)) + if (!(proposal instanceof ICompletionProposalExtension3)) { return false; + } int start= ((ICompletionProposalExtension3)proposal).getPrefixCompletionStart(document, fFilterOffset); CharSequence insertion= ((ICompletionProposalExtension3)proposal).getPrefixCompletionText(document, fFilterOffset); - if (insertion == null) + if (insertion == null) { insertion= TextProcessor.deprocess(proposal.getDisplayString()); + } try { int prefixLength= fFilterOffset - start; int relativeCompletionOffset= Math.min(insertion.length(), prefixLength); @@ -1725,10 +1786,11 @@ boolean completeCommonPrefix() { isWrongCaseMatch= false; rightCase.add(proposal); CharSequence newPostfix= insertion.subSequence(relativeCompletionOffset, insertion.length()); - if (rightCasePostfix == null) + if (rightCasePostfix == null) { rightCasePostfix= new StringBuilder(newPostfix.toString()); - else + } else { truncatePostfix(rightCasePostfix, newPostfix, false); + } } else if (i == 0 || isWrongCaseMatch) { String insertionStrLowerCase= insertion.toString().toLowerCase(); String prefixLowerCase= prefix.toLowerCase(); @@ -1757,23 +1819,26 @@ boolean completeCommonPrefix() { } else { newPostfix= insertion.subSequence(relativeCompletionOffset, insertion.length()); } - if (wrongCasePostfix == null) + if (wrongCasePostfix == null) { wrongCasePostfix= new StringBuilder(newPostfix.toString()); - else + } else { truncatePostfix(wrongCasePostfix, newPostfix, hasMixedProposals); + } wrongCase.add(proposal); } else { return false; } - } else + } else { return false; + } } catch (BadLocationException e2) { // bail out silently return false; } - if (rightCasePostfix != null && rightCasePostfix.length() == 0 && rightCase.size() > 1) + if (rightCasePostfix != null && rightCasePostfix.length() == 0 && rightCase.size() > 1) { return false; + } } // 2: replace single proposals @@ -1799,19 +1864,22 @@ boolean completeCommonPrefix() { // 3: replace post- / prefixes CharSequence prefix; - if (isWrongCaseMatch) + if (isWrongCaseMatch) { prefix= wrongCasePrefix; - else + } else { prefix= ""; //$NON-NLS-1$ + } CharSequence postfix; - if (isWrongCaseMatch) + if (isWrongCaseMatch) { postfix= wrongCasePostfix; - else + } else { postfix= rightCasePostfix; + } - if (prefix == null || postfix == null) + if (prefix == null || postfix == null) { return false; + } try { // 4: check if parts of the postfix are already in the document @@ -1849,8 +1917,9 @@ private boolean hasMixedProposals() { boolean hasSubstringMatch= false; boolean hasPrefixMatch= false; for (ICompletionProposal proposal : fFilteredProposals) { - if (!(proposal instanceof ICompletionProposalExtension3)) + if (!(proposal instanceof ICompletionProposalExtension3)) { return false; + } int start= ((ICompletionProposalExtension3) proposal).getPrefixCompletionStart(document, fFilterOffset); CharSequence insertion= ((ICompletionProposalExtension3) proposal).getPrefixCompletionText(document, fFilterOffset); @@ -1880,8 +1949,9 @@ private boolean hasMixedProposals() { * @since 3.1 */ private boolean isPrefixCompatible(CharSequence oneSequence, int oneOffset, CharSequence twoSequence, int twoOffset, IDocument document, boolean ignoreCase) throws BadLocationException { - if (oneSequence == null || twoSequence == null) + if (oneSequence == null || twoSequence == null) { return true; + } int min= Math.min(oneOffset, twoOffset); int oneEnd= oneOffset + oneSequence.length(); @@ -1930,8 +2000,9 @@ private void truncatePostfix(StringBuilder buffer, CharSequence sequence, boolea */ void setMessage(String message) { Assert.isNotNull(message); - if (isActive() && fMessageText != null && !fMessageText.isDisposed()) + if (isActive() && fMessageText != null && !fMessageText.isDisposed()) { fMessageText.setText(message + " "); //$NON-NLS-1$ + } } /** @@ -1953,8 +2024,9 @@ void setEmptyMessage(String message) { * @since 3.2 */ public void setStatusLineVisible(boolean show) { - if (!isActive() || show == (fMessageText != null && !fMessageText.isDisposed())) + if (!isActive() || show == (fMessageText != null && !fMessageText.isDisposed())) { return; // nothing to do + } if (show) { createMessageText(); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistSubjectControlAdapter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistSubjectControlAdapter.java index f045753e91b..b69fddaff5c 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistSubjectControlAdapter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistSubjectControlAdapter.java @@ -81,51 +81,58 @@ public ContentAssistSubjectControlAdapter(ITextViewer viewer) { @Override public int getLineHeight() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getLineHeight(); + } return fViewer.getTextWidget().getLineHeight(getCaretOffset()); } @Override public Control getControl() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getControl(); + } return fViewer.getTextWidget(); } @Override public Point getLocationAtOffset(int offset) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getLocationAtOffset(offset); + } return fViewer.getTextWidget().getLocationAtOffset(offset); } @Override public Point getWidgetSelectionRange() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getWidgetSelectionRange(); + } return fViewer.getTextWidget().getSelectionRange(); } @Override public Point getSelectedRange() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getSelectedRange(); + } return fViewer.getSelectedRange(); } @Override public int getCaretOffset() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getCaretOffset(); + } return fViewer.getTextWidget().getCaretOffset(); } @Override public String getLineDelimiter() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getLineDelimiter(); + } return fViewer.getTextWidget().getLineDelimiter(); } @@ -139,24 +146,27 @@ public boolean isValidWidgetOffset(int widgetOffset) { @Override public void addKeyListener(KeyListener keyListener) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { fContentAssistSubjectControl.addKeyListener(keyListener); - else + } else { fViewer.getTextWidget().addKeyListener(keyListener); + } } @Override public void removeKeyListener(KeyListener keyListener) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { fContentAssistSubjectControl.removeKeyListener(keyListener); - else + } else { fViewer.getTextWidget().removeKeyListener(keyListener); + } } @Override public IDocument getDocument() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.getDocument(); + } return fViewer.getDocument(); } @@ -180,9 +190,9 @@ public boolean prependVerifyKeyListener(VerifyKeyListener verifyKeyListener) { @Override public boolean appendVerifyKeyListener(VerifyKeyListener verifyKeyListener) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.appendVerifyKeyListener(verifyKeyListener); - else if (fViewer instanceof ITextViewerExtension extension) { + } else if (fViewer instanceof ITextViewerExtension extension) { extension.appendVerifyKeyListener(verifyKeyListener); return true; } else { @@ -203,33 +213,37 @@ public void removeVerifyKeyListener(VerifyKeyListener verifyKeyListener) { extension.removeVerifyKeyListener(verifyKeyListener); } else { StyledText textWidget= fViewer.getTextWidget(); - if (isValid(textWidget)) + if (isValid(textWidget)) { textWidget.removeVerifyKeyListener(verifyKeyListener); + } } } @Override public void setEventConsumer(IEventConsumer eventConsumer) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { fContentAssistSubjectControl.setEventConsumer(eventConsumer); - else + } else { fViewer.setEventConsumer(eventConsumer); + } } @Override public void setSelectedRange(int i, int j) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { fContentAssistSubjectControl.setSelectedRange(i, j); - else + } else { fViewer.setSelectedRange(i, j); + } } @Override public void revealRange(int i, int j) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { fContentAssistSubjectControl.revealRange(i, j); - else + } else { fViewer.revealRange(i, j); + } } /* @@ -237,8 +251,9 @@ public void revealRange(int i, int j) { */ @Override public boolean supportsVerifyKeyListener() { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.supportsVerifyKeyListener(); + } return true; } @@ -251,8 +266,9 @@ public boolean supportsVerifyKeyListener() { * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() */ Set getContentAssistProcessors(ContentAssistant contentAssistant, int offset) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return contentAssistant.getProcessors(fContentAssistSubjectControl, offset); + } return contentAssistant.getProcessors(fViewer, offset); } @@ -268,12 +284,14 @@ Set getContentAssistProcessors(ContentAssistant content */ CompletionProposalPopup createCompletionProposalPopup(ContentAssistant contentAssistant, AdditionalInfoController controller, boolean asynchronous) { if (asynchronous) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return new AsyncCompletionProposalPopup(contentAssistant, fContentAssistSubjectControl, controller); + } return new AsyncCompletionProposalPopup(contentAssistant, fViewer, controller); } else { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return new CompletionProposalPopup(contentAssistant, fContentAssistSubjectControl, controller); + } return new CompletionProposalPopup(contentAssistant, fViewer, controller); } } @@ -285,8 +303,9 @@ CompletionProposalPopup createCompletionProposalPopup(ContentAssistant contentAs * @return the context info popup or null */ ContextInformationPopup createContextInfoPopup(ContentAssistant contentAssistant) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return new ContextInformationPopup(contentAssistant, fContentAssistSubjectControl); + } return new ContextInformationPopup(contentAssistant, fViewer); } @@ -302,8 +321,9 @@ ContextInformationPopup createContextInfoPopup(ContentAssistant contentAssistant * @return an validator */ public IContextInformationValidator getContextInformationValidator(ContentAssistant contentAssistant, int offset) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return contentAssistant.getContextInformationValidator(fContentAssistSubjectControl, offset); + } return contentAssistant.getContextInformationValidator(fViewer, offset); } @@ -317,8 +337,9 @@ public IContextInformationValidator getContextInformationValidator(ContentAssist * @return a presenter */ public IContextInformationPresenter getContextInformationPresenter(ContentAssistant contentAssistant, int offset) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return contentAssistant.getContextInformationPresenter(fContentAssistSubjectControl, offset); + } return contentAssistant.getContextInformationPresenter(fViewer, offset); } @@ -329,10 +350,12 @@ public IContextInformationPresenter getContextInformationPresenter(ContentAssist */ public void installValidator(ContextFrame frame) { if (fContentAssistSubjectControl != null) { - if (frame.fValidator instanceof ISubjectControlContextInformationValidator) + if (frame.fValidator instanceof ISubjectControlContextInformationValidator) { ((ISubjectControlContextInformationValidator) frame.fValidator).install(frame.fInformation, fContentAssistSubjectControl, frame.fOffset); - } else + } + } else { frame.fValidator.install(frame.fInformation, fViewer, frame.fOffset); + } } /** @@ -342,10 +365,12 @@ public void installValidator(ContextFrame frame) { */ public void installContextInformationPresenter(ContextFrame frame) { if (fContentAssistSubjectControl != null) { - if (frame.fPresenter instanceof ISubjectControlContextInformationPresenter) + if (frame.fPresenter instanceof ISubjectControlContextInformationPresenter) { ((ISubjectControlContextInformationPresenter) frame.fValidator).install(frame.fInformation, fContentAssistSubjectControl, frame.fBeginOffset); - } else + } + } else { frame.fPresenter.install(frame.fInformation, fViewer, frame.fBeginOffset); + } } /** @@ -359,25 +384,28 @@ public void installContextInformationPresenter(ContextFrame frame) { * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) */ public IContextInformation[] computeContextInformation(ContentAssistant contentAssistant, int offset) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return contentAssistant.computeContextInformation(fContentAssistSubjectControl, offset); + } return contentAssistant.computeContextInformation(fViewer, offset); } @Override public boolean addSelectionListener(SelectionListener selectionListener) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { return fContentAssistSubjectControl.addSelectionListener(selectionListener); + } fViewer.getTextWidget().addSelectionListener(selectionListener); return true; } @Override public void removeSelectionListener(SelectionListener selectionListener) { - if (fContentAssistSubjectControl != null) + if (fContentAssistSubjectControl != null) { fContentAssistSubjectControl.removeSelectionListener(selectionListener); - else + } else { fViewer.getTextWidget().removeSelectionListener(selectionListener); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java index 3428fe00857..0dcdacd8728 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java @@ -183,8 +183,9 @@ private void updateCurrentCaretInfo() { protected void uninstall() { Control shell= fShell; fShell= null; - if (isValid(shell)) + if (isValid(shell)) { shell.removeControlListener(this); + } Control control= fControl; fControl= null; @@ -241,8 +242,9 @@ public void focusLost(FocusEvent e) { Display d= control.getDisplay(); if (d != null) { d.asyncExec(() -> { - if (!fProposalPopup.hasFocus() && (fContextInfoPopup == null || !fContextInfoPopup.hasFocus())) + if (!fProposalPopup.hasFocus() && (fContextInfoPopup == null || !fContextInfoPopup.hasFocus())) { hide(); + } }); } } @@ -285,7 +287,7 @@ protected class AutoAssistListener extends KeyAdapter implements Runnable, Verif private Thread fThread; private boolean fIsReset= false; - private Object fMutex= new Object(); + private final Object fMutex= new Object(); private int fShowStyle; private final static int SHOW_PROPOSALS= 1; @@ -305,8 +307,9 @@ public void run() { try { while (true) { synchronized (fMutex) { - if (fAutoActivationDelay != 0) + if (fAutoActivationDelay != 0) { fMutex.wait(fAutoActivationDelay); + } if (fIsReset) { fIsReset= false; continue; @@ -330,18 +333,21 @@ protected void reset(int showStyle) { protected void stop() { Thread threadToStop= fThread; - if (threadToStop != null && threadToStop.isAlive()) + if (threadToStop != null && threadToStop.isAlive()) { threadToStop.interrupt(); + } } @Override public void keyPressed(KeyEvent e) { // Only act on typed characters and ignore modifier-only events - if (e.character == 0 && (e.keyCode & SWT.KEYCODE_BIT) == 0) + if (e.character == 0 && (e.keyCode & SWT.KEYCODE_BIT) == 0) { return; + } - if (e.character != 0 && (e.stateMask == SWT.ALT || e.stateMask == SWT.CONTROL || e.stateMask == SWT.COMMAND)) + if (e.character != 0 && (e.stateMask == SWT.ALT || e.stateMask == SWT.CONTROL || e.stateMask == SWT.COMMAND)) { return; + } TriggerType triggerType= getAutoActivationTriggerType(e.character); @@ -353,21 +359,22 @@ public void keyPressed(KeyEvent e) { } int showStyle; - if (triggerType == TriggerType.COMPLETION_PROPOSAL && !isProposalPopupActive()) + if (triggerType == TriggerType.COMPLETION_PROPOSAL && !isProposalPopupActive()) { showStyle= SHOW_PROPOSALS; - else { - if (triggerType == TriggerType.CONTEXT_INFORMATION && !isContextInfoPopupActive()) + } else { + if (triggerType == TriggerType.CONTEXT_INFORMATION && !isContextInfoPopupActive()) { showStyle= SHOW_CONTEXT_INFO; - else { + } else { stop(); return; } } - if (fThread != null && fThread.isAlive()) + if (fThread != null && fThread.isAlive()) { reset(showStyle); - else + } else { start(showStyle); + } } @Override @@ -376,27 +383,33 @@ public void verifyKey(VerifyEvent event) { } protected void showAssist(final int showStyle) { - if (fContentAssistSubjectControlAdapter == null) + if (fContentAssistSubjectControlAdapter == null) { return; + } final Control control= fContentAssistSubjectControlAdapter.getControl(); - if (control == null) + if (control == null) { return; + } final Display d= control.getDisplay(); - if (d == null) + if (d == null) { return; + } try { d.syncExec(() -> { - if (isProposalPopupActive()) + if (isProposalPopupActive()) { return; + } - if (control.isDisposed() || !control.isFocusControl()) + if (control.isDisposed() || !control.isFocusControl()) { return; + } if (showStyle == SHOW_PROPOSALS) { - if (!prepareToShowCompletions(true)) + if (!prepareToShowCompletions(true)) { return; + } fProposalPopup.showProposals(true); fLastAutoActivation= System.currentTimeMillis(); } else if (showStyle == SHOW_CONTEXT_INFO && fContextInfoPopup != null) { @@ -433,15 +446,17 @@ protected void add(Object popup, Shell shell, int type, int offset) { checkType(type); if (fShells[type] != shell) { - if (fShells[type] != null) + if (fShells[type] != null) { fShells[type].removeListener(SWT.Dispose, this); + } shell.addListener(SWT.Dispose, this); fShells[type]= shell; } fPopups[type]= popup; - if (type == LAYOUT_CONTEXT_SELECTOR || type == LAYOUT_CONTEXT_INFO_POPUP) + if (type == LAYOUT_CONTEXT_SELECTOR || type == LAYOUT_CONTEXT_INFO_POPUP) { fContextType= type; + } layout(type, offset); adjustListeners(type); @@ -472,8 +487,9 @@ public void handleEvent(Event event) { case LAYOUT_CONTEXT_SELECTOR: if (isValid(fShells[LAYOUT_PROPOSAL_SELECTOR])) { - if (fProposalPopupOrientation == PROPOSAL_STACKED) + if (fProposalPopupOrientation == PROPOSAL_STACKED) { layout(LAYOUT_PROPOSAL_SELECTOR, getSelectionOffset()); + } // Restore event notification to the proposal popup. addContentAssistListener((IContentAssistListener) fPopups[LAYOUT_PROPOSAL_SELECTOR], PROPOSAL_SELECTOR); } @@ -482,8 +498,9 @@ public void handleEvent(Event event) { case LAYOUT_CONTEXT_INFO_POPUP: if (isValid(fShells[LAYOUT_PROPOSAL_SELECTOR])) { - if (fContextInfoPopupOrientation == CONTEXT_INFO_BELOW) + if (fContextInfoPopupOrientation == CONTEXT_INFO_BELOW) { layout(LAYOUT_PROPOSAL_SELECTOR, getSelectionOffset()); + } } fContextType= LAYOUT_CONTEXT_SELECTOR; break; @@ -492,8 +509,9 @@ public void handleEvent(Event event) { protected int getShellType(Widget shell) { for (int i= 0; i < fShells.length; i++) { - if (fShells[i] == shell) + if (fShells[i] == shell) { return i; + } } return -1; } @@ -620,28 +638,35 @@ protected void layoutContextInfoPopup(int offset) { * @since 3.3 */ protected void constrainLocation(Point point, Point shellSize, Rectangle bounds) { - if (point.x + shellSize.x > bounds.x + bounds.width) + if (point.x + shellSize.x > bounds.x + bounds.width) { point.x= bounds.x + bounds.width - shellSize.x; + } - if (point.x < bounds.x) + if (point.x < bounds.x) { point.x= bounds.x; + } - if (point.y + shellSize.y > bounds.y + bounds.height) + if (point.y + shellSize.y > bounds.y + bounds.height) { point.y= bounds.y + bounds.height - shellSize.y; + } - if (point.y < bounds.y) + if (point.y < bounds.y) { point.y= bounds.y; + } } protected Rectangle constrainHorizontally(Rectangle rect, Rectangle bounds) { // clip width - if (rect.width > bounds.width) + if (rect.width > bounds.width) { rect.width= bounds.width; + } - if (rect.x + rect.width > bounds.x + bounds.width) + if (rect.x + rect.width > bounds.x + bounds.width) { rect.x= bounds.x + bounds.width - rect.width; - if (rect.x < bounds.x) + } + if (rect.x < bounds.x) { rect.x= bounds.x; + } return rect; } @@ -669,15 +694,15 @@ protected Rectangle computeBoundsAboveBelow(Shell shell, Point preferred, int of int caretLowerY= caret.y + caret.height; int spaceBelow= bounds.y + bounds.height - caretLowerY; Rectangle rect; - if (spaceAbove >= preferred.y) + if (spaceAbove >= preferred.y) { rect= new Rectangle(caret.x, caret.y - preferred.y, preferred.x, preferred.y); - else if (spaceBelow >= preferred.y) + } else if (spaceBelow >= preferred.y) { rect= new Rectangle(caret.x, caretLowerY, preferred.x, preferred.y); - // we can't fit in the preferred size - squeeze into larger area - else if (spaceBelow <= spaceAbove) + } else if (spaceBelow <= spaceAbove) { rect= new Rectangle(caret.x, bounds.y, preferred.x, spaceAbove); - else + } else { rect= new Rectangle(caret.x, caretLowerY, preferred.x, spaceBelow); + } return constrainHorizontally(rect, bounds); } @@ -707,12 +732,11 @@ protected Rectangle computeBoundsBelowAbove(Shell shell, Point preferred, int of int spaceBelow= bounds.y + bounds.height - (caret.y + caret.height); Rectangle rect; boolean switched= false; - if (spaceBelow >= preferred.y) + if (spaceBelow >= preferred.y) { rect= new Rectangle(caret.x, caret.y + caret.height, preferred.x, preferred.y); - // squeeze in below if we have at least threshold space - else if (spaceBelow >= threshold) + } else if (spaceBelow >= threshold) { rect= new Rectangle(caret.x, caret.y + caret.height, preferred.x, spaceBelow); - else if (spaceAbove >= preferred.y) { + } else if (spaceAbove >= preferred.y) { rect= new Rectangle(caret.x, caret.y - preferred.y, preferred.x, preferred.y); switched= true; } else if (spaceBelow >= spaceAbove) { @@ -723,8 +747,9 @@ else if (spaceAbove >= preferred.y) { switched= true; } - if (popup != null) + if (popup != null) { popup.switchedPositionToAbove(switched); + } return constrainHorizontally(rect, bounds); } @@ -759,14 +784,16 @@ protected void adjustListeners(int type) { switch (type) { case LAYOUT_PROPOSAL_SELECTOR: if (fContextType == LAYOUT_CONTEXT_SELECTOR && - isValid(fShells[LAYOUT_CONTEXT_SELECTOR])) + isValid(fShells[LAYOUT_CONTEXT_SELECTOR])) { // Disable event notification to the tip selector. removeContentAssistListener((IContentAssistListener) fPopups[LAYOUT_CONTEXT_SELECTOR], CONTEXT_SELECTOR); + } break; case LAYOUT_CONTEXT_SELECTOR: - if (isValid(fShells[LAYOUT_PROPOSAL_SELECTOR])) + if (isValid(fShells[LAYOUT_PROPOSAL_SELECTOR])) { // Disable event notification to the proposal selector. removeContentAssistListener((IContentAssistListener) fPopups[LAYOUT_PROPOSAL_SELECTOR], PROPOSAL_SELECTOR); + } break; case LAYOUT_CONTEXT_INFO_POPUP: break; @@ -831,8 +858,9 @@ public void verifyKey(VerifyEvent e) { } } } - if (fAutoAssistListener != null) + if (fAutoAssistListener != null) { fAutoAssistListener.keyPressed(e); + } } /* @@ -847,8 +875,9 @@ public void processEvent(VerifyEvent event) { for (IContentAssistListener listener : listeners) { if (listener != null) { listener.processEvent(event); - if (!event.doit) + if (!event.doit) { return; + } } } } @@ -968,7 +997,7 @@ public void handleException(Throwable exception) { * @since 3.0 */ private boolean fVerifyKeyListenerHooked= false; - private IContentAssistListener[] fListeners= new IContentAssistListener[4]; + private final IContentAssistListener[] fListeners= new IContentAssistListener[4]; /** * The content assist subject control. * @@ -1010,7 +1039,7 @@ public void handleException(Throwable exception) { * * @since 3.2 */ - private ListenerList fCompletionListeners= new ListenerList<>(ListenerList.IDENTITY); + private final ListenerList fCompletionListeners= new ListenerList<>(ListenerList.IDENTITY); /** * The message to display at the bottom of the proposal popup. * @@ -1075,7 +1104,7 @@ public void handleException(Throwable exception) { * * @since 3.12 */ - private boolean fAsynchronous; + private final boolean fAsynchronous; private boolean fCompletionProposalTriggerCharsEnabled= true; @@ -1144,13 +1173,15 @@ public void setContentAssistProcessor(IContentAssistProcessor processor, String Assert.isNotNull(contentType); - if (fProcessors == null) + if (fProcessors == null) { fProcessors= new HashMap<>(); + } - if (processor == null) + if (processor == null) { fProcessors.remove(contentType); - else + } else { fProcessors.put(contentType, Collections.singleton(processor)); + } } /** @@ -1165,8 +1196,9 @@ public void setContentAssistProcessor(IContentAssistProcessor processor, String public void addContentAssistProcessor(IContentAssistProcessor processor, String contentType) { Assert.isNotNull(contentType); - if (fProcessors == null) + if (fProcessors == null) { fProcessors= new HashMap<>(); + } if (processor == null) { fProcessors.remove(contentType); @@ -1195,8 +1227,9 @@ public void removeContentAssistProcessor(IContentAssistProcessor processor) { */ @Override public IContentAssistProcessor getContentAssistProcessor(String contentType) { - if (fProcessors == null) + if (fProcessors == null) { return null; + } Set res = fProcessors.get(contentType); if (res == null || res.isEmpty()) { @@ -1216,8 +1249,9 @@ public IContentAssistProcessor getContentAssistProcessor(String contentType) { * @since 3.12 */ Set getContentAssistProcessors(String contentType) { - if (fProcessors == null) + if (fProcessors == null) { return null; + } Set res = fProcessors.get(contentType); if (res == null || res.isEmpty()) { @@ -1232,8 +1266,9 @@ Set getContentAssistProcessors(String contentType) { * @since 3.15 */ TriggerType getAutoActivationTriggerType(char c) { - if (fProcessors == null) + if (fProcessors == null) { return TriggerType.NONE; + } int offset= fContentAssistSubjectControlAdapter.getSelectedRange().x; Set processors= fContentAssistSubjectControlAdapter.getContentAssistProcessors(this, offset); if (processors == null) { @@ -1301,18 +1336,20 @@ private void manageAutoActivation(boolean start) { if ((fContentAssistSubjectControlAdapter != null) && fAutoAssistListener == null) { fAutoAssistListener= createAutoAssistListener(); // For details see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49212 - if (fContentAssistSubjectControlAdapter.supportsVerifyKeyListener()) + if (fContentAssistSubjectControlAdapter.supportsVerifyKeyListener()) { fContentAssistSubjectControlAdapter.appendVerifyKeyListener(fAutoAssistListener); - else + } else { fContentAssistSubjectControlAdapter.addKeyListener(fAutoAssistListener); + } } } else if (fAutoAssistListener != null) { // For details see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49212 - if (fContentAssistSubjectControlAdapter.supportsVerifyKeyListener()) + if (fContentAssistSubjectControlAdapter.supportsVerifyKeyListener()) { fContentAssistSubjectControlAdapter.removeVerifyKeyListener(fAutoAssistListener); - else + } else { fContentAssistSubjectControlAdapter.removeKeyListener(fAutoAssistListener); + } fAutoAssistListener= null; } } @@ -1580,8 +1617,9 @@ protected void install() { fInternalListener= new InternalListener(); AdditionalInfoController controller= null; - if (fInformationControlCreator != null) + if (fInformationControlCreator != null) { controller= new AdditionalInfoController(fInformationControlCreator, OpenStrategy.getPostSelectionDelay()); + } fContextInfoPopup= fContentAssistSubjectControlAdapter.createContextInfoPopup(this); fProposalPopup= fContentAssistSubjectControlAdapter.createCompletionProposalPopup(this, controller, fAsynchronous); @@ -1593,8 +1631,9 @@ protected void install() { if (isValid(fContentAssistSubjectControlAdapter.getControl())) { fContentAssistSubjectControlShell= fContentAssistSubjectControlAdapter.getControl().getShell(); fCASCSTraverseListener= e -> { - if (e.detail == SWT.TRAVERSE_ESCAPE && isProposalPopupActive()) + if (e.detail == SWT.TRAVERSE_ESCAPE && isProposalPopupActive()) { e.doit= false; + } }; fContentAssistSubjectControlShell.addTraverseListener(fCASCSTraverseListener); } @@ -1626,8 +1665,9 @@ public void uninstall() { fCloser= null; } - if (isValid(fContentAssistSubjectControlShell)) + if (isValid(fContentAssistSubjectControlShell)) { fContentAssistSubjectControlShell.removeTraverseListener(fCASCSTraverseListener); + } fCASCSTraverseListener= null; fContentAssistSubjectControlShell= null; @@ -1750,8 +1790,9 @@ boolean addContentAssistListener(IContentAssistListener listener, int type) { fCloser.install(); fContentAssistSubjectControlAdapter.setEventConsumer(fInternalListener); installKeyListener(); - } else + } else { promoteKeyListener(); + } return true; } @@ -1797,12 +1838,14 @@ private void installKeyListener() { private void releaseWidgetToken(int type) { if (fListeners[CONTEXT_SELECTOR] == null && fListeners[PROPOSAL_SELECTOR] == null) { IWidgetTokenOwner owner= null; - if (fContentAssistSubjectControl instanceof IWidgetTokenOwner) + if (fContentAssistSubjectControl instanceof IWidgetTokenOwner) { owner= (IWidgetTokenOwner) fContentAssistSubjectControl; - else if (fViewer instanceof IWidgetTokenOwner) + } else if (fViewer instanceof IWidgetTokenOwner) { owner= (IWidgetTokenOwner) fViewer; - if (owner != null) + } + if (owner != null) { owner.releaseWidgetToken(this); + } } } @@ -1837,8 +1880,9 @@ void removeContentAssistListener(IContentAssistListener listener, int type) { */ private void uninstallVerifyKeyListener() { if (fVerifyKeyListenerHooked) { - if (isValid(fContentAssistSubjectControlAdapter.getControl())) + if (isValid(fContentAssistSubjectControlAdapter.getControl())) { fContentAssistSubjectControlAdapter.removeVerifyKeyListener(fInternalListener); + } fVerifyKeyListenerHooked= false; } } @@ -1852,8 +1896,9 @@ private void uninstallVerifyKeyListener() { private int getNumberOfListeners() { int count= 0; for (int i= 0; i <= CONTEXT_INFO_POPUP; i++) { - if (fListeners[i] != null) + if (fListeners[i] != null) { ++count; + } } return count; } @@ -1863,17 +1908,20 @@ private int getNumberOfListeners() { */ @Override public String showPossibleCompletions() { - if (!prepareToShowCompletions(false)) + if (!prepareToShowCompletions(false)) { return null; - if (fIsPrefixCompletionEnabled) + } + if (fIsPrefixCompletionEnabled) { return fProposalPopup.incrementalComplete(); + } return fProposalPopup.showProposals(false); } @Override public String completePrefix() { - if (!prepareToShowCompletions(false)) + if (!prepareToShowCompletions(false)) { return null; + } return fProposalPopup.incrementalComplete(); } @@ -1916,8 +1964,9 @@ protected void possibleCompletionsClosed() { @Override public String showContextInformation() { promoteKeyListener(); - if (fContextInfoPopup != null) + if (fContextInfoPopup != null) { return fContextInfoPopup.showContextProposals(false); + } return null; } @@ -1938,8 +1987,9 @@ protected void contextInformationClosed() { * @since 2.0 */ void showContextInformation(IContextInformation contextInformation, int offset) { - if (fContextInfoPopup != null) + if (fContextInfoPopup != null) { fContextInfoPopup.showContextInformation(contextInformation, offset); + } } /** @@ -1986,10 +2036,11 @@ Set getProcessors(IContentAssistSubjectControl contentA IDocument document= contentAssistSubjectControl.getDocument(); String type; - if (document != null) + if (document != null) { type= TextUtilities.getContentType(document, getDocumentPartitioning(), offset, true); - else + } else { type= IDocument.DEFAULT_CONTENT_TYPE; + } return getContentAssistProcessors(type); @@ -2210,8 +2261,9 @@ IContextInformationValidator getContextInformationValidator(IContentAssistSubjec */ IContextInformationPresenter getContextInformationPresenter(ITextViewer viewer, int offset) { IContextInformationValidator validator= getContextInformationValidator(viewer, offset); - if (validator instanceof IContextInformationPresenter) + if (validator instanceof IContextInformationPresenter) { return (IContextInformationPresenter) validator; + } return null; } @@ -2226,8 +2278,9 @@ IContextInformationPresenter getContextInformationPresenter(ITextViewer viewer, */ IContextInformationPresenter getContextInformationPresenter(IContentAssistSubjectControl contentAssistSubjectControl, int offset) { IContextInformationValidator validator= getContextInformationValidator(contentAssistSubjectControl, offset); - if (validator instanceof IContextInformationPresenter) + if (validator instanceof IContextInformationPresenter) { return (IContextInformationPresenter) validator; + } return null; } @@ -2260,11 +2313,13 @@ public boolean setFocus(IWidgetTokenOwner owner) { * @since 3.0 */ protected void hide() { - if (fProposalPopup != null) + if (fProposalPopup != null) { fProposalPopup.hide(); + } - if (fContextInfoPopup != null) + if (fContextInfoPopup != null) { fContextInfoPopup.hide(); + } } // ------ control's size handling dialog settings ------ @@ -2300,12 +2355,14 @@ public void setRestoreCompletionProposalSize(IDialogSettings dialogSettings) { * Stores the content assist's proposal pop-up size. */ protected void storeCompletionProposalPopupSize() { - if (fDialogSettings == null || fProposalPopup == null) + if (fDialogSettings == null || fProposalPopup == null) { return; + } Point size= fProposalPopup.getSize(); - if (size == null) + if (size == null) { return; + } fDialogSettings.put(STORE_SIZE_X, size.x); fDialogSettings.put(STORE_SIZE_Y, size.y); @@ -2317,12 +2374,14 @@ protected void storeCompletionProposalPopupSize() { * @since 3.9 */ protected void storeContextSelectorPopupSize() { - if (fDialogSettings == null || fContextInfoPopup == null) + if (fDialogSettings == null || fContextInfoPopup == null) { return; + } Point size= fContextInfoPopup.getContextSelectorPopupSize(); - if (size == null) + if (size == null) { return; + } fDialogSettings.put(STORE_CONTEXT_SELECTOR_POPUP_SIZE_X, size.x); fDialogSettings.put(STORE_CONTEXT_SELECTOR_POPUP_SIZE_Y, size.y); @@ -2335,8 +2394,9 @@ protected void storeContextSelectorPopupSize() { * @since 3.0 */ protected Point restoreCompletionProposalPopupSize() { - if (fDialogSettings == null) + if (fDialogSettings == null) { return null; + } Point size= new Point(-1, -1); @@ -2348,19 +2408,22 @@ protected Point restoreCompletionProposalPopupSize() { } // sanity check - if (size.x == -1 && size.y == -1) + if (size.x == -1 && size.y == -1) { return null; + } Rectangle maxBounds= null; - if (fContentAssistSubjectControl != null && isValid(fContentAssistSubjectControl.getControl())) + if (fContentAssistSubjectControl != null && isValid(fContentAssistSubjectControl.getControl())) { maxBounds= fContentAssistSubjectControl.getControl().getDisplay().getBounds(); - else { + } else { // fallback Display display= Display.getCurrent(); - if (display == null) + if (display == null) { display= Display.getDefault(); - if (display != null && !display.isDisposed()) + } + if (display != null && !display.isDisposed()) { maxBounds= display.getBounds(); + } } if (size.x > -1 && size.y > -1) { @@ -2384,8 +2447,9 @@ protected Point restoreCompletionProposalPopupSize() { * @since 3.9 */ protected Point restoreContextSelectorPopupSize() { - if (fDialogSettings == null) + if (fDialogSettings == null) { return null; + } Point size= new Point(-1, -1); @@ -2397,15 +2461,18 @@ protected Point restoreContextSelectorPopupSize() { } // sanity check - if (size.x == -1 && size.y == -1) + if (size.x == -1 && size.y == -1) { return null; + } Rectangle maxBounds= null; Display display= Display.getCurrent(); - if (display == null) + if (display == null) { display= Display.getDefault(); - if (display != null && !display.isDisposed()) + } + if (display != null && !display.isDisposed()) { maxBounds= display.getBounds(); + } if (size.x > -1 && size.y > -1) { if (maxBounds != null) { @@ -2495,8 +2562,9 @@ void fireSessionRestartEvent() { processors.forEach(processor -> { ContentAssistEvent event= new ContentAssistEvent(this, processor); for (ICompletionListener listener : fCompletionListeners) { - if (listener instanceof ICompletionListenerExtension) + if (listener instanceof ICompletionListenerExtension) { ((ICompletionListenerExtension)listener).assistSessionRestarted(event); + } } }); } @@ -2559,8 +2627,9 @@ boolean isShowEmptyList() { @Override public void setStatusLineVisible(boolean show) { fIsStatusLineVisible= show; - if (fProposalPopup != null) + if (fProposalPopup != null) { fProposalPopup.setStatusLineVisible(show); + } } /** @@ -2579,8 +2648,9 @@ boolean isStatusLineVisible() { public void setStatusMessage(String message) { Assert.isLegal(message != null); fMessage= message; - if (fProposalPopup != null) + if (fProposalPopup != null) { fProposalPopup.setMessage(message); + } } /** @@ -2596,8 +2666,9 @@ String getStatusMessage() { @Override public void setEmptyMessage(String message) { Assert.isLegal(message != null); - if (fProposalPopup != null) + if (fProposalPopup != null) { fProposalPopup.setEmptyMessage(message); + } } /** @@ -2621,8 +2692,9 @@ void fireSelectionEvent(ICompletionProposal proposal, boolean smartToggle) { */ void fireAppliedEvent(ICompletionProposal proposal) { for (ICompletionListener listener : fCompletionListeners) { - if (listener instanceof ICompletionListenerExtension2) + if (listener instanceof ICompletionListenerExtension2) { ((ICompletionListenerExtension2)listener).applied(proposal); + } } } @@ -2672,12 +2744,14 @@ protected boolean isContextInfoPopupActive(){ */ @Override public final IHandler getHandler(String commandId) { - if (fHandlers == null) + if (fHandlers == null) { throw new IllegalStateException(); + } IHandler handler= fHandlers.get(commandId); - if (handler != null) + if (handler != null) { return handler; + } Assert.isLegal(false); return null; @@ -2691,8 +2765,9 @@ public final IHandler getHandler(String commandId) { * @since 3.4 */ protected final void registerHandler(String commandId, IHandler handler) { - if (fHandlers == null) + if (fHandlers == null) { fHandlers= new HashMap<>(2); + } fHandlers.put(commandId, handler); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformation.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformation.java index b5701baf105..561aa4b212c 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformation.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformation.java @@ -62,8 +62,9 @@ public ContextInformation(Image image, String contextDisplayString, String infor public boolean equals(Object object) { if (object instanceof IContextInformation contextInformation) { boolean equals= fInformationDisplayString.equalsIgnoreCase(contextInformation.getInformationDisplayString()); - if (fContextDisplayString != null) + if (fContextDisplayString != null) { equals= equals && fContextDisplayString.equalsIgnoreCase(contextInformation.getContextDisplayString()); + } return equals; } return false; @@ -87,8 +88,9 @@ public Image getImage() { @Override public String getContextDisplayString() { - if (fContextDisplayString != null) + if (fContextDisplayString != null) { return fContextDisplayString; + } return fInformationDisplayString; } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java index 07266cbc3e7..60f7b6b4356 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java @@ -107,9 +107,9 @@ public int hashCode() { } private ITextViewer fViewer; - private ContentAssistant fContentAssistant; + private final ContentAssistant fContentAssistant; - private PopupCloser fPopupCloser= new PopupCloser(); + private final PopupCloser fPopupCloser= new PopupCloser(); private Shell fContextSelectorShell; private Point fContextSelectorPopupSize; private Table fContextSelectorTable; @@ -120,7 +120,7 @@ public int hashCode() { private StyledText fContextInfoText; private TextPresentation fTextPresentation; - private Stack fContextFrameStack= new Stack<>(); + private final Stack fContextFrameStack= new Stack<>(); /** * The content assist subject control. * @@ -132,7 +132,7 @@ public int hashCode() { * * @since 3.0 */ - private ContentAssistSubjectControlAdapter fContentAssistSubjectControlAdapter; + private final ContentAssistSubjectControlAdapter fContentAssistSubjectControlAdapter; /** * Selection listener on the text widget which is active @@ -190,11 +190,12 @@ public String showContextProposals(final boolean autoActivated) { IContextInformation[] contexts= computeContextInformation(offset); if (contexts != null && contexts.length == 1) { ContextFrame frame1= createContextFrame(contexts[0], offset); - if (isDuplicate(frame1)) + if (isDuplicate(frame1)) { validateContextInformation(); - else + } else { // Show context information directly // Show context information directly internalShowContextInfo(frame1); + } } else if (contexts != null && contexts.length > 0) { // if any of the proposed context matches any of the contexts on the stack, @@ -227,8 +228,9 @@ public String showContextProposals(final boolean autoActivated) { // otherwise: // Precise context must be selected - if (fLineDelimiter == null) + if (fLineDelimiter == null) { fLineDelimiter= fContentAssistSubjectControlAdapter.getLineDelimiter(); + } createContextSelector(); setContexts(contexts, index); @@ -249,14 +251,15 @@ public String showContextProposals(final boolean autoActivated) { public void showContextInformation(final IContextInformation info, final int offset) { Control control= fContentAssistSubjectControlAdapter.getControl(); BusyIndicator.showWhile(control.getDisplay(), () -> { - if (info == null) + if (info == null) { validateContextInformation(); - else { + } else { ContextFrame frame= createContextFrame(info, offset); - if (isDuplicate(frame)) + if (isDuplicate(frame)) { validateContextInformation(); - else + } else { internalShowContextInfo(frame); + } hideContextSelector(); } }); @@ -271,8 +274,9 @@ public void showContextInformation(final IContextInformation info, final int off private void internalShowContextInfo(ContextFrame frame) { if (frame != null && canShowFrame(frame)) { fContextFrameStack.push(frame); - if (fContextFrameStack.size() == 1) + if (fContextFrameStack.size() == 1) { fLastContext= null; + } internalShowContextFrame(frame, fContextFrameStack.size() == 1); validateContextInformation(); } @@ -291,7 +295,9 @@ private ContextFrame createContextFrame(IContextInformation information, int off if (validator != null) { int beginOffset= (information instanceof IContextInformationExtension i) ? i.getContextInformationPosition() : offset; - if (beginOffset == -1) beginOffset= offset; + if (beginOffset == -1) { + beginOffset= offset; + } int visibleOffset= fContentAssistSubjectControlAdapter.getWidgetSelectionRange().x - (offset - beginOffset); IContextInformationPresenter presenter = fContentAssistSubjectControlAdapter.getContextInformationPresenter(fContentAssistant, offset); return new ContextFrame(information, beginOffset, offset, visibleOffset, validator, presenter); @@ -309,10 +315,12 @@ private ContextFrame createContextFrame(IContextInformation information, int off * @since 3.0 */ private boolean isDuplicate(ContextFrame frame) { - if (frame == null) + if (frame == null) { return false; - if (fContextFrameStack.isEmpty()) + } + if (fContextFrameStack.isEmpty()) { return false; + } // stack not empty ContextFrame top= fContextFrameStack.peek(); return frame.equals(top); @@ -355,8 +363,9 @@ private void internalShowContextFrame(ContextFrame frame, boolean initial) { fContentAssistSubjectControlAdapter.installValidator(frame); if (frame.fPresenter != null) { - if (fTextPresentation == null) + if (fTextPresentation == null) { fTextPresentation= new TextPresentation(); + } fContentAssistSubjectControlAdapter.installContextInformationPresenter(frame); frame.fPresenter.updatePresentation(frame.fOffset, fTextPresentation); } @@ -364,8 +373,9 @@ private void internalShowContextFrame(ContextFrame frame, boolean initial) { createContextInfoPopup(); fContextInfoText.setText(frame.fInformation.getInformationDisplayString()); - if (fTextPresentation != null) + if (fTextPresentation != null) { TextPresentation.applyTextPresentation(fTextPresentation, fContextInfoText); + } resize(frame.fVisibleOffset); if (initial) { @@ -410,8 +420,9 @@ private String getErrorMessage() { * Creates the context information popup. This is the tool tip like overlay window. */ private void createContextInfoPopup() { - if (isValid(fContextInfoPopup)) + if (isValid(fContextInfoPopup)) { return; + } Control control= fContentAssistSubjectControlAdapter.getControl(); Display display= control.getDisplay(); @@ -422,13 +433,15 @@ private void createContextInfoPopup() { fContextInfoText= new StyledText(fContextInfoPopup, SWT.MULTI | SWT.READ_ONLY | SWT.WRAP); Color c= fContentAssistant.getContextInformationPopupBackground(); - if (c == null) + if (c == null) { c= display.getSystemColor(SWT.COLOR_INFO_BACKGROUND); + } fContextInfoText.setBackground(c); c= fContentAssistant.getContextInformationPopupForeground(); - if (c == null) + if (c == null) { c= display.getSystemColor(SWT.COLOR_INFO_FOREGROUND); + } fContextInfoText.setForeground(c); } @@ -445,9 +458,10 @@ private void resize(int offset) { final int PAD= TEXT_PAD + BORDER_PAD; size.x += PAD; Rectangle bounds= fContentAssistant.getLayoutManager().computeBoundsAboveBelow(fContextInfoPopup, size, offset); - if (bounds.width < size.x) + if (bounds.width < size.x) { // we don't fit on the screen - try again and wrap size= fContextInfoText.computeSize(bounds.width - PAD, SWT.DEFAULT, true); + } size.x += TEXT_PAD; fContextInfoText.setSize(size); @@ -483,8 +497,9 @@ private void hideContextInfoPopup(boolean all) { } fContentAssistant.removeContentAssistListener(this, ContentAssistant.CONTEXT_INFO_POPUP); - if (fContentAssistSubjectControlAdapter.getControl() != null) + if (fContentAssistSubjectControlAdapter.getControl() != null) { fContentAssistSubjectControlAdapter.removeSelectionListener(fTextWidgetSelectionListener); + } fTextWidgetSelectionListener= null; fContextInfoPopup.setVisible(false); @@ -497,8 +512,9 @@ private void hideContextInfoPopup(boolean all) { } } - if (fContextInfoPopup == null) + if (fContextInfoPopup == null) { fContentAssistant.contextInformationClosed(); + } } /** @@ -506,8 +522,9 @@ private void hideContextInfoPopup(boolean all) { * at a given offset. */ private void createContextSelector() { - if (isValid(fContextSelectorShell)) + if (isValid(fContextSelectorShell)) { return; + } Control control= fContentAssistSubjectControlAdapter.getControl(); fContextSelectorShell= new Shell(control.getShell(), SWT.ON_TOP | SWT.RESIZE); @@ -554,19 +571,22 @@ public void controlResized(ControlEvent e) { fContextSelectorTable.setLayoutData(gd); Point size= fContentAssistant.restoreContextSelectorPopupSize(); - if (size != null) + if (size != null) { fContextSelectorShell.setSize(size); - else + } else { fContextSelectorShell.pack(true); + } Color c= fContentAssistant.getContextSelectorBackground(); - if (c == null) + if (c == null) { c= control.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND); + } fContextSelectorTable.setBackground(c); c= fContentAssistant.getContextSelectorForeground(); - if (c == null) + if (c == null) { c= control.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND); + } fContextSelectorTable.setForeground(c); fContextSelectorTable.addSelectionListener(new SelectionListener() { @@ -621,8 +641,9 @@ Point getContextSelectorPopupSize() { private void insertSelectedContext() { int i= fContextSelectorTable.getSelectionIndex(); - if (i < 0 || i >= fContextSelectorInput.length) + if (i < 0 || i >= fContextSelectorInput.length) { return; + } int offset= fContentAssistSubjectControlAdapter.getSelectedRange().x; internalShowContextInfo(createContextFrame(fContextSelectorInput[i], offset)); @@ -647,8 +668,9 @@ private void setContexts(IContextInformation[] contexts, int selectionIndex) { for (IContextInformation context : contexts) { t= context; item= new TableItem(fContextSelectorTable, SWT.NULL); - if (t.getImage() != null) + if (t.getImage() != null) { item.setImage(t.getImage()); + } item.setText(t.getContextDisplayString()); } @@ -661,8 +683,9 @@ private void setContexts(IContextInformation[] contexts, int selectionIndex) { * Displays the context selector. */ private void displayContextSelector() { - if (fContentAssistant.addContentAssistListener(this, ContentAssistant.CONTEXT_SELECTOR)) + if (fContentAssistant.addContentAssistListener(this, ContentAssistant.CONTEXT_SELECTOR)) { fContextSelectorShell.setVisible(true); + } } /** @@ -679,8 +702,9 @@ private void hideContextSelector() { fContextSelectorShell= null; } - if (!isValid(fContextInfoPopup)) + if (!isValid(fContextInfoPopup)) { fContentAssistant.contextInformationClosed(); + } } /** @@ -689,8 +713,9 @@ private void hideContextSelector() { * @return true if the context selector has the focus */ public boolean hasFocus() { - if (isValid(fContextSelectorShell)) + if (isValid(fContextSelectorShell)) { return fContextSelectorShell.getDisplay().getActiveShell() == fContextSelectorShell; + } return false; } @@ -715,10 +740,12 @@ public boolean isActive() { @Override public boolean verifyKey(VerifyEvent e) { - if (isValid(fContextSelectorShell)) + if (isValid(fContextSelectorShell)) { return contextSelectorKeyPressed(e); - if (isValid(fContextInfoPopup)) + } + if (isValid(fContextInfoPopup)) { return contextInfoPopupKeyPressed(e); + } return true; } @@ -739,26 +766,30 @@ private boolean contextSelectorKeyPressed(VerifyEvent e) { switch (e.keyCode) { case SWT.ARROW_UP : newSelection -= 1; - if (newSelection < 0) + if (newSelection < 0) { newSelection= itemCount - 1; + } break; case SWT.ARROW_DOWN : newSelection += 1; - if (newSelection > itemCount - 1) + if (newSelection > itemCount - 1) { newSelection= 0; + } break; case SWT.PAGE_DOWN : newSelection += visibleRows; - if (newSelection >= itemCount) + if (newSelection >= itemCount) { newSelection= itemCount - 1; + } break; case SWT.PAGE_UP : newSelection -= visibleRows; - if (newSelection < 0) + if (newSelection < 0) { newSelection= 0; + } break; case SWT.HOME : @@ -770,8 +801,9 @@ private boolean contextSelectorKeyPressed(VerifyEvent e) { break; default : - if (e.keyCode != SWT.CAPS_LOCK && e.keyCode != SWT.MOD1 && e.keyCode != SWT.MOD2 && e.keyCode != SWT.MOD3 && e.keyCode != SWT.MOD4) + if (e.keyCode != SWT.CAPS_LOCK && e.keyCode != SWT.MOD1 && e.keyCode != SWT.MOD2 && e.keyCode != SWT.MOD3 && e.keyCode != SWT.MOD4) { hideContextSelector(); + } return true; } @@ -812,8 +844,9 @@ private boolean contextInfoPopupKeyPressed(KeyEvent e) { validateContextInformation(); break; default: - if (e.keyCode != SWT.CAPS_LOCK && e.keyCode != SWT.MOD1 && e.keyCode != SWT.MOD2 && e.keyCode != SWT.MOD3 && e.keyCode != SWT.MOD4) + if (e.keyCode != SWT.CAPS_LOCK && e.keyCode != SWT.MOD1 && e.keyCode != SWT.MOD2 && e.keyCode != SWT.MOD3 && e.keyCode != SWT.MOD4) { hideContextInfoPopup(true); + } break; } @@ -828,10 +861,12 @@ private boolean contextInfoPopupKeyPressed(KeyEvent e) { @Override public void processEvent(VerifyEvent event) { - if (isValid(fContextSelectorShell)) + if (isValid(fContextSelectorShell)) { contextSelectorProcessEvent(event); - if (isValid(fContextInfoPopup)) + } + if (isValid(fContextInfoPopup)) { contextInfoPopupProcessEvent(event); + } } /** @@ -855,8 +890,9 @@ private void contextSelectorProcessEvent(VerifyEvent e) { * @param e the verify event describing the key stroke */ private void contextInfoPopupProcessEvent(VerifyEvent e) { - if (e.start != e.end && (e.text == null || e.text.isEmpty())) + if (e.start != e.end && (e.text == null || e.text.isEmpty())) { validateContextInformation(); + } } /** @@ -869,12 +905,13 @@ private void validateContextInformation() { * Otherwise, we'd validate the context information based on the * pre-key-stroke state. */ - if (!isValid(fContextInfoPopup)) + if (!isValid(fContextInfoPopup)) { return; + } fContextInfoPopup.getDisplay().asyncExec(new Runnable() { - private ContextFrame fFrame= fContextFrameStack.peek(); + private final ContextFrame fFrame= fContextFrameStack.peek(); @Override public void run() { @@ -892,8 +929,9 @@ public void run() { TextPresentation.applyTextPresentation(fTextPresentation, fContextInfoText); resize(widgetOffset); break; - } else + } else { break; + } } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationValidator.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationValidator.java index 971779f0816..06c5824f6f1 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationValidator.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationValidator.java @@ -26,7 +26,7 @@ public final class ContextInformationValidator implements IContextInformationValidator { /** The content assist processor. */ - private IContentAssistProcessor fProcessor; + private final IContentAssistProcessor fProcessor; /** The context information to be validated. */ private IContextInformation fContextInformation; /** The associated text viewer. */ @@ -52,9 +52,11 @@ public void install(IContextInformation contextInformation, ITextViewer viewer, public boolean isContextInformationValid(int offset) { IContextInformation[] infos= fProcessor.computeContextInformation(fViewer, offset); if (infos != null && infos.length > 0) { - for (IContextInformation info : infos) - if (fContextInformation.equals(info)) + for (IContextInformation info : infos) { + if (fContextInformation.equals(info)) { return true; + } + } } return false; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java index 3d2cc5a139b..4f4951cda1b 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/PopupCloser.java @@ -101,8 +101,9 @@ public void install(ContentAssistant contentAssistant, Table table, AdditionalIn fShell.addShellListener(this); fTable.addFocusListener(this); fScrollbar= fTable.getVerticalBar(); - if (fScrollbar != null) + if (fScrollbar != null) { fScrollbar.addSelectionListener(this); + } fDisplay.addFilter(SWT.Activate, this); fDisplay.addFilter(SWT.MouseVerticalWheel, this); @@ -120,13 +121,16 @@ public void install(ContentAssistant contentAssistant, Table table, AdditionalIn */ public void uninstall() { fContentAssistant= null; - if (isValid(fShell)) + if (isValid(fShell)) { fShell.removeShellListener(this); + } fShell= null; - if (isValid(fScrollbar)) + if (isValid(fScrollbar)) { fScrollbar.removeSelectionListener(this); - if (isValid(fTable)) + } + if (isValid(fTable)) { fTable.removeFocusListener(this); + } if (fDisplay != null && ! fDisplay.isDisposed()) { fDisplay.removeFilter(SWT.Activate, this); fDisplay.removeFilter(SWT.MouseVerticalWheel, this); @@ -158,8 +162,9 @@ public void focusLost(final FocusEvent e) { fScrollbarClicked= false; Display d= fTable.getDisplay(); d.asyncExec(() -> { - if (isValid(fTable) && !fTable.isFocusControl() && !fScrollbarClicked && fContentAssistant != null) + if (isValid(fTable) && !fTable.isFocusControl() && !fScrollbarClicked && fContentAssistant != null) { fContentAssistant.popupFocusLost(e); + } }); } @@ -171,8 +176,9 @@ public void shellDeactivated(ShellEvent e) { * The asyncExec is a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=235556 : * fContentAssistant.hasProposalPopupFocus() is still true during the shellDeactivated(..) event. */ - if (fContentAssistant != null && !fContentAssistant.hasProposalPopupFocus()) + if (fContentAssistant != null && !fContentAssistant.hasProposalPopupFocus()) { fContentAssistant.hide(); + } }); } } @@ -180,8 +186,9 @@ public void shellDeactivated(ShellEvent e) { @Override public void shellClosed(ShellEvent e) { - if (fContentAssistant != null) + if (fContentAssistant != null) { fContentAssistant.hide(); + } } @Override @@ -189,21 +196,24 @@ public void handleEvent(Event event) { switch (event.type) { case SWT.Activate: case SWT.MouseVerticalWheel: - if (fAdditionalInfoController == null) + if (fAdditionalInfoController == null) { return; - if (event.widget == fShell || event.widget == fTable || event.widget == fScrollbar) + } + if (event.widget == fShell || event.widget == fTable || event.widget == fScrollbar) { return; + } - if (fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer() == null) + if (fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer() == null) { fAdditionalInfoController.hideInformationControl(); - else if (!fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) { + } else if (!fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) { IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2(); // During isReplaceInProgress(), events can come from the replacing information control if (event.widget instanceof Control control && infoControl instanceof IInformationControlExtension5 iControl5) { - if (!(iControl5.containsControl(control))) + if (!(iControl5.containsControl(control))) { fAdditionalInfoController.hideInformationControl(); - else if (event.type == SWT.MouseVerticalWheel) + } else if (event.type == SWT.MouseVerticalWheel) { fAdditionalInfoController.getInternalAccessor().replaceInformationControl(false); + } } else if (infoControl != null && infoControl.isFocusControl()) { fAdditionalInfoController.getInternalAccessor().replaceInformationControl(true); } @@ -213,8 +223,9 @@ else if (event.type == SWT.MouseVerticalWheel) case SWT.MouseEnter: case SWT.MouseMove: case SWT.MouseUp: - if (fAdditionalInfoController == null || fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) + if (fAdditionalInfoController == null || fAdditionalInfoController.getInternalAccessor().isReplaceInProgress()) { break; + } if (event.widget instanceof Control control) { IInformationControl infoControl= fAdditionalInfoController.getCurrentInformationControl2(); if (infoControl instanceof final IInformationControlExtension5 iControl5) { @@ -234,16 +245,18 @@ else if (event.type == SWT.MouseVerticalWheel) break; case SWT.Deactivate: - if (fAdditionalInfoController == null) + if (fAdditionalInfoController == null) { break; + } InformationControlReplacer replacer= fAdditionalInfoController.getInternalAccessor().getInformationControlReplacer(); if (replacer != null && fContentAssistant != null) { IInformationControl iControl= replacer.getCurrentInformationControl2(); if (event.widget instanceof Control control && iControl instanceof IInformationControlExtension5 iControl5) { if (iControl5.containsControl(control)) { control.getDisplay().asyncExec(() -> { - if (fContentAssistant != null && !fContentAssistant.hasProposalPopupFocus()) + if (fContentAssistant != null && !fContentAssistant.hasProposalPopupFocus()) { fContentAssistant.hide(); + } }); } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java index 309c31d74f3..83c0a963a2b 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java @@ -164,8 +164,9 @@ protected Position getPosition() { * @return the referenced character position */ protected int getCharacterPosition() { - if (fRefersToOffset) + if (fRefersToOffset) { return getOffset(); + } return getOffset() + getLength(); } @@ -222,9 +223,9 @@ public void update(DocumentEvent event) { class UpdateAffectedPositions implements IPositionUpdater { /** The affected positions */ - private int[] fPositions; + private final int[] fPositions; /** The offset */ - private int fOffset; + private final int fOffset; /** * Creates a new updater. @@ -302,13 +303,15 @@ public void setFormattingStrategy(IFormattingStrategy strategy, String contentTy Assert.isNotNull(contentType); - if (fStrategies == null) + if (fStrategies == null) { fStrategies= new HashMap<>(); + } - if (strategy == null) + if (strategy == null) { fStrategies.remove(contentType); - else + } else { fStrategies.put(contentType, strategy); + } } /** @@ -349,8 +352,9 @@ public IFormattingStrategy getFormattingStrategy(String contentType) { Assert.isNotNull(contentType); - if (fStrategies == null) + if (fStrategies == null) { return null; + } return fStrategies.get(contentType); } @@ -361,10 +365,11 @@ public void format(IDocument document, IRegion region) { fDocument= document; try { - if (fIsPartitionAware) + if (fIsPartitionAware) { formatPartitions(region); - else + } else { formatRegion(region); + } } finally { fNeedsComputation= true; @@ -458,8 +463,9 @@ private TypedPosition[] getPartitioning(IRegion region) throws BadLocationExcept private void start(TypedPosition[] regions, String indentation) { for (TypedPosition region : regions) { IFormattingStrategy s= getFormattingStrategy(region.getType()); - if (s != null) + if (s != null) { s.formatterStarts(indentation); + } } } @@ -530,8 +536,9 @@ private void format(IFormattingStrategy strategy, TypedPosition region) { private void stop(TypedPosition[] regions) { for (TypedPosition region : regions) { IFormattingStrategy s= getFormattingStrategy(region.getType()); - if (s != null) + if (s != null) { s.formatterStops(); + } } } @@ -573,8 +580,9 @@ private String[] getPartitionManagingCategories() { if (fNeedsComputation) { fNeedsComputation= false; fPartitionManagingCategories= TextUtilities.computePartitionManagingCategories(fDocument); - if (fPartitionManagingCategories == null) + if (fPartitionManagingCategories == null) { fPartitionManagingCategories= fExternalPartitonManagingCategories; + } } return fPartitionManagingCategories; } @@ -617,8 +625,9 @@ private void determinePositionsToUpdate(int offset, int length) { if (categories != null) { for (String cat : categories) { - if (ignoreCategory(cat)) + if (ignoreCategory(cat)) { continue; + } try { @@ -628,11 +637,13 @@ private void determinePositionsToUpdate(int offset, int length) { if (p.overlapsWith(offset, length)) { - if (offset < p.getOffset()) + if (offset < p.getOffset()) { fOverlappingPositionReferences.add(new PositionReference(p, true, cat)); + } - if (p.getOffset() + p.getLength() < offset + length) + if (p.getOffset() + p.getLength() < offset + length) { fOverlappingPositionReferences.add(new PositionReference(p, false, cat)); + } } } @@ -697,27 +708,31 @@ private void removeAffectedPositions(IDocument document) { */ protected void updateAffectedPositions(IDocument document, int[] positions, int offset) { - if (document != fDocument) + if (document != fDocument) { return; + } - if (positions.length == 0) + if (positions.length == 0) { return; + } for (int i= 0; i < positions.length; i++) { PositionReference r= fOverlappingPositionReferences.get(i); - if (r.refersToOffset()) + if (r.refersToOffset()) { r.setOffset(offset + positions[i]); - else + } else { r.setLength((offset + positions[i]) - r.getOffset()); + } Position p= r.getPosition(); String category= r.getCategory(); if (!document.containsPosition(category, p.offset, p.length)) { try { - if (positionAboutToBeAdded(document, category, p)) + if (positionAboutToBeAdded(document, category, p)) { document.addPosition(r.getCategory(), p); + } } catch (BadPositionCategoryException x) { // can not happen } catch (BadLocationException x) { @@ -758,8 +773,9 @@ private String getIndentation(int offset) { int end= start; char c= fDocument.getChar(end); - while ('\t' == c || ' ' == c) + while ('\t' == c || ' ' == c) { c= fDocument.getChar(++end); + } return fDocument.get(start, end - start); } catch (BadLocationException x) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java index e8e0aa4a70f..04646991187 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java @@ -87,8 +87,9 @@ protected final boolean notDeleted() { character= fDocument.getChar(offset++); } - if (moved) + if (moved) { offset--; + } } catch (BadLocationException exception) { // Can not happen @@ -249,13 +250,15 @@ protected void formatSlaves(final IFormattingContext context, final IDocument do final ITypedRegion[] partitions= TextUtilities.computePartitioning(document, fPartitioning, offset, length, false); - if (!fType.equals(partitions[0].getType())) + if (!fType.equals(partitions[0].getType())) { partitions[0]= TextUtilities.getPartition(document, fPartitioning, partitions[0].getOffset(), false); + } if (partitions.length > 1) { - if (!fType.equals(partitions[partitions.length - 1].getType())) + if (!fType.equals(partitions[partitions.length - 1].getType())) { partitions[partitions.length - 1]= TextUtilities.getPartition(document, fPartitioning, partitions[partitions.length - 1].getOffset(), false); + } } String type= null; @@ -268,8 +271,9 @@ protected void formatSlaves(final IFormattingContext context, final IDocument do partition= partitions[index]; type= partition.getType(); - if (!fType.equals(type)) + if (!fType.equals(type)) { formatSlave(context, document, partition.getOffset(), partition.getLength(), type); + } } } catch (BadLocationException exception) { @@ -315,7 +319,8 @@ public final void setMasterStrategy(final IFormattingStrategy strategy) { */ public final void setSlaveStrategy(final IFormattingStrategy strategy, final String type) { Assert.isTrue(strategy instanceof IFormattingStrategyExtension); - if (!fType.equals(type)) + if (!fType.equals(type)) { fSlaves.put(type, strategy); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java index 51d0f61fc32..0364168fa2f 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java @@ -44,8 +44,9 @@ public abstract class AbstractHyperlinkDetector implements IHyperlinkDetector, I */ public final void setContext(IAdaptable context) throws IllegalStateException, IllegalArgumentException { Assert.isLegal(context != null); - if (fContext != null) + if (fContext != null) { throw new IllegalStateException(); + } fContext= context; } @@ -65,8 +66,9 @@ public void dispose() { */ protected final T getAdapter(Class adapterClass) { Assert.isLegal(adapterClass != null); - if (fContext != null) + if (fContext != null) { return fContext.getAdapter(adapterClass); + } return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/DefaultHyperlinkPresenter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/DefaultHyperlinkPresenter.java index 73cc24675d7..95ec25c7122 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/DefaultHyperlinkPresenter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/DefaultHyperlinkPresenter.java @@ -167,18 +167,21 @@ public void install(ITextViewer textViewer) { Assert.isNotNull(textViewer); fTextViewer= textViewer; fTextViewer.addTextInputListener(this); - if (fTextViewer instanceof ITextViewerExtension4) + if (fTextViewer instanceof ITextViewerExtension4) { ((ITextViewerExtension4)fTextViewer).addTextPresentationListener(this); + } if (fPreferenceStore != null) { fIsUsingNativeLinkColor= fPreferenceStore.getBoolean(HYPERLINK_COLOR_SYSTEM_DEFAULT); - if (!fIsUsingNativeLinkColor) + if (!fIsUsingNativeLinkColor) { fColor= createColorFromPreferenceStore(); + } fPreferenceStore.addPropertyChangeListener(this); } else if (fRGB != null) { StyledText text= fTextViewer.getTextWidget(); - if (text != null && !text.isDisposed()) + if (text != null && !text.isDisposed()) { fColor= new Color(text.getDisplay(), fRGB); + } } } @@ -186,15 +189,17 @@ public void install(ITextViewer textViewer) { public void uninstall() { fTextViewer.removeTextInputListener(this); IDocument document= fTextViewer.getDocument(); - if (document != null) + if (document != null) { document.removeDocumentListener(this); + } if (fColor != null) { fColor= null; } - if (fTextViewer instanceof ITextViewerExtension4) + if (fTextViewer instanceof ITextViewerExtension4) { ((ITextViewerExtension4)fTextViewer).removeTextPresentationListener(this); + } fTextViewer= null; if (fPreferenceStore != null) { @@ -217,13 +222,15 @@ public void setColor(Color color) { @Override public void applyTextPresentation(TextPresentation textPresentation) { - if (fActiveRegion == null) + if (fActiveRegion == null) { return; + } IRegion region= textPresentation.getExtent(); if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset()) { Color color= null; - if (!fIsUsingNativeLinkColor) + if (!fIsUsingNativeLinkColor) { color= fColor; + } StyleRange styleRange= new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), color, null); styleRange.underlineStyle= SWT.UNDERLINE_LINK; styleRange.underline= true; @@ -233,37 +240,42 @@ public void applyTextPresentation(TextPresentation textPresentation) { private void highlightRegion(IRegion region) { - if (region.equals(fActiveRegion)) + if (region.equals(fActiveRegion)) { return; + } repairRepresentation(); StyledText text= fTextViewer.getTextWidget(); - if (text == null || text.isDisposed()) + if (text == null || text.isDisposed()) { return; + } // Invalidate region ==> apply text presentation fActiveRegion= region; - if (fTextViewer instanceof ITextViewerExtension2) + if (fTextViewer instanceof ITextViewerExtension2) { ((ITextViewerExtension2)fTextViewer).invalidateTextPresentation(region.getOffset(), region.getLength()); - else + } else { fTextViewer.invalidateTextPresentation(); + } } private void repairRepresentation() { - if (fActiveRegion == null) + if (fActiveRegion == null) { return; + } int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); fActiveRegion= null; // Invalidate ==> remove applied text presentation - if (fTextViewer instanceof ITextViewerExtension2) + if (fTextViewer instanceof ITextViewerExtension2) { ((ITextViewerExtension2) fTextViewer).invalidateTextPresentation(offset, length); - else + } else { fTextViewer.invalidateTextPresentation(); + } } @@ -299,16 +311,18 @@ public void documentChanged(DocumentEvent event) { @Override public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { - if (oldInput == null) + if (oldInput == null) { return; + } hideHyperlinks(); oldInput.removeDocumentListener(this); } @Override public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - if (newInput == null) + if (newInput == null) { return; + } newInput.addDocumentListener(this); } @@ -320,20 +334,23 @@ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { */ private Color createColorFromPreferenceStore() { StyledText textWidget= fTextViewer.getTextWidget(); - if (textWidget == null || textWidget.isDisposed()) + if (textWidget == null || textWidget.isDisposed()) { return null; + } RGB rgb= null; if (fPreferenceStore.contains(HYPERLINK_COLOR)) { - if (fPreferenceStore.isDefault(HYPERLINK_COLOR)) + if (fPreferenceStore.isDefault(HYPERLINK_COLOR)) { rgb= PreferenceConverter.getDefaultColor(fPreferenceStore, HYPERLINK_COLOR); - else + } else { rgb= PreferenceConverter.getColor(fPreferenceStore, HYPERLINK_COLOR); + } - if (rgb != null) + if (rgb != null) { return new Color(textWidget.getDisplay(), rgb); + } } return null; @@ -348,8 +365,9 @@ public void propertyChange(PropertyChangeEvent event) { if (HYPERLINK_COLOR_SYSTEM_DEFAULT.equals(event.getProperty())) { fIsUsingNativeLinkColor= fPreferenceStore.getBoolean(HYPERLINK_COLOR_SYSTEM_DEFAULT); - if (!fIsUsingNativeLinkColor && fColor == null) + if (!fIsUsingNativeLinkColor && fColor == null) { fColor= createColorFromPreferenceStore(); + } return; } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java index 9c29c407006..4fbc079cc60 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java @@ -164,8 +164,9 @@ public void install(ITextViewer textViewer, IHyperlinkPresenter hyperlinkPresent setHyperlinkStateMask(eventStateMask); StyledText text= fTextViewer.getTextWidget(); - if (text == null || text.isDisposed()) + if (text == null || text.isDisposed()) { return; + } text.getDisplay().addFilter(SWT.KeyUp, this); text.addKeyListener(this); @@ -190,9 +191,9 @@ public void install(ITextViewer textViewer, IHyperlinkPresenter hyperlinkPresent */ public void setHyperlinkDetectors(IHyperlinkDetector[] hyperlinkDetectors) { Assert.isTrue(hyperlinkDetectors != null && hyperlinkDetectors.length > 0); - if (fHyperlinkDetectors == null) + if (fHyperlinkDetectors == null) { fHyperlinkDetectors= hyperlinkDetectors; - else { + } else { synchronized (fHyperlinkDetectors) { fHyperlinkDetectors= hyperlinkDetectors; } @@ -255,8 +256,9 @@ protected void deactivate() { */ protected IHyperlink[] findHyperlinks() { int offset= getCurrentTextOffset(); - if (offset == -1) + if (offset == -1) { return null; + } IRegion region= new Region(offset, 0); return findHyperlinks(region); @@ -273,49 +275,57 @@ private IHyperlink[] findHyperlinks(IRegion region) { List allHyperlinks= new ArrayList<>(fHyperlinkDetectors.length * 2); synchronized (fHyperlinkDetectors) { for (IHyperlinkDetector detector : fHyperlinkDetectors) { - if (detector == null) + if (detector == null) { continue; + } if (detector instanceof IHyperlinkDetectorExtension2) { int stateMask= ((IHyperlinkDetectorExtension2)detector).getStateMask(); - if (stateMask != -1 && stateMask != fActiveHyperlinkStateMask) + if (stateMask != -1 && stateMask != fActiveHyperlinkStateMask) { continue; - else if (stateMask == -1 && fActiveHyperlinkStateMask != fHyperlinkStateMask) - continue; - } else if (fActiveHyperlinkStateMask != fHyperlinkStateMask) + } else if (stateMask == -1 && fActiveHyperlinkStateMask != fHyperlinkStateMask) { + continue; + } + } else if (fActiveHyperlinkStateMask != fHyperlinkStateMask) { continue; + } boolean canShowMultipleHyperlinks= fHyperlinkPresenter.canShowMultipleHyperlinks(); IHyperlink[] hyperlinks= detector.detectHyperlinks(fTextViewer, region, canShowMultipleHyperlinks); - if (hyperlinks == null) + if (hyperlinks == null) { continue; + } Assert.isLegal(hyperlinks.length > 0); if (fDetectionStrategy == FIRST) { - if (hyperlinks.length == 1) + if (hyperlinks.length == 1) { return hyperlinks; + } return new IHyperlink[] {hyperlinks[0]}; } allHyperlinks.addAll(Arrays.asList(hyperlinks)); } } - if (allHyperlinks.isEmpty()) + if (allHyperlinks.isEmpty()) { return null; + } if (fDetectionStrategy != ALL) { int maxLength= computeLongestHyperlinkLength(allHyperlinks); Iterator iter= new ArrayList<>(allHyperlinks).iterator(); while (iter.hasNext()) { IHyperlink hyperlink= iter.next(); - if (hyperlink.getHyperlinkRegion().getLength() < maxLength) + if (hyperlink.getHyperlinkRegion().getLength() < maxLength) { allHyperlinks.remove(hyperlink); + } } } - if (fDetectionStrategy == LONGEST_REGION_FIRST) + if (fDetectionStrategy == LONGEST_REGION_FIRST) { return new IHyperlink[] {allHyperlinks.get(0)}; + } return allHyperlinks.toArray(new IHyperlink[allHyperlinks.size()]); @@ -333,8 +343,9 @@ protected int computeLongestHyperlinkLength(List hyperlink int length= Integer.MIN_VALUE; while (iter.hasNext()) { IRegion region= iter.next().getHyperlinkRegion(); - if (region.getLength() < length) + if (region.getLength() < length) { continue; + } length= region.getLength(); } return length; @@ -375,13 +386,15 @@ public void mouseDoubleClick(MouseEvent e) { public void mouseDown(MouseEvent event) { if (fHyperlinkPresenter instanceof IHyperlinkPresenterExtension) { - if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) + if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) { return; + } } if (!isRegisteredStateMask(event.stateMask)) { - if (fActive) + if (fActive) { deactivate(); + } return; } @@ -417,25 +430,29 @@ public void mouseUp(MouseEvent e) { return; } - if (e.button != 1) + if (e.button != 1) { fActiveHyperlinks= null; + } deactivate(); - if (fActiveHyperlinks != null) + if (fActiveHyperlinks != null) { fActiveHyperlinks[0].open(); + } } @Override public void mouseMove(MouseEvent event) { if (fHyperlinkPresenter instanceof IHyperlinkPresenterExtension) { - if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) + if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) { return; + } } if (!isRegisteredStateMask(event.stateMask)) { - if (fActive) + if (fActive) { deactivate(); + } return; } @@ -466,14 +483,16 @@ public void mouseMove(MouseEvent event) { * @since 3.3 */ private boolean isRegisteredStateMask(int stateMask) { - if (stateMask == fHyperlinkStateMask) + if (stateMask == fHyperlinkStateMask) { return true; + } synchronized (fHyperlinkDetectors) { for (IHyperlinkDetector fHyperlinkDetector : fHyperlinkDetectors) { if (fHyperlinkDetector instanceof IHyperlinkDetectorExtension2) { - if (stateMask == ((IHyperlinkDetectorExtension2)fHyperlinkDetector).getStateMask()) + if (stateMask == ((IHyperlinkDetectorExtension2)fHyperlinkDetector).getStateMask()) { return true; + } } } } @@ -496,8 +515,9 @@ public void handleEvent(Event event) { @Override public void textChanged(TextEvent event) { - if (event.getDocumentEvent() != null) + if (event.getDocumentEvent() != null) { deactivate(); + } } /** @@ -508,8 +528,9 @@ public void textChanged(TextEvent event) { @Override public void mouseExit(MouseEvent e) { if (fHyperlinkPresenter instanceof IHyperlinkPresenterExtension) { - if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) + if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) { return; + } } deactivate(); } @@ -552,10 +573,11 @@ private boolean showHyperlinks(boolean takesFocusWhenVisible) { if (fActiveHyperlinks.length == 1 && takesFocusWhenVisible) { fActiveHyperlinks[0].open(); } else { - if (fHyperlinkPresenter instanceof IHyperlinkPresenterExtension2) + if (fHyperlinkPresenter instanceof IHyperlinkPresenterExtension2) { ((IHyperlinkPresenterExtension2)fHyperlinkPresenter).showHyperlinks(fActiveHyperlinks, takesFocusWhenVisible); - else + } else { fHyperlinkPresenter.showHyperlinks(fActiveHyperlinks); + } } return true; @@ -573,13 +595,15 @@ public boolean openHyperlink() { fActiveHyperlinkStateMask= fHyperlinkStateMask; if (fHyperlinkPresenter instanceof IHyperlinkPresenterExtension) { - if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) + if (!((IHyperlinkPresenterExtension)fHyperlinkPresenter).canHideHyperlinks()) { return false; + } } ITextSelection sel= (ITextSelection)((TextViewer)fTextViewer).getSelection(); int offset= sel.getOffset(); - if (offset == -1) + if (offset == -1) { return false; + } IRegion region= new Region(offset, 0); fActiveHyperlinks= findHyperlinks(region); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/MultipleHyperlinkPresenter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/MultipleHyperlinkPresenter.java index 2b828c79838..f768594788d 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/MultipleHyperlinkPresenter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/MultipleHyperlinkPresenter.java @@ -122,8 +122,9 @@ private static final class LinkLabelProvider extends ColumnLabelProvider { public String getText(Object element) { IHyperlink link= (IHyperlink)element; String text= link.getHyperlinkText(); - if (text != null) + if (text != null) { return text; + } return HyperlinkMessages.getString("LinkListInformationControl.unknownLink"); //$NON-NLS-1$ } } @@ -207,11 +208,13 @@ public Point computeSizeHint() { Point preferedSize= getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point constraints= getSizeConstraints(); - if (constraints == null) + if (constraints == null) { return preferedSize; + } - if (fTable.getVerticalBar() == null || fTable.getHorizontalBar() == null) + if (fTable.getVerticalBar() == null || fTable.getHorizontalBar() == null) { return Geometry.min(constraints, preferedSize); + } int scrollBarWidth= fTable.getVerticalBar().getSize().x; int scrollBarHeight= fTable.getHorizontalBar().getSize().y; @@ -335,17 +338,20 @@ public void widgetDefaultSelected(SelectionEvent e) { fTable.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { - if (fTable.getSelectionCount() < 1) + if (fTable.getSelectionCount() < 1) { return; + } - if (e.button != 1) + if (e.button != 1) { return; + } if (fTable.equals(e.getSource())) { Object o= fTable.getItem(new Point(e.x, e.y)); TableItem selection= fTable.getSelection()[0]; - if (selection.equals(o)) + if (selection.equals(o)) { openSelectedLink(); + } } } }); @@ -366,8 +372,9 @@ public boolean hasContents() { * Opens the currently selected link. */ private void openSelectedLink() { - if (fTable.getSelectionCount() < 1) + if (fTable.getSelectionCount() < 1) { return; + } TableItem selection= fTable.getSelection()[0]; IHyperlink link= (IHyperlink)selection.getData(); @@ -458,8 +465,9 @@ public void stop() { public void handleEvent(Event event) { switch (event.type) { case SWT.FocusOut: - if (!fControl.isFocusControl()) + if (!fControl.isFocusControl()) { disposeInformationControl(); + } break; case SWT.MouseMove: handleMouseMove(event); @@ -473,25 +481,30 @@ public void handleEvent(Event event) { * @param event the event */ private void handleMouseMove(Event event) { - if (!(event.widget instanceof Control)) + if (!(event.widget instanceof Control)) { return; + } - if (fControl.isFocusControl()) + if (fControl.isFocusControl()) { return; + } Control eventControl= (Control) event.widget; //transform coordinates to subject control: Point mouseLoc= event.display.map(eventControl, fSubjectControl, event.x, event.y); - if (fSubjectArea.contains(mouseLoc)) + if (fSubjectArea.contains(mouseLoc)) { return; + } - if (inKeepUpZone(mouseLoc.x, mouseLoc.y, ((IInformationControlExtension3) fControl).getBounds())) + if (inKeepUpZone(mouseLoc.x, mouseLoc.y, ((IInformationControlExtension3) fControl).getBounds())) { return; + } - if (!isTakingFocusWhenVisible()) + if (!isTakingFocusWhenVisible()) { hideInformationControl(); + } } /** @@ -512,13 +525,15 @@ private boolean inKeepUpZone(int x, int y, Rectangle controlBounds) { // ++-----------+-------+ // | totalBounds | // +--------------------+ - if (fSubjectArea.contains(x, y)) + if (fSubjectArea.contains(x, y)) { return true; + } Rectangle iControlBounds= fSubjectControl.getDisplay().map(null, fSubjectControl, controlBounds); Rectangle totalBounds= Geometry.copy(iControlBounds); - if (totalBounds.contains(x, y)) + if (totalBounds.contains(x, y)) { return true; + } int keepUpY= fSubjectArea.y + fSubjectArea.height; Rectangle alsoKeepUp= new Rectangle(fSubjectArea.x, keepUpY, fSubjectArea.width, totalBounds.y - keepUpY); @@ -532,8 +547,9 @@ public void keyPressed(KeyEvent e) { @Override public void keyReleased(KeyEvent e) { - if (!isTakingFocusWhenVisible()) + if (!isTakingFocusWhenVisible()) { hideInformationControl(); + } } @Override @@ -609,8 +625,9 @@ protected Point computeInformationControlLocation(Rectangle subjectArea, Point c Point result= super.computeInformationControlLocation(subjectArea, controlSize); Point cursorLocation= fTextViewer.getTextWidget().getDisplay().getCursorLocation(); - if (isTakingFocusWhenVisible() || cursorLocation.x <= result.x + controlSize.x) + if (isTakingFocusWhenVisible() || cursorLocation.x <= result.x + controlSize.x) { return result; + } result.x= cursorLocation.x + 20 - controlSize.x; return result; @@ -675,8 +692,9 @@ public boolean requestWidgetToken(IWidgetTokenOwner owner) { @Override public boolean requestWidgetToken(IWidgetTokenOwner owner, int priority) { - if (priority < WIDGET_TOKEN_PRIORITY) + if (priority < WIDGET_TOKEN_PRIORITY) { return false; + } hideInformationControl(); return true; @@ -784,8 +802,9 @@ public void showHyperlinks(IHyperlink[] activeHyperlinks, boolean takesFocusWhen fSubjectRegion= null; fHyperlinks= activeHyperlinks; - if (activeHyperlinks.length == 1) + if (activeHyperlinks.length == 1) { return; + } int start= activeHyperlinks[0].getHyperlinkRegion().getOffset(); int end= start + activeHyperlinks[0].getHyperlinkRegion().getLength(); @@ -811,8 +830,9 @@ public void showHyperlinks(IHyperlink[] activeHyperlinks, boolean takesFocusWhen */ private void setCaret() { Point selectedRange= fTextViewer.getSelectedRange(); - if (fCursorOffset != -1 && !(fSubjectRegion.getOffset() <= selectedRange.x && selectedRange.x + selectedRange.y <= fSubjectRegion.getOffset() + fSubjectRegion.getLength())) + if (fCursorOffset != -1 && !(fSubjectRegion.getOffset() <= selectedRange.x && selectedRange.x + selectedRange.y <= fSubjectRegion.getOffset() + fSubjectRegion.getLength())) { fTextViewer.setSelectedRange(fCursorOffset, 0); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlink.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlink.java index b5442cac7af..4a101f28964 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlink.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlink.java @@ -30,8 +30,8 @@ */ public class URLHyperlink implements IHyperlink { - private String fURLString; - private IRegion fRegion; + private final String fURLString; + private final IRegion fRegion; /** * Creates a new URL hyperlink. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlinkDetector.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlinkDetector.java index dd2b2836be5..5fee530004a 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlinkDetector.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/URLHyperlinkDetector.java @@ -53,16 +53,18 @@ public URLHyperlinkDetector(ITextViewer textViewer) { @Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { - if (region == null || textViewer == null) + if (region == null || textViewer == null) { return null; + } IDocument document= textViewer.getDocument(); int offset= region.getOffset(); String urlString= null; - if (document == null) + if (document == null) { return null; + } IRegion lineInfo; String line; @@ -89,10 +91,12 @@ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boo do { urlOffsetInLine--; ch= ' '; - if (urlOffsetInLine > -1) + if (urlOffsetInLine > -1) { ch= line.charAt(urlOffsetInLine); - if (ch == '"' || ch == '\'') + } + if (ch == '"' || ch == '\'') { quote= ch; + } } while (Character.isUnicodeIdentifierStart(ch)); urlOffsetInLine++; // Handle prefixes like "scm:https://foo": scan further back @@ -129,21 +133,24 @@ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boo urlSeparatorOffset= line.indexOf("://", afterSeparator); //$NON-NLS-1$ } - if (urlSeparatorOffset < 0) + if (urlSeparatorOffset < 0) { return null; + } if (quote != 0) { int endOffset= -1; int nextQuote= line.indexOf(quote, urlOffsetInLine); int nextWhitespace= line.indexOf(' ', urlOffsetInLine); - if (nextQuote != -1 && nextWhitespace != -1) + if (nextQuote != -1 && nextWhitespace != -1) { endOffset= Math.min(nextQuote, nextWhitespace); - else if (nextQuote != -1) + } else if (nextQuote != -1) { endOffset= nextQuote; - else if (nextWhitespace != -1) + } else if (nextWhitespace != -1) { endOffset= nextWhitespace; - if (endOffset != -1) + } + if (endOffset != -1) { urlLength= endOffset - urlOffsetInLine; + } } if (urlOffsetInLine + urlLength == urlSeparatorOffset + 3) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java index 226adec7c62..b0ecdc63d72 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java @@ -106,8 +106,9 @@ public void setInformationControl(IInformationControl control) { @Override public void start(Rectangle informationArea) { - if (fIsActive) + if (fIsActive) { return; + } fIsActive= true; if (fSubjectControl != null && !fSubjectControl.isDisposed()) { @@ -117,8 +118,9 @@ public void start(Rectangle informationArea) { fSubjectControl.addKeyListener(this); } - if (fInformationControlToClose != null) + if (fInformationControlToClose != null) { fInformationControlToClose.addFocusListener(this); + } fTextViewer.addViewportListener(this); } @@ -126,14 +128,16 @@ public void start(Rectangle informationArea) { @Override public void stop() { - if (!fIsActive) + if (!fIsActive) { return; + } fIsActive= false; fTextViewer.removeViewportListener(this); - if (fInformationControlToClose != null) + if (fInformationControlToClose != null) { fInformationControlToClose.removeFocusListener(this); + } if (fSubjectControl != null && !fSubjectControl.isDisposed()) { fSubjectControl.removeControlListener(this); @@ -176,8 +180,9 @@ public void focusLost(FocusEvent e) { Display d= fSubjectControl.getDisplay(); // Without the asyncExec, mouse clicks to the workbench window are swallowed. d.asyncExec(() -> { - if (fInformationControlToClose == null || !fInformationControlToClose.isFocusControl()) + if (fInformationControlToClose == null || !fInformationControlToClose.isFocusControl()) { hideInformationControl(); + } }); } @@ -255,19 +260,22 @@ public void setInformationProvider(IInformationProvider provider, String content Assert.isNotNull(contentType); - if (fProviders == null) + if (fProviders == null) { fProviders= new HashMap<>(); + } - if (provider == null) + if (provider == null) { fProviders.remove(contentType); - else + } else { fProviders.put(contentType, provider); + } } @Override public IInformationProvider getInformationProvider(String contentType) { - if (fProviders == null) + if (fProviders == null) { return null; + } return fProviders.get(contentType); } @@ -286,8 +294,9 @@ public void setOffset(int offset) { protected void computeInformation() { int offset= fOffset < 0 ? fTextViewer.getSelectedRange().x : fOffset; - if (offset == -1) + if (offset == -1) { return; + } fOffset= -1; @@ -297,12 +306,14 @@ protected void computeInformation() { provider= getInformationProvider(contentType); } catch (BadLocationException x) { } - if (provider == null) + if (provider == null) { return; + } IRegion subject= provider.getSubject(fTextViewer, offset); - if (subject == null) + if (subject == null) { return; + } Object info; if (provider instanceof IInformationProviderExtension extension) { @@ -312,10 +323,11 @@ protected void computeInformation() { info= provider.getInformation(fTextViewer, subject); } - if (provider instanceof IInformationProviderExtension2) + if (provider instanceof IInformationProviderExtension2) { setCustomInformationControlCreator(((IInformationProviderExtension2) provider).getInformationPresenterControlCreator()); - else + } else { setCustomInformationControlCreator(null); + } setInformation(info, computeArea(subject)); } @@ -339,9 +351,9 @@ private Rectangle computeArea(IRegion region) { StyledText styledText= fTextViewer.getTextWidget(); Rectangle bounds; - if (end > 0 && start < end) + if (end > 0 && start < end) { bounds= styledText.getTextBounds(start, end - 1); - else { + } else { Point loc= styledText.getLocationAtOffset(start); bounds= new Rectangle(loc.x, loc.y, 0, styledText.getLineHeight(start)); } @@ -367,8 +379,9 @@ private IRegion modelRange2WidgetRange(IRegion region) { IRegion visibleRegion= fTextViewer.getVisibleRegion(); int start= region.getOffset() - visibleRegion.getOffset(); int end= start + region.getLength(); - if (end > visibleRegion.getLength()) + if (end > visibleRegion.getLength()) { end= visibleRegion.getLength(); + } return new Region(start, end - start); } @@ -387,14 +400,17 @@ public void uninstall() { @Override protected void showInformationControl(Rectangle subjectArea) { if (fTextViewer instanceof IWidgetTokenOwnerExtension extension && fTextViewer instanceof IWidgetTokenOwner) { - if (extension.requestWidgetToken(this, WIDGET_PRIORITY)) + if (extension.requestWidgetToken(this, WIDGET_PRIORITY)) { super.showInformationControl(subjectArea); + } } else if (fTextViewer instanceof IWidgetTokenOwner owner) { - if (owner.requestWidgetToken(this)) + if (owner.requestWidgetToken(this)) { super.showInformationControl(subjectArea); + } - } else + } else { super.showInformationControl(subjectArea); + } } @Override diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java index 4e6783ddc20..99d8fd3a870 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java @@ -183,7 +183,7 @@ public static abstract class LinkedModeUITarget implements ILinkedModeUIFocusLis private static final class EmptyTarget extends LinkedModeUITarget { - private ITextViewer fTextViewer; + private final ITextViewer fTextViewer; /** * @param viewer the viewer @@ -229,8 +229,9 @@ public void resume(LinkedModeModel model, int flags) { leave(flags); } else { connect(); - if ((flags & ILinkedModeListener.SELECT) != 0) + if ((flags & ILinkedModeListener.SELECT) != 0) { select(); + } ensureAnnotationModelInstalled(); redraw(); } @@ -357,8 +358,9 @@ public void shellDeactivated(ShellEvent e) { if (fIsActive && viewer instanceof IEditingSupportRegistry) { IEditingSupport[] helpers= ((IEditingSupportRegistry) viewer).getRegisteredSupports(); for (IEditingSupport helper : helpers) { - if (helper.ownsFocusShell()) + if (helper.ownsFocusShell()) { return; + } } } @@ -401,8 +403,9 @@ public void documentUndoNotification(DocumentUndoEvent event) { if (fFramePosition != null && viewer instanceof IEditingSupportRegistry) { IEditingSupport[] helpers= ((IEditingSupportRegistry) viewer).getRegisteredSupports(); for (IEditingSupport helper : helpers) { - if (helper.isOriginator(null, new Region(fFramePosition.getOffset(), fFramePosition.getLength()))) + if (helper.isOriginator(null, new Region(fFramePosition.getOffset(), fFramePosition.getLength()))) { return; + } } } @@ -433,8 +436,9 @@ public void documentAboutToBeChanged(DocumentEvent event) { if (fFramePosition != null && viewer instanceof IEditingSupportRegistry) { IEditingSupport[] helpers= ((IEditingSupportRegistry) viewer).getRegisteredSupports(); for (IEditingSupport helper : helpers) { - if (helper.isOriginator(null, new Region(fFramePosition.getOffset(), fFramePosition.getLength()))) + if (helper.isOriginator(null, new Region(fFramePosition.getOffset(), fFramePosition.getLength()))) { return; + } } } @@ -473,8 +477,9 @@ private class KeyListener implements VerifyKeyListener { @Override public void verifyKey(VerifyEvent event) { - if (!event.doit || !fIsEnabled) + if (!event.doit || !fIsEnabled) { return; + } Point selection= fCurrentTarget.getViewer().getSelectedRange(); int offset= selection.x; @@ -504,10 +509,11 @@ public void verifyKey(VerifyEvent event) { break; } - if (event.stateMask == SWT.SHIFT) + if (event.stateMask == SWT.SHIFT) { previous(); - else + } else { next(); + } event.doit= false; break; @@ -551,8 +557,9 @@ private boolean controlUndoBehavior(int offset, int length) { if (position != null) { // if the last position is not the same and there is an open change: close it. - if (!position.equals(fPreviousPosition)) + if (!position.equals(fPreviousPosition)) { endCompoundChangeIfNeeded(); + } beginCompoundChangeIfNeeded(); } @@ -589,11 +596,13 @@ public void selectionChanged(SelectionChangedEvent event) { if (offset >= 0 && length >= 0) { LinkedPosition find= new LinkedPosition(doc, offset, length, LinkedPositionGroup.NO_STOP); LinkedPosition pos= fModel.findPosition(find); - if (pos == null && fExitPosition != null && fExitPosition.includes(find)) + if (pos == null && fExitPosition != null && fExitPosition.includes(find)) { pos= fExitPosition; + } - if (pos != null) + if (pos != null) { switchPosition(pos, false, false); + } } } } @@ -624,18 +633,18 @@ public void proposalChosen(ICompletionProposal proposal) { /* Our team of event listeners */ /** The shell listener. */ - private Closer fCloser= new Closer(); + private final Closer fCloser= new Closer(); /** The linked mode listener. */ - private ILinkedModeListener fLinkedListener= new ExitListener(); + private final ILinkedModeListener fLinkedListener= new ExitListener(); /** The selection listener. */ - private MySelectionListener fSelectionListener= new MySelectionListener(); + private final MySelectionListener fSelectionListener= new MySelectionListener(); /** The content assist listener. */ - private ProposalListener fProposalListener= new ProposalListener(); + private final ProposalListener fProposalListener= new ProposalListener(); /** * The document listener. * @since 3.1 */ - private IDocumentListener fDocumentListener= new DocumentListener(); + private final IDocumentListener fDocumentListener= new DocumentListener(); /** The last caret position, used by fCaretListener. */ private final Position fCaretPosition= new Position(0, 0); @@ -652,7 +661,7 @@ public void proposalChosen(ICompletionProposal proposal) { /** State indicator to prevent multiple invocation of leave. */ private boolean fIsActive= false; /** The position updater for the exit position. */ - private IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(getCategory()); + private final IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(getCategory()); /** Whether to show context info. */ private boolean fDoContextInfo= false; /** Whether we have begun a compound change, but not yet closed. */ @@ -660,7 +669,7 @@ public void proposalChosen(ICompletionProposal proposal) { /** The position listener. */ private ILinkedModeUIFocusListener fPositionListener= new EmtpyFocusListener(); - private IAutoEditStrategy fAutoEditVetoer= (document, command) -> { + private final IAutoEditStrategy fAutoEditVetoer= (document, command) -> { // invalidate the change to ensure that the change is performed on the document only. if (fModel.anyPositionContains(command.offset)) { command.doit= false; @@ -789,13 +798,15 @@ public void setExitPosition(LinkedModeUITarget target, int offset, int length, i } IDocument doc= target.getViewer().getDocument(); - if (doc == null) + if (doc == null) { return; + } fExitPosition= new LinkedPosition(doc, offset, length, sequence); doc.addPosition(fExitPosition); // gets removed in leave() - if (sequence != LinkedPositionGroup.NO_STOP) + if (sequence != LinkedPositionGroup.NO_STOP) { fIterator.addPosition(fExitPosition); + } } @@ -823,13 +834,15 @@ public void setExitPosition(ITextViewer viewer, int offset, int length, int sequ * @param mode the new cycling mode. */ public void setCyclingMode(Object mode) { - if (mode != CYCLE_ALWAYS && mode != CYCLE_NEVER && mode != CYCLE_WHEN_NO_PARENT) + if (mode != CYCLE_ALWAYS && mode != CYCLE_NEVER && mode != CYCLE_WHEN_NO_PARENT) { throw new IllegalArgumentException(); + } - if (mode == CYCLE_ALWAYS || mode == CYCLE_WHEN_NO_PARENT && !fModel.isNested()) + if (mode == CYCLE_ALWAYS || mode == CYCLE_WHEN_NO_PARENT && !fModel.isNested()) { fIterator.setCycling(true); - else + } else { fIterator.setCycling(false); + } } void next() { @@ -843,9 +856,10 @@ void next() { void previous() { if (fIterator.hasPrevious(fFramePosition)) { switchPosition(fIterator.previous(fFramePosition), true, true); - } else + } else { // dont't update caret, but rather select the current frame // dont't update caret, but rather select the current frame leave(ILinkedModeListener.SELECT); + } } private void triggerContextInfo() { @@ -869,11 +883,13 @@ private void triggerContentAssist() { private void switchPosition(LinkedPosition pos, boolean select, boolean showProposals) { Assert.isNotNull(pos); - if (pos.equals(fFramePosition)) + if (pos.equals(fFramePosition)) { return; + } - if (fFramePosition != null && fCurrentTarget != null) + if (fFramePosition != null && fCurrentTarget != null) { fPositionListener.linkingFocusLost(fFramePosition, fCurrentTarget); + } // undo endCompoundChangeIfNeeded(); @@ -885,21 +901,25 @@ private void switchPosition(LinkedPosition pos, boolean select, boolean showProp switchViewer(oldDoc, newDoc, pos); fFramePosition= pos; - if (select) + if (select) { select(); - if (fFramePosition == fExitPosition && !fIterator.isCycling()) + } + if (fFramePosition == fExitPosition && !fIterator.isCycling()) { leave(ILinkedModeListener.NONE); - else { + } else { redraw(); // redraw new position ensureAnnotationModelInstalled(); } - if (showProposals) + if (showProposals) { triggerContentAssist(); - if (fFramePosition != fExitPosition && fDoContextInfo) + } + if (fFramePosition != fExitPosition && fDoContextInfo) { triggerContextInfo(); + } - if (fFramePosition != null && fCurrentTarget != null) + if (fFramePosition != null && fCurrentTarget != null) { fPositionListener.linkingFocusGained(fFramePosition, fCurrentTarget); + } } @@ -933,8 +953,9 @@ private void switchViewer(IDocument oldDoc, IDocument newDoc, LinkedPosition pos if (oldDoc != newDoc) { // redraw current document with new position before switching viewer - if (fCurrentTarget.fAnnotationModel != null) + if (fCurrentTarget.fAnnotationModel != null) { fCurrentTarget.fAnnotationModel.switchToPosition(fModel, pos); + } LinkedModeUITarget target= null; for (LinkedModeUITarget fTarget : fTargets) { @@ -952,8 +973,9 @@ private void switchViewer(IDocument oldDoc, IDocument newDoc, LinkedPosition pos target.linkingFocusLost(fFramePosition, target); connect(); ensureAnnotationModelInstalled(); - if (fCurrentTarget != null) + if (fCurrentTarget != null) { fCurrentTarget.linkingFocusGained(pos, fCurrentTarget); + } } } } @@ -970,8 +992,9 @@ private void select() { } private void redraw() { - if (fCurrentTarget.fAnnotationModel != null) + if (fCurrentTarget.fAnnotationModel != null) { fCurrentTarget.fAnnotationModel.switchToPosition(fModel, fFramePosition); + } } private void connect() { @@ -979,14 +1002,16 @@ private void connect() { ITextViewer viewer= fCurrentTarget.getViewer(); Assert.isNotNull(viewer); fCurrentTarget.fWidget= viewer.getTextWidget(); - if (fCurrentTarget.fWidget == null) + if (fCurrentTarget.fWidget == null) { leave(ILinkedModeListener.EXIT_ALL); + } if (fCurrentTarget.fKeyListener == null) { fCurrentTarget.fKeyListener= new KeyListener(); ((ITextViewerExtension) viewer).prependVerifyKeyListener(fCurrentTarget.fKeyListener); - } else + } else { fCurrentTarget.fKeyListener.setEnabled(true); + } registerAutoEditVetoer(viewer); @@ -997,8 +1022,9 @@ private void connect() { showSelection(); fCurrentTarget.fShell= fCurrentTarget.fWidget.getShell(); - if (fCurrentTarget.fShell == null) + if (fCurrentTarget.fShell == null) { leave(ILinkedModeListener.EXIT_ALL); + } fCurrentTarget.fShell.addShellListener(fCloser); fAssistant.install(viewer); @@ -1018,12 +1044,13 @@ private void connect() { */ private void showSelection() { final StyledText widget= fCurrentTarget.fWidget; - if (widget == null || widget.isDisposed()) + if (widget == null || widget.isDisposed()) { return; + } // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=132263 widget.getDisplay().asyncExec(() -> { - if (!widget.isDisposed()) + if (!widget.isDisposed()) { try { widget.showSelection(); } catch (IllegalArgumentException e) { @@ -1037,6 +1064,7 @@ private void showSelection() { * and ignore an IAE. */ } + } }); } @@ -1133,8 +1161,9 @@ private void disconnect() { Shell shell= fCurrentTarget.fShell; fCurrentTarget.fShell= null; - if (shell != null && !shell.isDisposed()) + if (shell != null && !shell.isDisposed()) { shell.removeShellListener(fCloser); + } // this one is asymmetric: we don't install the model in // connect, but leave it to its callers to ensure they @@ -1145,8 +1174,9 @@ private void disconnect() { // don't remove the verify key listener to let it keep its position // in the listener queue - if (fCurrentTarget.fKeyListener != null) + if (fCurrentTarget.fKeyListener != null) { fCurrentTarget.fKeyListener.setEnabled(false); + } ((IPostSelectionProvider) viewer).removePostSelectionChangedListener(fSelectionListener); @@ -1159,18 +1189,21 @@ private void disconnect() { } void leave(final int flags) { - if (!fIsActive) + if (!fIsActive) { return; + } fIsActive= false; endCompoundChangeIfNeeded(); Display display= null; - if (fCurrentTarget.fWidget != null && !fCurrentTarget.fWidget.isDisposed()) + if (fCurrentTarget.fWidget != null && !fCurrentTarget.fWidget.isDisposed()) { display= fCurrentTarget.fWidget.getDisplay(); + } - if (fCurrentTarget.fAnnotationModel != null) + if (fCurrentTarget.fAnnotationModel != null) { fCurrentTarget.fAnnotationModel.removeAllAnnotations(); + } disconnect(); for (LinkedModeUITarget fTarget : fTargets) { @@ -1194,21 +1227,24 @@ void leave(final int flags) { } - if ((flags & ILinkedModeListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition && !fExitPosition.isDeleted()) + if ((flags & ILinkedModeListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition && !fExitPosition.isDeleted()) { switchPosition(fExitPosition, true, false); + } final List docs= new ArrayList<>(); for (LinkedModeUITarget fTarget : fTargets) { IDocument doc= fTarget.getViewer().getDocument(); - if (doc != null) + if (doc != null) { docs.add(doc); + } } fModel.stopForwarding(flags); Runnable runnable= () -> { - if (fExitPosition != null) + if (fExitPosition != null) { fExitPosition.getDocument().removePosition(fExitPosition); + } for (IDocument doc : docs) { doc.removePositionUpdater(fPositionUpdater); @@ -1220,12 +1256,13 @@ void leave(final int flags) { break; } } - if (uninstallCat) + if (uninstallCat) { try { doc.removePositionCategory(getCategory()); } catch (BadPositionCategoryException e) { // ignore } + } } fModel.exit(flags); }; @@ -1233,10 +1270,11 @@ void leave(final int flags) { // remove positions (both exit positions AND linked positions in the // model) asynchronously to make sure that the annotation painter // gets correct document offsets. - if (display != null) + if (display != null) { display.asyncExec(runnable); - else + } else { runnable.run(); + } } private void endCompoundChangeIfNeeded() { @@ -1263,10 +1301,12 @@ private void beginCompoundChangeIfNeeded() { * @return the currently selected region or null */ public IRegion getSelectedRegion() { - if (fFramePosition != null) + if (fFramePosition != null) { return new Region(fFramePosition.getOffset(), fFramePosition.getLength()); - if (fExitPosition != null) + } + if (fExitPosition != null) { return new Region(fExitPosition.getOffset(), fExitPosition.getLength()); + } return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java index cb65807185b..f4e95906b32 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java @@ -68,8 +68,9 @@ private void setFocusPosition(Position position) throws BadLocationException { if (position != null) { fFocusAnnotation= new Annotation(FOCUS_ANNOTATION_TYPE, false, ""); //$NON-NLS-1$ addAnnotation(fFocusAnnotation, position, false); - } else + } else { fFocusAnnotation= null; + } } } @@ -87,8 +88,9 @@ private void setExitPosition(Position position) throws BadLocationException { if (position != null) { fExitAnnotation= new Annotation(EXIT_ANNOTATION_TYPE, false, ""); //$NON-NLS-1$ addAnnotation(fExitAnnotation, position, false); - } else + } else { fExitAnnotation= null; + } } } @@ -100,8 +102,9 @@ private void setExitPosition(Position position) throws BadLocationException { * @throws BadLocationException in case any of the given positions is invalid */ private void setGroupPositions(List positions) throws BadLocationException { - if (!fMarkSlaves) + if (!fMarkSlaves) { return; + } // remove all positions which are already there // Algorithm: toRemove contains all mappings at first, but all that are in @@ -133,8 +136,9 @@ private void setGroupPositions(List positions) throws BadLocationExcep * @throws BadLocationException in case any of the given positions is invalid */ private void setTargetPositions(List positions) throws BadLocationException { - if (!fMarkTargets) + if (!fMarkTargets) { return; + } // remove all positions which are already there // Algorithm: toRemove contains all mappings at first, but all that are in @@ -169,30 +173,35 @@ private void setTargetPositions(List positions) throws BadLocationExce public void switchToPosition(LinkedModeModel env, LinkedPosition position) { if (fDocument == null || (position != null && getPosition(fFocusAnnotation) == position) || - (position == null && fFocusAnnotation == null)) + (position == null && fFocusAnnotation == null)) { return; + } LinkedPositionGroup linkedGroup= null; - if (position != null) + if (position != null) { linkedGroup= env.getGroupForPosition(position); + } List targets= new ArrayList<>(); targets.addAll(Arrays.asList(fTargets)); List group; - if (linkedGroup != null) + if (linkedGroup != null) { group= new ArrayList<>(Arrays.asList(linkedGroup.getPositions())); - else + } else { group= new ArrayList<>(); + } - if (position == null || !fDocument.equals(position.getDocument())) + if (position == null || !fDocument.equals(position.getDocument())) { // position is not valid if not in this document position= null; + } LinkedPosition exit= fExitPosition; - if (exit == null || !fDocument.equals(exit.getDocument())) + if (exit == null || !fDocument.equals(exit.getDocument())) { // position is not valid if not in this document exit= null; + } if (exit != null) { @@ -229,8 +238,9 @@ public void switchToPosition(LinkedModeModel env, LinkedPosition position) { private void prune(List list) { for (Iterator iter= list.iterator(); iter.hasNext();) { LinkedPosition pos= (LinkedPosition) iter.next(); - if (!pos.getDocument().equals(fDocument)) + if (!pos.getDocument().equals(fDocument)) { iter.remove(); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/ProposalPosition.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/ProposalPosition.java index 7686a844173..0c41ee90cde 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/ProposalPosition.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/ProposalPosition.java @@ -31,7 +31,7 @@ public class ProposalPosition extends LinkedPosition { /** * The proposals */ - private ICompletionProposal[] fProposals; + private final ICompletionProposal[] fProposals; /** * Creates a new instance. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java index 919157fa87f..55e81ebe6e3 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java @@ -43,8 +43,9 @@ private static class SequenceComparator implements Comparator { @Override public int compare(LinkedPosition p1, LinkedPosition p2) { int i= p1.getSequenceNumber() - p2.getSequenceNumber(); - if (i != 0) + if (i != 0) { return i; + } return p1.getOffset() - p2.getOffset(); } @@ -76,13 +77,14 @@ boolean hasNext(LinkedPosition current) { } private int getNextIndex(LinkedPosition current) { - if (current != null && fList.get(fIndex) != current) + if (current != null && fList.get(fIndex) != current) { return findNext(current); - else if (fIsCycling && fIndex == fSize - 1) + } else if (fIsCycling && fIndex == fSize - 1) { return 0; - else + } else { // default: increase // default: increase return fIndex + 1; + } } /** @@ -98,8 +100,9 @@ private int findNext(LinkedPosition current) { // if the position is in the iteration set, jump to the next one int index= fList.indexOf(current); if (index != -1) { - if (fIsCycling && index == fSize - 1) + if (fIsCycling && index == fSize - 1) { return 0; + } return index + 1; } @@ -108,17 +111,20 @@ private int findNext(LinkedPosition current) { // find the position that follows closest to the current position LinkedPosition found= null; for (LinkedPosition p : fList) { - if (p.offset > current.offset) - if (found == null || found.offset > p.offset) + if (p.offset > current.offset) { + if (found == null || found.offset > p.offset) { found= p; + } + } } if (found != null) { return fList.indexOf(found); } else if (fIsCycling) { return 0; - } else + } else { return fSize; + } } boolean hasPrevious(LinkedPosition current) { @@ -126,12 +132,13 @@ boolean hasPrevious(LinkedPosition current) { } private int getPreviousIndex(LinkedPosition current) { - if (current != null && fList.get(fIndex) != current) + if (current != null && fList.get(fIndex) != current) { return findPrevious(current); - else if (fIsCycling && fIndex == 0) + } else if (fIsCycling && fIndex == 0) { return fSize - 1; - else + } else { return fIndex - 1; + } } /** @@ -147,8 +154,9 @@ private int findPrevious(LinkedPosition current) { // if the position is in the iteration set, jump to the next one int index= fList.indexOf(current); if (index != -1) { - if (fIsCycling && index == 0) + if (fIsCycling && index == 0) { return fSize - 1; + } return index - 1; } @@ -157,27 +165,32 @@ private int findPrevious(LinkedPosition current) { // find the position that follows closest to the current position LinkedPosition found= null; for (LinkedPosition p : fList) { - if (p.offset < current.offset) - if (found == null || found.offset < p.offset) + if (p.offset < current.offset) { + if (found == null || found.offset < p.offset) { found= p; + } + } } if (found != null) { return fList.indexOf(found); } else if (fIsCycling) { return fSize - 1; - } else + } else { return -1; + } } LinkedPosition next(LinkedPosition current) { - if (!hasNext(current)) + if (!hasNext(current)) { throw new NoSuchElementException(); + } return fList.get(fIndex= getNextIndex(current)); } LinkedPosition previous(LinkedPosition current) { - if (!hasPrevious(current)) + if (!hasPrevious(current)) { throw new NoSuchElementException(); + } return fList.get(fIndex= getPreviousIndex(current)); } @@ -191,8 +204,9 @@ void addPosition(LinkedPosition position) { } void removePosition(Position position) { - if (fList.remove(position)) + if (fList.remove(position)) { fSize--; + } } /** diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java index 6e66e4a56ac..41724755c1b 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java @@ -124,10 +124,11 @@ public void inputDocumentChanged(IDocument oldDocument, IDocument newDocument) { @Override public void documentPartitioningChanged(IDocument document) { - if (!fDocumentChanging && fCachedRedrawState) + if (!fDocumentChanging && fCachedRedrawState) { processDamage(new Region(0, document.getLength()), document); - else + } else { fDocumentPartitioningChanged= true; + } } @Override @@ -143,8 +144,9 @@ public void documentPartitioningChanged(IDocument document, IRegion changedRegio @Override public void documentPartitioningChanged(DocumentPartitioningChangedEvent event) { IRegion changedRegion= event.getChangedRegion(getDocumentPartitioning()); - if (changedRegion != null) + if (changedRegion != null) { documentPartitioningChanged(event.getDocument(), changedRegion); + } } @Override @@ -181,8 +183,9 @@ public void documentChanged(DocumentEvent e) { public void textChanged(TextEvent e) { fCachedRedrawState= e.getViewerRedrawState(); - if (!fCachedRedrawState) - return; + if (!fCachedRedrawState) { + return; + } IRegion damage= null; IDocument document= null; @@ -211,8 +214,9 @@ public void textChanged(TextEvent e) { damage= getDamage(de, true); } - if (damage != null && document != null) + if (damage != null && document != null) { processDamage(damage, document); + } fDocumentPartitioningChanged= false; fChangedDocumentPartitions= null; @@ -248,11 +252,11 @@ protected IRegion widgetRegion2ModelRegion(TextEvent e) { /** The target viewer. */ private ITextViewer fViewer; /** The internal listener. */ - private InternalListener fInternalListener= new InternalListener(); + private final InternalListener fInternalListener= new InternalListener(); /** The name of the position category to track damage regions. */ - private String fPositionCategory; + private final String fPositionCategory; /** The position updated for the damage regions' position category. */ - private IPositionUpdater fPositionUpdater; + private final IPositionUpdater fPositionUpdater; /** The positions representing the damage regions. */ private TypedPosition fRememberedPosition; /** Flag indicating the receipt of a partitioning changed notification. */ @@ -309,13 +313,15 @@ public void setDamager(IPresentationDamager damager, String contentType) { Assert.isNotNull(contentType); - if (fDamagers == null) + if (fDamagers == null) { fDamagers= new HashMap<>(); + } - if (damager == null) + if (damager == null) { fDamagers.remove(contentType); - else + } else { fDamagers.put(contentType, damager); + } } /** @@ -330,13 +336,15 @@ public void setRepairer(IPresentationRepairer repairer, String contentType) { Assert.isNotNull(contentType); - if (fRepairers == null) + if (fRepairers == null) { fRepairers= new HashMap<>(); + } - if (repairer == null) + if (repairer == null) { fRepairers.remove(contentType); - else + } else { fRepairers.put(contentType, repairer); + } } @Override @@ -347,8 +355,9 @@ public void install(ITextViewer viewer) { fViewer.addTextInputListener(fInternalListener); IDocument document= viewer.getDocument(); - if (document != null) + if (document != null) { fInternalListener.inputDocumentChanged(null, document); + } } @Override @@ -362,8 +371,9 @@ public void uninstall() { @Override public IPresentationDamager getDamager(String contentType) { - if (fDamagers == null) + if (fDamagers == null) { return null; + } return fDamagers.get(contentType); } @@ -371,8 +381,9 @@ public IPresentationDamager getDamager(String contentType) { @Override public IPresentationRepairer getRepairer(String contentType) { - if (fRepairers == null) + if (fRepairers == null) { return null; + } return fRepairers.get(contentType); } @@ -431,8 +442,9 @@ protected TextPresentation createPresentation(IRegion damage, IDocument document ITypedRegion[] partitioning= TextUtilities.computePartitioning(document, getDocumentPartitioning(), damage.getOffset(), damage.getLength(), false); for (ITypedRegion r : partitioning) { IPresentationRepairer repairer= getRepairer(r.getType()); - if (repairer != null) + if (repairer != null) { repairer.createPresentation(presentation, r); + } } return presentation; @@ -469,12 +481,14 @@ private IRegion getDamage(DocumentEvent e, boolean optimize) { IRegion damage= null; try { int offset= e.getOffset(); - if (isDeletion) + if (isDeletion) { offset= Math.max(0, offset - 1); + } ITypedRegion partition= getPartition(e.getDocument(), offset); IPresentationDamager damager= getDamager(partition.getType()); - if (damager == null) + if (damager == null) { return null; + } IRegion r= damager.getDamageRegion(partition, e, fDocumentPartitioningChanged); @@ -516,22 +530,26 @@ private int getDamageEndOffset(DocumentEvent e) throws BadLocationException { int length= 0; if (e.getText() != null) { length= e.getText().length(); - if (length > 0) + if (length > 0) { -- length; + } } ITypedRegion partition= getPartition(d, e.getOffset() + length); int endOffset= partition.getOffset() + partition.getLength(); - if (endOffset == e.getOffset()) + if (endOffset == e.getOffset()) { return -1; + } int end= fRememberedPosition == null ? -1 : fRememberedPosition.getOffset() + fRememberedPosition.getLength(); - if (endOffset < end && end < d.getLength()) + if (endOffset < end && end < d.getLength()) { partition= getPartition(d, end); + } IPresentationDamager damager= getDamager(partition.getType()); - if (damager == null) + if (damager == null) { return -1; + } IRegion r= damager.getDamageRegion(partition, e, fDocumentPartitioningChanged); @@ -546,8 +564,9 @@ private int getDamageEndOffset(DocumentEvent e) throws BadLocationException { private void processDamage(IRegion damage, IDocument document) { if (damage != null && damage.getLength() > 0) { TextPresentation p= createPresentation(damage, document); - if (p != null) + if (p != null) { applyTextRegionCollection(p); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/quickassist/QuickAssistAssistant.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/quickassist/QuickAssistAssistant.java index 15ae59280b3..809b1bff94b 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/quickassist/QuickAssistAssistant.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/quickassist/QuickAssistAssistant.java @@ -56,7 +56,7 @@ protected void hide() { private static final class ContentAssistProcessor implements IContentAssistProcessor { - private IQuickAssistProcessor fQuickAssistProcessor; + private final IQuickAssistProcessor fQuickAssistProcessor; ContentAssistProcessor(IQuickAssistProcessor processor) { fQuickAssistProcessor= processor; @@ -65,8 +65,9 @@ private static final class ContentAssistProcessor implements IContentAssistProce @Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { // panic code - should not happen - if (!(viewer instanceof ISourceViewer)) + if (!(viewer instanceof ISourceViewer)) { return null; + } return fQuickAssistProcessor.computeQuickAssistProposals(new TextInvocationContext((ISourceViewer)viewer, offset, -1)); } @@ -98,7 +99,7 @@ public IContextInformationValidator getContextInformationValidator() { } - private QuickAssistAssistantImpl fQuickAssistAssistantImpl; + private final QuickAssistAssistantImpl fQuickAssistAssistantImpl; private IQuickAssistProcessor fQuickAssistProcessor; public QuickAssistAssistant() { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java index 0a9005113fa..52b54f3d743 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java @@ -67,8 +67,9 @@ public boolean isFirstStep() { public void setProgressMonitor(IProgressMonitor monitor) { fProgressMonitor= monitor; - if (!isLastStep()) + if (!isLastStep()) { fNextStep.setProgressMonitor(monitor); + } } @Override @@ -128,11 +129,13 @@ protected IReconcileResult[] convertToInputModel(IReconcileResult[] inputResults * @return an array with the merged reconcile results */ private IReconcileResult[] merge(IReconcileResult[] results1, IReconcileResult[] results2) { - if (results1 == null) + if (results1 == null) { return results2; + } - if (results2 == null) + if (results2 == null) { return results1; + } // XXX: not yet performance optimized Collection collection= new ArrayList<>(Arrays.asList(results1)); @@ -158,8 +161,9 @@ public void setPreviousStep(IReconcileStep step) { public void setInputModel(IReconcilableModel inputModel) { fInputModel= inputModel; - if (!isLastStep()) + if (!isLastStep()) { fNextStep.setInputModel(getModel()); + } } /** diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java index 19c8ab9ed26..2978a8b9ec9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconciler.java @@ -68,7 +68,7 @@ class BackgroundWorker implements Runnable { private boolean fStarted; - private String fName; + private final String fName; private boolean fIsAlive; @@ -103,8 +103,9 @@ public synchronized boolean isDirty() { public void cancel() { fCanceled= true; IProgressMonitor pm= fProgressMonitor; - if (pm != null) + if (pm != null) { pm.setCanceled(true); + } synchronized (fDirtyRegionQueue) { fDirtyRegionQueue.notifyAll(); } @@ -172,8 +173,9 @@ public void run() { delay(); - if (fCanceled) + if (fCanceled) { break; + } if (!isDirty()) { waitFinish= false; //signalWaitForFinish() was called but nothing todo @@ -265,8 +267,9 @@ public void documentAboutToBeChanged(DocumentEvent e) { public void documentChanged(DocumentEvent e) { if (fWorker.isActive() || !fWorker.isDirty() && fWorker.isAlive()) { - if (!fIsAllowedToModifyDocument && isRunningInReconcilerThread()) + if (!fIsAllowedToModifyDocument && isRunningInReconcilerThread()) { throw new UnsupportedOperationException("The reconciler thread is not allowed to modify the document"); //$NON-NLS-1$ + } aboutToBeReconciledInternal(); } @@ -274,11 +277,13 @@ public void documentChanged(DocumentEvent e) { * The second OR condition handles the case when the document * gets changed while still inside initialProcess(). */ - if (fWorker.isActive() || fWorker.isDirty() && fWorker.isAlive()) + if (fWorker.isActive() || fWorker.isDirty() && fWorker.isAlive()) { fProgressMonitor.setCanceled(true); + } - if (fIsIncrementalReconciler) + if (fIsIncrementalReconciler) { createDirtyRegion(e); + } fWorker.reset(); @@ -289,8 +294,9 @@ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput if (oldInput == fDocument) { - if (fDocument != null) + if (fDocument != null) { fDocument.removeDocumentListener(this); + } if (fIsIncrementalReconciler) { synchronized (fDirtyRegionQueue) { @@ -312,16 +318,18 @@ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { fDocument= newInput; - if (fDocument == null) + if (fDocument == null) { return; + } reconcilerDocumentChanged(fDocument); fDocument.addDocumentListener(this); - if (!fWorker.isDirty()) + if (!fWorker.isDirty()) { aboutToBeReconciledInternal(); + } startReconciling(); } @@ -479,8 +487,9 @@ public void install(ITextViewer textViewer) { fViewer= textViewer; synchronized (this) { - if (fWorker != null) + if (fWorker != null) { return; + } fWorker= new BackgroundWorker(getClass().getName()); } @@ -622,11 +631,13 @@ protected void forceReconciling() { if (fDocument != null) { - if (!fWorker.isDirty()&& fWorker.isAlive()) + if (!fWorker.isDirty()&& fWorker.isAlive()) { aboutToBeReconciledInternal(); + } - if (fWorker.isActive()) + if (fWorker.isActive()) { fProgressMonitor.setCanceled(true); + } if (fIsIncrementalReconciler) { DocumentEvent e= new DocumentEvent(fDocument, 0, fDocument.getLength(), fDocument.get()); @@ -642,8 +653,9 @@ protected void forceReconciling() { * Clients may extend this method. */ protected synchronized void startReconciling() { - if (fWorker == null) + if (fWorker == null) { return; + } fWorker.startReconciling(); } @@ -662,8 +674,9 @@ protected void reconcilerReset() { * @since 3.4 */ protected synchronized boolean isRunningInReconcilerThread() { - if (fWorker == null) + if (fWorker == null) { return false; + } return Thread.currentThread() == fWorker.fThread; } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegion.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegion.java index 56bb12efdc8..6aad18ab156 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegion.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegion.java @@ -35,7 +35,7 @@ public class DirtyRegion implements ITypedRegion { /** The region's length. */ private int fLength; /** Indicates the type of the applied change. */ - private String fType; + private final String fType; /** The text which has been inserted. */ private String fText; @@ -63,10 +63,12 @@ public DirtyRegion(int offset, int length, String type, String text) { * @since 3.1 */ private String normalizeTypeValue(String type) { - if (INSERT.equals(type)) + if (INSERT.equals(type)) { return INSERT; - if (REMOVE.equals(type)) + } + if (REMOVE.equals(type)) { return REMOVE; + } return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java index e8a53dfd266..c1f556f76bc 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java @@ -28,7 +28,7 @@ class DirtyRegionQueue { /** The list of dirty regions. */ - private List fDirtyRegions= new ArrayList<>(); + private final List fDirtyRegions= new ArrayList<>(); /** * Creates a new empty dirty region. @@ -47,8 +47,8 @@ public void addDirtyRegion(DirtyRegion dr) { // region on the queue then merge the two dirty regions together. DirtyRegion lastDR= getLastDirtyRegion(); boolean wasMerged= false; - if (lastDR != null) - if (lastDR.getType() == dr.getType()) + if (lastDR != null) { + if (lastDR.getType() == dr.getType()) { if (lastDR.getType() == DirtyRegion.INSERT) { if (lastDR.getOffset() + lastDR.getLength() == dr.getOffset()) { lastDR.mergeWith(dr); @@ -60,10 +60,13 @@ public void addDirtyRegion(DirtyRegion dr) { wasMerged= true; } } + } + } - if (!wasMerged) + if (!wasMerged) { // Don't merge- just add the new one onto the queue. fDirtyRegions.add(dr); + } } /** @@ -102,8 +105,9 @@ public void purgeQueue() { * @return the next dirty region on the queue */ public DirtyRegion removeNextDirtyRegion() { - if (fDirtyRegions.isEmpty()) + if (fDirtyRegions.isEmpty()) { return null; + } DirtyRegion dr= fDirtyRegions.get(0); fDirtyRegions.remove(0); return dr; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/MonoReconciler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/MonoReconciler.java index 42ea6c960a9..c5871f282d5 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/MonoReconciler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/MonoReconciler.java @@ -40,7 +40,7 @@ public class MonoReconciler extends AbstractReconciler { /** The reconciling strategy. */ - private IReconcilingStrategy fStrategy; + private final IReconcilingStrategy fStrategy; /** @@ -69,12 +69,13 @@ public IReconcilingStrategy getReconcilingStrategy(String contentType) { @Override protected void process(DirtyRegion dirtyRegion) { - if(dirtyRegion != null) + if(dirtyRegion != null) { fStrategy.reconcile(dirtyRegion, dirtyRegion); - else { + } else { IDocument document= getDocument(); - if (document != null) + if (document != null) { fStrategy.reconcile(new Region(0, document.getLength())); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java index ce983b087b7..682c95f9c07 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java @@ -96,12 +96,13 @@ public void setReconcilingStrategy(IReconcilingStrategy strategy, String content Assert.isNotNull(contentType); - if (fStrategies == null) + if (fStrategies == null) { fStrategies= new HashMap<>(); + } - if (strategy == null) + if (strategy == null) { fStrategies.remove(contentType); - else { + } else { fStrategies.put(contentType, strategy); if (strategy instanceof IReconcilingStrategyExtension extension && getProgressMonitor() != null) { extension.setProgressMonitor(getProgressMonitor()); @@ -114,8 +115,9 @@ public IReconcilingStrategy getReconcilingStrategy(String contentType) { Assert.isNotNull(contentType); - if (fStrategies == null) + if (fStrategies == null) { return null; + } return fStrategies.get(contentType); } @@ -134,20 +136,23 @@ protected void process(DirtyRegion dirtyRegion) { IRegion region= dirtyRegion; - if (region == null) + if (region == null) { region= new Region(0, getDocument().getLength()); + } ITypedRegion[] regions= computePartitioning(region.getOffset(), region.getLength()); for (ITypedRegion r : regions) { IReconcilingStrategy s= getReconcilingStrategy(r.getType()); - if (s == null) + if (s == null) { continue; + } - if(dirtyRegion != null) + if(dirtyRegion != null) { s.reconcile(dirtyRegion, r); - else + } else { s.reconcile(r); + } } } @@ -212,8 +217,9 @@ protected void initialProcess() { List contentTypes= new ArrayList<>(regions.length); for (ITypedRegion region : regions) { String contentType= region.getType(); - if( contentTypes.contains(contentType)) + if( contentTypes.contains(contentType)) { continue; + } contentTypes.add(contentType); IReconcilingStrategy s= getReconcilingStrategy(contentType); if (s instanceof IReconcilingStrategyExtension e) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java index 5d850df55e3..b74dfba0c35 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java @@ -122,8 +122,9 @@ public List getRanges() { */ public void applyDiff(Hunk[] hunks) { fRanges= null; // mark for recomputation - for (Revision revision : getRevisions()) + for (Revision revision : getRevisions()) { revision.applyDiff(hunks); + } } @Override diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultDamagerRepairer.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultDamagerRepairer.java index 57b614d9429..c2a27daddea 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultDamagerRepairer.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultDamagerRepairer.java @@ -107,8 +107,9 @@ public void setDocument(IDocument document) { protected int endOfLineOf(int offset) throws BadLocationException { IRegion info= fDocument.getLineInformationOfOffset(offset); - if (offset <= info.getOffset() + info.getLength()) + if (offset <= info.getOffset() + info.getLength()) { return info.getOffset() + info.getLength(); + } int line= fDocument.getLineOfOffset(offset); try { @@ -143,8 +144,9 @@ public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean if (info.getOffset() <= end && end <= info.getOffset() + info.getLength()) { // optimize the case of the same line end= info.getOffset() + info.getLength(); - } else + } else { end= endOfLineOf(end); + } end= Math.min(partition.getOffset() + partition.getLength(), end); return new Region(start, end - start); @@ -177,16 +179,18 @@ public void createPresentation(TextPresentation presentation, ITypedRegion regio while (true) { IToken token= fScanner.nextToken(); - if (token.isEOF()) + if (token.isEOF()) { break; + } TextAttribute attribute= getTokenTextAttribute(token); if (lastAttribute != null && lastAttribute.equals(attribute)) { length += fScanner.getTokenLength(); firstToken= false; } else { - if (!firstToken) + if (!firstToken) { addRange(presentation, lastStart, length, lastAttribute); + } firstToken= false; lastToken= token; lastAttribute= attribute; @@ -209,8 +213,9 @@ public void createPresentation(TextPresentation presentation, ITypedRegion regio */ protected TextAttribute getTokenTextAttribute(IToken token) { Object data= token.getData(); - if (data instanceof TextAttribute) + if (data instanceof TextAttribute) { return (TextAttribute) data; + } return fDefaultTextAttribute; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AbstractRulerColumn.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AbstractRulerColumn.java index f0b37e3cb6a..a6a9f98f819 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AbstractRulerColumn.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AbstractRulerColumn.java @@ -108,8 +108,9 @@ private final class InternalListener implements IViewportListener, ITextListener @Override public void viewportChanged(int topPixel) { int delta= topPixel - fLastTopPixel; - if (scrollVertical(delta)) + if (scrollVertical(delta)) { fCanvas.update(); // force update the invalidated regions + } } @Override @@ -120,11 +121,13 @@ public void textChanged(TextEvent event) { * was a visual modification (no document event attached) - for example when the * projection changes. */ - if (!event.getViewerRedrawState()) + if (!event.getViewerRedrawState()) { return; + } - if (fWasShowingEntireContents || event.getDocumentEvent() == null || JFaceTextUtil.isShowingEntireContents(fStyledText)) + if (fWasShowingEntireContents || event.getDocumentEvent() == null || JFaceTextUtil.isShowingEntireContents(fStyledText)) { redraw(); + } } } @@ -234,8 +237,9 @@ protected final void setWidth(int width) { if (fWidth != width) { fWidth= width; CompositeRuler composite= getParentRuler(); - if (composite != null) + if (composite != null) { composite.relayout(); + } } } @@ -274,10 +278,12 @@ public final void setFont(Font font) { * @return the font used to render text on the ruler. */ protected final Font getFont() { - if (fFont != null) + if (fFont != null) { return fFont; - if (fStyledText != null && !fStyledText.isDisposed()) + } + if (fStyledText != null && !fStyledText.isDisposed()) { return fStyledText.getFont(); + } return JFaceResources.getTextFont(); } @@ -327,8 +333,9 @@ public final IAnnotationModel getModel() { protected final void setDefaultBackground(Color background) { if (fBackground != background) { fBackground= background; - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.setBackground(getDefaultBackground()); + } redraw(); } } @@ -339,17 +346,21 @@ protected final void setDefaultBackground(Color background) { * @return the background color */ protected final Color getDefaultBackground() { - if (fBackground != null) + if (fBackground != null) { return fBackground; - if (fStyledText != null && !fStyledText.isDisposed()) + } + if (fStyledText != null && !fStyledText.isDisposed()) { return fStyledText.getBackground(); + } Display display; - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { display= fCanvas.getDisplay(); - else + } else { display= Display.getCurrent(); - if (display != null) + } + if (display != null) { return display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); + } return null; } @@ -359,8 +370,9 @@ protected final Color getDefaultBackground() { * @param hover the annotation hover, null for no hover */ protected final void setHover(IAnnotationHover hover) { - if (fHover != hover) + if (fHover != hover) { fHover= hover; + } } @Override @@ -383,8 +395,9 @@ public void dispose() { fTextViewer= null; } - if (fStyledText != null) + if (fStyledText != null) { fStyledText= null; + } if (fCanvas != null) { fCanvas.dispose(); @@ -394,8 +407,9 @@ public void dispose() { @Override public final void redraw() { - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.redraw(); + } } /** @@ -404,8 +418,9 @@ public final void redraw() { * @param lines the lines to be redrawn in document coordinates */ protected final void redraw(ILineRange lines) { - if (fCanvas == null || fCanvas.isDisposed()) + if (fCanvas == null || fCanvas.isDisposed()) { return; + } int firstModelLine= lines.getStartLine(); int lastModelLine= firstModelLine + lines.getNumberOfLines(); int firstWidgetLine= JFaceTextUtil.modelLineToWidgetLine(fTextViewer, firstModelLine); @@ -423,8 +438,9 @@ protected final void redraw(ILineRange lines) { * @param event the paint event */ private void paintControl(PaintEvent event) { - if (fTextViewer == null) + if (fTextViewer == null) { return; + } fWasShowingEntireContents= JFaceTextUtil.isShowingEntireContents(fStyledText); fLastTopPixel= fStyledText.getTopPixel(); @@ -472,8 +488,9 @@ protected void paint(GC gc, ILineRange lines) { final int lastLine= firstLine + lines.getNumberOfLines(); for (int line= firstLine; line < lastLine; line++) { int modelLine= JFaceTextUtil.widgetLine2ModelLine(fTextViewer, line); - if (modelLine == -1) + if (modelLine == -1) { continue; + } int linePixel= fStyledText.getLinePixel(line); int lineHeight= fStyledText.getLineHeight(fStyledText.getOffsetAtLine(line)); paintLine(gc, modelLine, line, linePixel, lineHeight); @@ -578,8 +595,9 @@ public void removeVerticalRulerListener(IVerticalRulerListener listener) { * was not scrolled */ private boolean scrollVertical(int pixels) { - if (pixels == 0 || fCanvas == null || fCanvas.isDisposed()) + if (pixels == 0 || fCanvas == null || fCanvas.isDisposed()) { return false; + } final int width= getWidth(); final int clientAreaHeight= fStyledText.getClientArea().height; @@ -591,9 +609,10 @@ private boolean scrollVertical(int pixels) { // downwards scrolling - content moves upwards int sourceY= topMargin + pixels; int scrollHeight= clientAreaHeight - sourceY - bottomMargin; - if (scrollHeight > 0) + if (scrollHeight > 0) { // scroll recycled area fCanvas.scroll(leftMargin, topMargin, leftMargin, sourceY, width, scrollHeight, true); + } if (sourceY > scrollHeight) { // redraw in-between area int redrawY= Math.max(0, topMargin + scrollHeight); @@ -604,9 +623,10 @@ private boolean scrollVertical(int pixels) { // upwards scrolling - content moves downwards int destinationY= topMargin - pixels; int scrollHeight= clientAreaHeight - destinationY - bottomMargin; - if (scrollHeight > 0) + if (scrollHeight > 0) { // scroll recycled area fCanvas.scroll(leftMargin, destinationY, leftMargin, topMargin, width, scrollHeight, true); + } if (destinationY > scrollHeight) { // redraw in-between area int redrawY= Math.max(0, topMargin + scrollHeight); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java index 60ea42caec9..bb7476f7dfb 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java @@ -114,7 +114,9 @@ public void setInformationControl(IInformationControl control) { @Override public void start(Rectangle subjectArea) { - if (fIsActive) return; + if (fIsActive) { + return; + } fIsActive= true; fSubjectArea= subjectArea; @@ -140,8 +142,9 @@ public void start(Rectangle subjectArea) { @Override public void stop() { - if (!fIsActive) + if (!fIsActive) { return; + } fIsActive= false; if (fSubjectControl != null && !fSubjectControl.isDisposed()) { @@ -176,8 +179,9 @@ protected void stop(boolean delayRestart) { @Override public void mouseMove(MouseEvent event) { - if (!fSubjectArea.contains(event.x, event.y)) + if (!fSubjectArea.contains(event.x, event.y)) { hideInformationControl(); + } } @Override @@ -196,14 +200,16 @@ public void mouseDoubleClick(MouseEvent event) { @Override public void handleEvent(Event event) { - if (event.type == SWT.MouseHorizontalWheel || event.type == SWT.MouseVerticalWheel) + if (event.type == SWT.MouseHorizontalWheel || event.type == SWT.MouseVerticalWheel) { hideInformationControl(); + } } @Override public void mouseExit(MouseEvent event) { - if (!fAllowMouseExit) + if (!fAllowMouseExit) { hideInformationControl(); + } } @Override @@ -253,11 +259,11 @@ public void widgetDisposed(DisposeEvent e) { } /** The source viewer the manager is connected to */ - private ISourceViewer fSourceViewer; + private final ISourceViewer fSourceViewer; /** The vertical ruler the manager is registered with */ - private IVerticalRulerInfo fVerticalRulerInfo; + private final IVerticalRulerInfo fVerticalRulerInfo; /** The annotation hover the manager uses to retrieve the information to display. Can be null. */ - private IAnnotationHover fAnnotationHover; + private final IAnnotationHover fAnnotationHover; /** * Indicates whether the mouse cursor is allowed to leave the subject area without closing the hover. * @since 3.0 @@ -335,10 +341,11 @@ protected void computeInformation() { ILineRange range= extension.getHoverLineRange(fSourceViewer, line); setCustomInformationControlCreator(extension.getHoverControlCreator()); range= adaptLineRange(range, line); - if (range != null) + if (range != null) { setInformation(extension.getHoverInfo(fSourceViewer, range, computeNumberOfVisibleLines()), computeArea(range)); - else + } else { setInformation(null, null); + } } else { setCustomInformationControlCreator(null); @@ -372,8 +379,9 @@ protected void hideInformationControl() { private ILineRange adaptLineRange(ILineRange lineRange, int line) { if (lineRange != null) { lineRange= adaptLineRangeToFolding(lineRange, line); - if (lineRange != null) + if (lineRange != null) { return adaptLineRangeToViewport(lineRange); + } } return null; } @@ -395,8 +403,9 @@ private ILineRange adaptLineRangeToFolding(ILineRange lineRange, int line) { IRegion[] coverage= extension.getCoveredModelRanges(region); if (coverage != null && coverage.length > 0) { IRegion container= findRegionContainingLine(coverage, line); - if (container != null) + if (container != null) { return convertToLineRange(container); + } } } catch (BadLocationException x) { @@ -473,8 +482,9 @@ private IRegion findRegionContainingLine(IRegion[] regions, int line) throws Bad IDocument document= fSourceViewer.getDocument(); IRegion lineInfo= document.getLineInformation(line); for (IRegion region : regions) { - if (TextUtilities.overlaps(region, lineInfo)) + if (TextUtilities.overlaps(region, lineInfo)) { return region; + } } return null; } @@ -535,8 +545,9 @@ private int computeNumberOfVisibleLines() { * @since 3.0 */ private IAnnotationHover getHover(MouseEvent event) { - if (event == null || event.getSource() == null) + if (event == null || event.getSource() == null) { return fAnnotationHover; + } if (fVerticalRulerInfo instanceof CompositeRuler comp) { for (Iterator it= comp.getDecoratorIterator(); it.hasNext();) { @@ -544,8 +555,9 @@ private IAnnotationHover getHover(MouseEvent event) { if (o instanceof IVerticalRulerInfoExtension && o instanceof IVerticalRulerInfo) { if (((IVerticalRulerInfo) o).getControl() == event.getSource()) { IAnnotationHover hover= ((IVerticalRulerInfoExtension) o).getHover(); - if (hover != null) + if (hover != null) { return hover; + } } } } @@ -682,10 +694,11 @@ protected Point computeLocation(Rectangle subjectArea, Point controlSize, Anchor Control subjectControl= getSubjectControl(); // return a location that just overlaps the annotation on the bar - if (anchor == AbstractInformationControlManager.ANCHOR_RIGHT) + if (anchor == AbstractInformationControlManager.ANCHOR_RIGHT) { return subjectControl.toDisplay(subjectArea.x - 4, subjectArea.y - 2); - else if (anchor == AbstractInformationControlManager.ANCHOR_LEFT) + } else if (anchor == AbstractInformationControlManager.ANCHOR_LEFT) { return subjectControl.toDisplay(subjectArea.x + subjectArea.width - controlSize.x + 4, subjectArea.y - 2); + } } fAllowMouseExit= false; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java index 713055cc589..4b9d1c1b6b8 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java @@ -117,8 +117,9 @@ public static class SquigglesStrategy implements IDrawingStrategy { public void draw(Annotation annotation, GC gc, StyledText textWidget, int offset, int length, Color color) { if (gc != null) { - if (length < 1) + if (length < 1) { return; + } Point left= textWidget.getLocationAtOffset(offset); Point right= textWidget.getLocationAtOffset(offset + length); @@ -154,15 +155,17 @@ private int[] computePolyline(Point left, Point right, int baseline, int lineHei final int HEIGHT= 2; // can be any number int peaks= (right.x - left.x) / WIDTH; - if (peaks == 0 && right.x - left.x > 2) + if (peaks == 0 && right.x - left.x > 2) { peaks= 1; + } int leftX= left.x; // compute (number of point) * 2 int length= ((2 * peaks) + 1) * 2; - if (length < 0) + if (length < 0) { return new int[0]; + } int[] coordinates= new int[length]; @@ -370,12 +373,12 @@ private static class Decoration { * Mutex for highlighted decorations map. * @since 3.0 */ - private Object fDecorationMapLock= new Object(); + private final Object fDecorationMapLock= new Object(); /** * Mutex for for decorations map. * @since 3.0 */ - private Object fHighlightedDecorationsMapLock= new Object(); + private final Object fHighlightedDecorationsMapLock= new Object(); /** * Maps an annotation type to its registered color. * @@ -438,13 +441,13 @@ private static class Decoration { * * @since 3.0 */ - private Map fPaintingStrategyId2PaintingStrategy= new HashMap<>(); + private final Map fPaintingStrategyId2PaintingStrategy= new HashMap<>(); /** * Reuse this region for performance reasons. * @since 3.3 */ - private ReusableRegion fReusableRegion= new ReusableRegion(); + private final ReusableRegion fReusableRegion= new ReusableRegion(); /** * Color used to draw inline annotations. @@ -503,8 +506,9 @@ private void disablePainting(boolean redraw) { if (fIsPainting) { fIsPainting= false; fTextWidget.removePaintListener(this); - if (redraw && hasDecorations()) + if (redraw && hasDecorations()) { handleDrawRequest(null); + } } } @@ -516,8 +520,9 @@ private void disablePainting(boolean redraw) { */ private void setModel(IAnnotationModel model) { if (fModel != model) { - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(this); + } fModel= model; if (fModel != null) { try { @@ -539,8 +544,9 @@ private void setModel(IAnnotationModel model) { private void catchupWithModel(AnnotationModelEvent event) { synchronized (fDecorationMapLock) { - if (fDecorationsMap == null) + if (fDecorationsMap == null) { return; + } } if (fModel == null) { @@ -580,8 +586,9 @@ private void catchupWithModel(AnnotationModelEvent event) { if (event == null || event.isWorldChange()) { isWorldChange= true; - if (DEBUG && event == null) + if (DEBUG && event == null) { System.out.println("AP: INTERNAL CHANGE"); //$NON-NLS-1$ + } Iterator> iter= decorationsMap.entrySet().iterator(); while (iter.hasNext()) { @@ -653,10 +660,11 @@ private void catchupWithModel(AnnotationModelEvent event) { boolean usesDrawingStrategy= !isHighlighting && decoration != null; Position position= null; - if (decoration == null) + if (decoration == null) { position= fModel.getPosition(annotation); - else + } else { position= decoration.fPosition; + } if (position != null && !position.isDeleted()) { if (isHighlighting) { @@ -679,10 +687,11 @@ private void catchupWithModel(AnnotationModelEvent event) { Decoration oldDecoration= decorationsMap.get(annotation); if (oldDecoration != null) { drawDecoration(oldDecoration, null, annotation, clippingRegion, document); - if (decoration != null) + if (decoration != null) { decorationsMap.put(annotation, decoration); - else + } else { decorationsMap.remove(annotation); + } } } } @@ -738,10 +747,12 @@ private void updateHighlightRanges(int highlightAnnotationRangeStart, int highli maxRangeEnd= Math.max(maxRangeEnd, fTotalHighlightAnnotationRange.offset + fTotalHighlightAnnotationRange.length); } - if (fTotalHighlightAnnotationRange == null) + if (fTotalHighlightAnnotationRange == null) { fTotalHighlightAnnotationRange= new Position(0); - if (fCurrentHighlightAnnotationRange == null) + } + if (fCurrentHighlightAnnotationRange == null) { fCurrentHighlightAnnotationRange= new Position(0); + } if (isWorldChange) { fTotalHighlightAnnotationRange.offset= highlightAnnotationRangeStart; @@ -786,10 +797,12 @@ private void updateDrawRanges(int drawRangeStart, int drawRangeEnd, boolean isWo maxRangeEnd= Math.max(maxRangeEnd, fTotalDrawRange.offset + fTotalDrawRange.length); } - if (fTotalDrawRange == null) + if (fTotalDrawRange == null) { fTotalDrawRange= new Position(0); - if (fCurrentDrawRange == null) + } + if (fCurrentDrawRange == null) { fCurrentDrawRange= new Position(0); + } if (isWorldChange) { fTotalDrawRange.offset= drawRangeStart; @@ -822,8 +835,9 @@ private void updateDrawRanges(int drawRangeStart, int drawRangeEnd, boolean isWo * @since 3.0 */ private void adaptToDocumentLength(Position position) { - if (position == null) + if (position == null) { return; + } int length= fSourceViewer.getDocument().getLength(); position.offset= Math.min(position.offset, length); @@ -841,25 +855,30 @@ private void adaptToDocumentLength(Position position) { */ private Decoration getDecoration(Annotation annotation, Decoration decoration) { - if (annotation.isMarkedDeleted()) + if (annotation.isMarkedDeleted()) { return null; + } String type= annotation.getType(); Object paintingStrategy= getPaintingStrategy(type); - if (paintingStrategy == null || paintingStrategy instanceof NullStrategy) + if (paintingStrategy == null || paintingStrategy instanceof NullStrategy) { return null; + } Color color= getColor(type); - if (color == null) + if (color == null) { return null; + } Position position= fModel.getPosition(annotation); - if (position == null || position.isDeleted()) + if (position == null || position.isDeleted()) { return null; + } - if (decoration == null) + if (decoration == null) { decoration= new Decoration(); + } decoration.fPosition= position; decoration.fColor= color; @@ -883,8 +902,9 @@ private Decoration getDecoration(Annotation annotation, Decoration decoration) { */ private Object getPaintingStrategy(final String type) { Object strategy= fCachedAnnotationType2PaintingStrategy.get(type); - if (strategy != null) + if (strategy != null) { return strategy; + } strategy= fPaintingStrategyId2PaintingStrategy.get(fAnnotationType2PaintingStrategyId.get(type)); if (strategy != null) { @@ -917,8 +937,9 @@ private Object getPaintingStrategy(final String type) { */ private Color getColor(final Object annotationType) { Color color= fCachedAnnotationType2Color.get(annotationType); - if (color != null) + if (color != null) { return color; + } color= fAnnotationType2Color.get(annotationType); if (color != null) { @@ -953,8 +974,9 @@ private void updatePainting(AnnotationModelEvent event) { catchupWithModel(event); - if (!fInputDocumentAboutToBeChanged) + if (!fInputDocumentAboutToBeChanged) { invalidateTextPresentation(); + } enablePainting(); } @@ -962,15 +984,18 @@ private void updatePainting(AnnotationModelEvent event) { private void invalidateTextPresentation() { IRegion r= null; synchronized (fHighlightedDecorationsMapLock) { - if (fCurrentHighlightAnnotationRange != null) + if (fCurrentHighlightAnnotationRange != null) { r= new Region(fCurrentHighlightAnnotationRange.getOffset(), fCurrentHighlightAnnotationRange.getLength()); + } } - if (r == null) + if (r == null) { return; + } if (fSourceViewer instanceof ITextViewerExtension2) { - if (DEBUG) + if (DEBUG) { System.out.println("AP: invalidating offset: " + r.getOffset() + ", length= " + r.getLength()); //$NON-NLS-1$ //$NON-NLS-2$ + } ((ITextViewerExtension2)fSourceViewer).invalidateTextPresentation(r.getOffset(), r.getLength()); @@ -984,34 +1009,39 @@ public void applyTextPresentation(TextPresentation tp) { Set> decorations; synchronized (fHighlightedDecorationsMapLock) { - if (fHighlightedDecorationsMap == null || fHighlightedDecorationsMap.isEmpty()) + if (fHighlightedDecorationsMap == null || fHighlightedDecorationsMap.isEmpty()) { return; + } decorations= new HashSet<>(fHighlightedDecorationsMap.entrySet()); } IRegion region= tp.getExtent(); - if (DEBUG) + if (DEBUG) { System.out.println("AP: applying text presentation offset: " + region.getOffset() + ", length= " + region.getLength()); //$NON-NLS-1$ //$NON-NLS-2$ + } for (int layer= 0, maxLayer= 1; layer < maxLayer; layer++) { for (Entry entry : decorations) { Annotation a= entry.getKey(); - if (a.isMarkedDeleted()) + if (a.isMarkedDeleted()) { continue; + } Decoration pp = entry.getValue(); maxLayer= Math.max(maxLayer, pp.fLayer + 1); // dynamically update layer maximum - if (pp.fLayer != layer) // wrong layer: skip annotation + if (pp.fLayer != layer) { // wrong layer: skip annotation continue; + } Position p= pp.fPosition; if (fSourceViewer instanceof ITextViewerExtension5 extension3) { - if (null == extension3.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()))) + if (null == extension3.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()))) { continue; + } } else if (!fSourceViewer.overlapsWithVisibleRegion(p.offset, p.length)) { continue; } @@ -1032,8 +1062,9 @@ public void applyTextPresentation(TextPresentation tp) { @Override public synchronized void modelChanged(final IAnnotationModel model) { - if (DEBUG) + if (DEBUG) { System.err.println("AP: OLD API of AnnotationModelListener called"); //$NON-NLS-1$ + } modelChanged(new AnnotationModelEvent(model)); } @@ -1043,20 +1074,22 @@ public void modelChanged(final AnnotationModelEvent event) { Display textWidgetDisplay; try { StyledText textWidget= fTextWidget; - if (textWidget == null || textWidget.isDisposed()) + if (textWidget == null || textWidget.isDisposed()) { return; + } textWidgetDisplay= textWidget.getDisplay(); } catch (SWTException ex) { - if (ex.code == SWT.ERROR_WIDGET_DISPOSED) + if (ex.code == SWT.ERROR_WIDGET_DISPOSED) { return; + } throw ex; } if (fIsSettingModel) { // inside the UI thread -> no need for posting - if (textWidgetDisplay == Display.getCurrent()) + if (textWidgetDisplay == Display.getCurrent()) { updatePainting(event); - else { + } else { /* * we can throw away the changes since * further update painting will happen @@ -1075,8 +1108,9 @@ public void modelChanged(final AnnotationModelEvent event) { // now and running the posted runnable, the position information // is not accurate any longer. textWidgetDisplay.asyncExec(() -> { - if (fTextWidget != null && !fTextWidget.isDisposed()) + if (fTextWidget != null && !fTextWidget.isDisposed()) { updatePainting(event); + } }); } } @@ -1088,10 +1122,11 @@ public void modelChanged(final AnnotationModelEvent event) { * @param color the color */ public void setAnnotationTypeColor(Object annotationType, Color color) { - if (color != null) + if (color != null) { fAnnotationType2Color.put(annotationType, color); - else + } else { fAnnotationType2Color.remove(annotationType); + } fCachedAnnotationType2Color.clear(); } @@ -1155,8 +1190,9 @@ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { public void addDrawingStrategy(Object id, IDrawingStrategy strategy) { // don't permit null as null is used to signal that an annotation type is not // registered with a specific strategy, and that its annotation hierarchy should be searched - if (id == null) + if (id == null) { throw new IllegalArgumentException(); + } fPaintingStrategyId2PaintingStrategy.put(id, strategy); fCachedAnnotationType2PaintingStrategy.clear(); } @@ -1180,8 +1216,9 @@ public void addDrawingStrategy(Object id, IDrawingStrategy strategy) { public void addTextStyleStrategy(Object id, ITextStyleStrategy strategy) { // don't permit null as null is used to signal that an annotation type is not // registered with a specific strategy, and that its annotation hierarchy should be searched - if (id == null) + if (id == null) { throw new IllegalArgumentException(); + } fPaintingStrategyId2PaintingStrategy.put(id, strategy); fCachedAnnotationType2PaintingStrategy.clear(); } @@ -1322,8 +1359,9 @@ private int getExclusiveBottomIndexEndOffset() { try { IDocument document= fSourceViewer.getDocument(); - if (bottom >= document.getNumberOfLines()) + if (bottom >= document.getNumberOfLines()) { bottom= document.getNumberOfLines() - 1; + } return document.getLineOffset(bottom) + document.getLineLength(bottom); } catch (BadLocationException x) { @@ -1335,8 +1373,9 @@ private int getExclusiveBottomIndexEndOffset() { @Override public void paintControl(PaintEvent event) { - if (fTextWidget != null) + if (fTextWidget != null) { handleDrawRequest(event); + } } /** @@ -1352,8 +1391,9 @@ private void handleDrawRequest(PaintEvent event) { } IRegion clippingRegion= computeClippingRegion(event, false); - if (clippingRegion == null) + if (clippingRegion == null) { return; + } int vOffset= clippingRegion.getOffset(); int vLength= clippingRegion.getLength(); @@ -1378,8 +1418,9 @@ private void handleDrawRequest(PaintEvent event) { // prune any annotation that is not drawable or does not need drawing if (!(a.isMarkedDeleted() || skip(a) || !regionsTouchOrOverlap(pp.fPosition.getOffset(), pp.fPosition.getLength(), vOffset, vLength))) { // ensure sized appropriately - for (int i= toBeDrawn.size(); i <= pp.fLayer; i++) + for (int i= toBeDrawn.size(); i <= pp.fLayer; i++) { toBeDrawn.add(new LinkedList<>()); + } toBeDrawn.get(pp.fLayer).add(entry); } } @@ -1394,11 +1435,13 @@ private void handleDrawRequest(PaintEvent event) { } private void drawDecoration(Decoration pp, GC gc, Annotation annotation, IRegion clippingRegion, IDocument document) { - if (clippingRegion == null) + if (clippingRegion == null) { return; + } - if (!(pp.fPaintingStrategy instanceof IDrawingStrategy drawingStrategy)) + if (!(pp.fPaintingStrategy instanceof IDrawingStrategy drawingStrategy)) { return; + } int clippingOffset= clippingRegion.getOffset(); int clippingLength= clippingRegion.getLength(); @@ -1448,13 +1491,15 @@ private void drawDecoration(Decoration pp, GC gc, Annotation annotation, IRegion private IRegion computeClippingRegion(PaintEvent event, boolean isClearing) { if (event == null) { - if (!isClearing && fCurrentDrawRange != null) + if (!isClearing && fCurrentDrawRange != null) { return new Region(fCurrentDrawRange.offset, fCurrentDrawRange.length); + } // trigger a repaint of the entire viewport int vOffset= getInclusiveTopIndexStartOffset(); - if (vOffset == -1) + if (vOffset == -1) { return null; + } // http://bugs.eclipse.org/bugs/show_bug.cgi?id=17147 int vLength= getExclusiveBottomIndexEndOffset() - vOffset; @@ -1536,8 +1581,9 @@ protected boolean skip(Annotation annotation) { * @return the corresponding widget region */ private IRegion getWidgetRange(int modelOffset, int modelLength) { - if (modelOffset == Integer.MAX_VALUE) + if (modelOffset == Integer.MAX_VALUE) { return null; + } if (fSourceViewer instanceof ITextViewerExtension5 extension) { fReusableRegion.setOffset(modelOffset); @@ -1569,8 +1615,9 @@ private IRegion getWidgetRange(int modelOffset, int modelLength) { * @since 3.2 */ private IRegion getModelRange(int offset, int length) { - if (offset == Integer.MAX_VALUE) + if (offset == Integer.MAX_VALUE) { return null; + } if (fSourceViewer instanceof ITextViewerExtension5 extension) { return extension.widgetRange2ModelRange(new Region(offset, length)); @@ -1622,8 +1669,9 @@ protected boolean isRepaintReason(int reason) { * @since 3.0 */ protected IAnnotationModel findAnnotationModel(ISourceViewer sourceViewer) { - if(sourceViewer != null) + if(sourceViewer != null) { return sourceViewer.getAnnotationModel(); + } return null; } @@ -1640,8 +1688,9 @@ public void paint(int reason) { fIsActive= true; setModel(model); } - } else if (isRepaintReason(reason)) + } else if (isRepaintReason(reason)) { updatePainting(null); + } } @Override diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java index 9233ebe0421..2017489327a 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java @@ -129,23 +129,23 @@ public int compare(Tuple o1, Tuple o2) { /** The buffer for double buffering */ private Image fBuffer; /** The internal listener */ - private AnnotationsListener fAnnotationListener= new AnnotationsListener(); + private final AnnotationsListener fAnnotationListener= new AnnotationsListener(); /** The width of this vertical ruler */ - private int fWidth; + private final int fWidth; /** Switch for enabling/disabling the setModel method. */ private boolean fAllowSetModel= true; /** * The list of annotation types to be shown in this ruler. * @since 3.0 */ - private Set fConfiguredAnnotationTypes= new HashSet<>(); + private final Set fConfiguredAnnotationTypes= new HashSet<>(); /** * The list of allowed annotation types to be shown in this ruler. * An allowed annotation type maps to true, a disallowed * to false. * @since 3.0 */ - private Map fAllowedAnnotationTypes= new HashMap<>(); + private final Map fAllowedAnnotationTypes= new HashMap<>(); /** * The annotation access extension. * @since 3.0 @@ -160,12 +160,12 @@ public int compare(Tuple o1, Tuple o2) { * The cached annotations. * @since 3.0 */ - private List fCachedAnnotations= new ArrayList<>(); + private final List fCachedAnnotations= new ArrayList<>(); /** * The comparator for sorting annotations according to the offset of their position. * @since 3.0 */ - private Comparator fTupleComparator= new TupleComparator(); + private final Comparator fTupleComparator= new TupleComparator(); /** * The hit detection cursor. Do not dispose. * @since 3.0 @@ -182,7 +182,7 @@ public int compare(Tuple o1, Tuple o2) { */ private MouseListener fMouseListener; - private Consumer lineHeightChangeHandler= t -> postRedraw(); + private final Consumer lineHeightChangeHandler= t -> postRedraw(); /** * Constructs this column with the given arguments. @@ -208,8 +208,9 @@ public AnnotationRulerColumn(IAnnotationModel model, int width, IAnnotationAcces */ public AnnotationRulerColumn(int width, IAnnotationAccess annotationAccess) { fWidth= width; - if (annotationAccess instanceof IAnnotationAccessExtension) + if (annotationAccess instanceof IAnnotationAccessExtension) { fAnnotationAccessExtension= (IAnnotationAccessExtension) annotationAccess; + } } /** @@ -256,8 +257,9 @@ public Control createControl(CompositeRuler parentRuler, Composite parentControl fCanvas= createCanvas(parentControl); fCanvas.addPaintListener(event -> { - if (fCachedTextViewer != null) + if (fCachedTextViewer != null) { doubleBufferPaint(event.gc); + } }); fCanvas.addDisposeListener(e -> { @@ -280,11 +282,13 @@ public void mouseUp(MouseEvent event) { if (isPropagatingMouseListener()) { fParentRuler.setLocationOfLastMouseButtonActivity(event.x, event.y); lineNumber= fParentRuler.getLineOfLastMouseButtonActivity(); - } else + } else { lineNumber= fParentRuler.toDocumentLineNumber(event.y); + } - if (1 == event.button) + if (1 == event.button) { mouseClicked(lineNumber); + } } @Override @@ -293,11 +297,13 @@ public void mouseDown(MouseEvent event) { if (isPropagatingMouseListener()) { fParentRuler.setLocationOfLastMouseButtonActivity(event.x, event.y); lineNumber= fParentRuler.getLineOfLastMouseButtonActivity(); - } else + } else { lineNumber= fParentRuler.toDocumentLineNumber(event.y); + } - if (1 == event.button) + if (1 == event.button) { AnnotationRulerColumn.this.mouseDown(lineNumber); + } } @Override @@ -306,11 +312,13 @@ public void mouseDoubleClick(MouseEvent event) { if (isPropagatingMouseListener()) { fParentRuler.setLocationOfLastMouseButtonActivity(event.x, event.y); lineNumber= fParentRuler.getLineOfLastMouseButtonActivity(); - } else + } else { lineNumber= fParentRuler.toDocumentLineNumber(event.y); + } - if (1 == event.button) + if (1 == event.button) { mouseDoubleClicked(lineNumber); + } } }; fCanvas.addMouseListener(fMouseListener); @@ -345,8 +353,9 @@ private Canvas createCanvas(Composite parent) { return new Canvas(parent, SWT.NO_BACKGROUND | SWT.NO_FOCUS) { @Override public void addMouseListener(MouseListener listener) { - if (isPropagatingMouseListener() || listener == fMouseListener) + if (isPropagatingMouseListener() || listener == fMouseListener) { super.addMouseListener(listener); + } } }; } @@ -435,17 +444,20 @@ private void handleMouseScrolled(MouseEvent event) { protected boolean hasAnnotation(int lineNumber) { IAnnotationModel model= fModel; - if (fModel instanceof IAnnotationModelExtension) + if (fModel instanceof IAnnotationModelExtension) { model= ((IAnnotationModelExtension)fModel).getAnnotationModel(SourceViewer.MODEL_ANNOTATION_MODEL); + } - if (model == null) + if (model == null) { return false; + } IRegion line; try { IDocument d= fCachedTextViewer.getDocument(); - if (d == null) + if (d == null) { return false; + } line= d.getLineInformation(lineNumber); } catch (BadLocationException ex) { @@ -456,26 +468,31 @@ protected boolean hasAnnotation(int lineNumber) { int lineLength= line.getLength(); Iterator e; - if (fModel instanceof IAnnotationModelExtension2) + if (fModel instanceof IAnnotationModelExtension2) { e= ((IAnnotationModelExtension2)fModel).getAnnotationIterator(lineStart, lineLength + 1, true, true); - else + } else { e= model.getAnnotationIterator(); + } while (e.hasNext()) { Annotation a= e.next(); - if (a.isMarkedDeleted()) + if (a.isMarkedDeleted()) { continue; + } - if (skip(a)) + if (skip(a)) { continue; + } Position p= model.getPosition(a); - if (p == null || p.isDeleted()) + if (p == null || p.isDeleted()) { continue; + } - if (p.overlapsWith(lineStart, lineLength) || p.length == 0 && p.offset == lineStart + lineLength) + if (p.overlapsWith(lineStart, lineLength) || p.length == 0 && p.offset == lineStart + lineLength) { return true; + } } return false; @@ -490,8 +507,9 @@ private void handleDispose() { VisibleLinesTracker.untrack(fCachedTextViewer, lineHeightChangeHandler); } - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(fAnnotationListener); + } if (fBuffer != null) { fBuffer.dispose(); @@ -513,8 +531,9 @@ private void doubleBufferPaint(GC dest) { Point size= fCanvas.getSize(); - if (size.x <= 0 || size.y <= 0) + if (size.x <= 0 || size.y <= 0) { return; + } if (fBuffer != null) { Rectangle r= fBuffer.getBounds(); @@ -541,10 +560,11 @@ private void doPaint(GC gc, int width, int height) { gc.setBackground(fCanvas.getBackground()); gc.fillRectangle(0, 0, width, height); - if (fCachedTextViewer instanceof ITextViewerExtension5) + if (fCachedTextViewer instanceof ITextViewerExtension5) { doPaint1(gc); - else + } else { doPaint(gc); + } } /** @@ -554,12 +574,14 @@ private void doPaint(GC gc, int width, int height) { * @return document offset of the upper left corner including partially visible lines */ protected int getInclusiveTopIndexStartOffset() { - if (fCachedTextWidget == null || fCachedTextWidget.isDisposed()) + if (fCachedTextWidget == null || fCachedTextWidget.isDisposed()) { return -1; + } IDocument document= fCachedTextViewer.getDocument(); - if (document == null) + if (document == null) { return -1; + } int top= JFaceTextUtil.getPartialTopIndex(fCachedTextViewer); try { @@ -576,17 +598,20 @@ protected int getInclusiveTopIndexStartOffset() { * @return the first invisible document offset of the lower right corner of the view port */ private int getExclusiveBottomIndexEndOffset() { - if (fCachedTextWidget == null || fCachedTextWidget.isDisposed()) + if (fCachedTextWidget == null || fCachedTextWidget.isDisposed()) { return -1; + } IDocument document= fCachedTextViewer.getDocument(); - if (document == null) + if (document == null) { return -1; + } int bottom= JFaceTextUtil.getPartialBottomIndex(fCachedTextViewer); try { - if (bottom >= document.getNumberOfLines()) + if (bottom >= document.getNumberOfLines()) { bottom= document.getNumberOfLines() - 1; + } return document.getLineOffset(bottom) + document.getLineLength(bottom); } catch (BadLocationException x) { return -1; @@ -600,8 +625,9 @@ private int getExclusiveBottomIndexEndOffset() { */ protected void doPaint(GC gc) { - if (fModel == null || fCachedTextViewer == null) + if (fModel == null || fCachedTextViewer == null) { return; + } int topLeft= getInclusiveTopIndexStartOffset(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=14938 @@ -614,8 +640,9 @@ protected void doPaint(GC gc) { Point dimension= fCanvas.getSize(); IDocument doc= fCachedTextViewer.getDocument(); - if (doc == null) + if (doc == null) { return; + } int topLine= -1, bottomLine= -1; try { @@ -632,34 +659,40 @@ protected void doPaint(GC gc) { boolean isWrapActive= fCachedTextWidget.getWordWrap(); for (int layer= 0; layer < maxLayer; layer++) { Iterator iter; - if (fModel instanceof IAnnotationModelExtension2) + if (fModel instanceof IAnnotationModelExtension2) { iter= ((IAnnotationModelExtension2)fModel).getAnnotationIterator(topLeft, viewPort + 1, true, true); - else + } else { iter= fModel.getAnnotationIterator(); + } while (iter.hasNext()) { Annotation annotation= iter.next(); int lay= IAnnotationAccessExtension.DEFAULT_LAYER; - if (fAnnotationAccessExtension != null) + if (fAnnotationAccessExtension != null) { lay= fAnnotationAccessExtension.getLayer(annotation); + } maxLayer= Math.max(maxLayer, lay+1); // dynamically update layer maximum - if (lay != layer) // wrong layer: skip annotation + if (lay != layer) { // wrong layer: skip annotation continue; + } - if (skip(annotation)) + if (skip(annotation)) { continue; + } Position position= fModel.getPosition(annotation); - if (position == null) + if (position == null) { continue; + } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=20284 // Position.overlapsWith returns false if the position just starts at the end // of the specified range. If the position has zero length, we want to include it anyhow int viewPortSize= position.getLength() == 0 ? viewPort + 1 : viewPort; - if (!position.overlapsWith(topLeft, viewPortSize)) + if (!position.overlapsWith(topLeft, viewPortSize)) { continue; + } try { @@ -667,14 +700,17 @@ protected void doPaint(GC gc) { int length= position.getLength(); int startLine= doc.getLineOfOffset(offset); - if (startLine < topLine) + if (startLine < topLine) { startLine= topLine; + } int endLine= startLine; - if (length > 0) + if (length > 0) { endLine= doc.getLineOfOffset(offset + length - 1); - if (endLine > bottomLine) + } + if (endLine > bottomLine) { endLine= bottomLine; + } startLine -= topLine; endLine -= topLine; @@ -695,8 +731,9 @@ protected void doPaint(GC gc) { r.height= textBounds.height; r.y= textBounds.y; } - if (r.y < dimension.y && fAnnotationAccessExtension != null) // annotation within visible area + if (r.y < dimension.y && fAnnotationAccessExtension != null) { // annotation within visible area fAnnotationAccessExtension.paint(annotation, gc, fCanvas, r); + } } catch (BadLocationException x) { } @@ -712,8 +749,9 @@ protected void doPaint(GC gc) { */ protected void doPaint1(GC gc) { - if (fModel == null || fCachedTextViewer == null) + if (fModel == null || fCachedTextViewer == null) { return; + } ITextViewerExtension5 extension= (ITextViewerExtension5) fCachedTextViewer; @@ -722,8 +760,9 @@ protected void doPaint1(GC gc) { int vOffset= getInclusiveTopIndexStartOffset(); int vLength= getExclusiveBottomIndexEndOffset() - vOffset; - if (vOffset < 0 || vLength < 0) + if (vOffset < 0 || vLength < 0) { return; + } // draw Annotations Rectangle r= new Rectangle(0, 0, 0, 0); @@ -731,29 +770,34 @@ protected void doPaint1(GC gc) { boolean isWrapActive= fCachedTextWidget.getWordWrap(); fCachedAnnotations.clear(); Iterator iter; - if (fModel instanceof IAnnotationModelExtension2) + if (fModel instanceof IAnnotationModelExtension2) { iter= ((IAnnotationModelExtension2)fModel).getAnnotationIterator(vOffset, vLength + 1, true, true); - else + } else { iter= fModel.getAnnotationIterator(); + } while (iter.hasNext()) { Annotation annotation= iter.next(); - if (skip(annotation)) + if (skip(annotation)) { continue; + } Position position= fModel.getPosition(annotation); - if (position == null) + if (position == null) { continue; + } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=217710 int extendedVLength= position.getLength() == 0 ? vLength + 1 : vLength; - if (!position.overlapsWith(vOffset, extendedVLength)) + if (!position.overlapsWith(vOffset, extendedVLength)) { continue; + } int lay= IAnnotationAccessExtension.DEFAULT_LAYER; - if (fAnnotationAccessExtension != null) + if (fAnnotationAccessExtension != null) { lay= fAnnotationAccessExtension.getLayer(annotation); + } fCachedAnnotations.add(new Tuple(annotation, position, lay)); } @@ -766,18 +810,21 @@ protected void doPaint1(GC gc) { range.setOffset(position.getOffset()); range.setLength(position.getLength()); IRegion widgetRegion= extension.modelRange2WidgetRange(range); - if (widgetRegion == null) + if (widgetRegion == null) { continue; + } int offset= widgetRegion.getOffset(); int startLine= extension.widgetLineOfWidgetOffset(offset); - if (startLine == -1) + if (startLine == -1) { continue; + } int length= Math.max(widgetRegion.getLength() - 1, 0); int endLine= extension.widgetLineOfWidgetOffset(offset + length); - if (endLine == -1) + if (endLine == -1) { continue; + } r.x= 0; @@ -801,8 +848,9 @@ protected void doPaint1(GC gc) { r.y+= verticalIndent; r.height-= verticalIndent; } - if (r.y < dimension.y && fAnnotationAccessExtension != null) // annotation within visible area + if (r.y < dimension.y && fAnnotationAccessExtension != null) { // annotation within visible area fAnnotationAccessExtension.paint(annotation, gc, fCanvas, r); + } } fCachedAnnotations.clear(); @@ -841,13 +889,15 @@ public void redraw() { public void setModel(IAnnotationModel model) { if (fAllowSetModel && model != fModel) { - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(fAnnotationListener); + } fModel= model; - if (fModel != null) + if (fModel != null) { fModel.addAnnotationModelListener(fAnnotationListener); + } postRedraw(); } @@ -919,8 +969,9 @@ public void removeAnnotationType(Object annotationType) { private boolean skip(Annotation annotation) { Object annotationType= annotation.getType(); Boolean allowed= fAllowedAnnotationTypes.get(annotationType); - if (allowed != null) + if (allowed != null) { return !allowed.booleanValue(); + } boolean skip= skip(annotationType); fAllowedAnnotationTypes.put(annotationType, !skip ? Boolean.TRUE : Boolean.FALSE); @@ -940,8 +991,9 @@ private boolean skip(Object annotationType) { if (fAnnotationAccessExtension != null) { Iterator e= fConfiguredAnnotationTypes.iterator(); while (e.hasNext()) { - if (fAnnotationAccessExtension.isSubtype(annotationType, e.next())) + if (fAnnotationAccessExtension.isSubtype(annotationType, e.next())) { return false; + } } return true; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ChangeRulerColumn.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ChangeRulerColumn.java index d712d40ef35..befc92e6c6f 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ChangeRulerColumn.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ChangeRulerColumn.java @@ -86,18 +86,21 @@ private class InternalListener implements IViewportListener, ITextListener { @Override public void viewportChanged(int verticalPosition) { - if (verticalPosition != fScrollPos) + if (verticalPosition != fScrollPos) { redraw(); + } } @Override public void textChanged(TextEvent event) { - if (!event.getViewerRedrawState()) + if (!event.getViewerRedrawState()) { return; + } - if (fSensitiveToTextChanges || event.getDocumentEvent() == null) + if (fSensitiveToTextChanges || event.getDocumentEvent() == null) { postRedraw(); + } } } @@ -173,8 +176,9 @@ public ChangeRulerColumn(ISharedTextColors sharedColors) { * @return the System background color for list widgets */ private Color getBackground() { - if (fBackground == null) + if (fBackground == null) { return fCachedTextWidget.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND); + } return fBackground; } @@ -189,8 +193,9 @@ public Control createControl(CompositeRuler parentRuler, Composite parentControl fCanvas.setBackground(getBackground()); fCanvas.addPaintListener(event -> { - if (fCachedTextViewer != null) + if (fCachedTextViewer != null) { doubleBufferPaint(event.gc); + } }); fCanvas.addDisposeListener(e -> { @@ -246,8 +251,9 @@ private void doubleBufferPaint(GC dest) { Point size= fCanvas.getSize(); - if (size.x <= 0 || size.y <= 0) + if (size.x <= 0 || size.y <= 0) { return; + } if (fBuffer != null) { Rectangle r= fBuffer.getBounds(); @@ -309,16 +315,18 @@ private void doPaint(GC gc, int width, int height) { */ private void doPaint(GC gc) { ILineRange visibleModelLines= computeVisibleModelLines(); - if (visibleModelLines == null) + if (visibleModelLines == null) { return; + } fSensitiveToTextChanges= isViewerCompletelyShown(); fScrollPos= fCachedTextWidget.getTopPixel(); fRevisionPainter.paint(gc, visibleModelLines); - if (!fRevisionPainter.hasInformation()) // don't paint quick diff colors if revisions are painted + if (!fRevisionPainter.hasInformation()) { // don't paint quick diff colors if revisions are painted fDiffPainter.paint(gc, visibleModelLines); + } } @Override @@ -362,10 +370,12 @@ public int toDocumentLineNumber(int y_coordinate) { @Override public IAnnotationHover getHover() { int activeLine= getParentRuler().getLineOfLastMouseButtonActivity(); - if (fRevisionPainter.hasHover(activeLine)) + if (fRevisionPainter.hasHover(activeLine)) { return fRevisionPainter.getHover(); - if (fDiffPainter.hasHover(activeLine)) + } + if (fDiffPainter.hasHover(activeLine)) { return fDiffPainter.getHover(); + } return null; } @@ -383,15 +393,17 @@ public void setModel(IAnnotationModel model) { } private void setAnnotationModel(IAnnotationModel model) { - if (fAnnotationModel != model) + if (fAnnotationModel != model) { fAnnotationModel= model; + } } @Override public void setBackground(Color background) { fBackground= background; - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.setBackground(getBackground()); + } fRevisionPainter.setBackground(background); fDiffPainter.setBackground(background); } @@ -456,8 +468,9 @@ public void removeVerticalRulerListener(IVerticalRulerListener listener) { */ private final ILineRange computeVisibleModelLines() { IDocument doc= fCachedTextViewer.getDocument(); - if (doc == null) + if (doc == null) { return null; + } int topLine; IRegion coverage; @@ -476,18 +489,21 @@ private final ILineRange computeVisibleModelLines() { } int bottomLine= fCachedTextViewer.getBottomIndex(); - if (bottomLine != -1) + if (bottomLine != -1) { ++ bottomLine; + } // clip by coverage window try { int firstLine= doc.getLineOfOffset(coverage.getOffset()); - if (firstLine > topLine) + if (firstLine > topLine) { topLine= firstLine; + } int lastLine= doc.getLineOfOffset(coverage.getOffset() + coverage.getLength()); - if (lastLine < bottomLine || bottomLine == -1) + if (lastLine < bottomLine || bottomLine == -1) { bottomLine= lastLine; + } } catch (BadLocationException x) { return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java index 23f6b6b8a01..7c1ea48d400 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java @@ -133,7 +133,7 @@ static class ListenerInfo { * Internal listener for opening the context menu. * @since 3.0 */ - private Listener fMenuDetectListener; + private final Listener fMenuDetectListener; /** * Creates a new composite ruler canvas. @@ -298,8 +298,9 @@ private void removeListener(Class clazz, EventListener // Keep as first statement to ensure checkWidget() is called. Control[] children= getChildren(); - if (fCachedListeners == null) // already disposed + if (fCachedListeners == null) { // already disposed return; + } int length= fCachedListeners.size(); for (int i= 0; i < length; i++) { @@ -495,18 +496,18 @@ public void addGestureListener(GestureListener listener) { /** The ruler's annotation model */ private IAnnotationModel fModel; /** The list of columns */ - private List fDecorators= new ArrayList<>(2); + private final List fDecorators= new ArrayList<>(2); /** The cached location of the last mouse button activity */ - private Point fLocation= new Point(-1, -1); + private final Point fLocation= new Point(-1, -1); /** The cached line of the list mouse button activity */ private int fLastMouseButtonActivityLine= -1; /** The gap between the individual columns of this composite ruler */ - private int fGap; + private final int fGap; /** * The set of annotation listeners. * @since 3.0 */ - private Set fAnnotationListeners= new HashSet<>(); + private final Set fAnnotationListeners= new HashSet<>(); /** @@ -535,10 +536,11 @@ public CompositeRuler(int gap) { public void addDecorator(int index, IVerticalRulerColumn rulerColumn) { rulerColumn.setModel(getModel()); - if (index > fDecorators.size()) + if (index > fDecorators.size()) { fDecorators.add(rulerColumn); - else + } else { fDecorators.add(index, rulerColumn); + } if (fComposite != null && !fComposite.isDisposed()) { rulerColumn.createControl(this, fComposite); @@ -587,8 +589,9 @@ private void layoutTextViewer() { parent= extension.getControl(); } - if (parent instanceof Composite && !parent.isDisposed()) + if (parent instanceof Composite && !parent.isDisposed()) { ((Composite) parent).layout(true, true); + } } @Override @@ -676,25 +679,28 @@ public int getWidth() { @Override public int getLineOfLastMouseButtonActivity() { - if (fLastMouseButtonActivityLine == -1) + if (fLastMouseButtonActivityLine == -1) { fLastMouseButtonActivityLine= toDocumentLineNumber(fLocation.y); - else if (fTextViewer.getDocument() == null || fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) + } else if (fTextViewer.getDocument() == null || fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) { fLastMouseButtonActivityLine= -1; + } return fLastMouseButtonActivityLine; } @Override public int toDocumentLineNumber(int y_coordinate) { - if (fTextViewer == null || y_coordinate == -1) + if (fTextViewer == null || y_coordinate == -1) { return -1; + } StyledText text= fTextViewer.getTextWidget(); int line= text.getLineIndex(y_coordinate); if (line == text.getLineCount() - 1) { // check whether y_coordinate exceeds last line - if (y_coordinate > text.getLinePixel(line + 1)) + if (y_coordinate > text.getLinePixel(line + 1)) { return -1; + } } return widgetLine2ModelLine(fTextViewer, line); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ContentAssistantFacade.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ContentAssistantFacade.java index ec0a2250b9c..4834d9bfd7f 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ContentAssistantFacade.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/ContentAssistantFacade.java @@ -33,7 +33,7 @@ */ public final class ContentAssistantFacade { - private IContentAssistant fContentAssistant; + private final IContentAssistant fContentAssistant; /** * Creates a new facade. @@ -60,8 +60,9 @@ public ContentAssistantFacade(IContentAssistant contentAssistant) { * uninstalled */ public IHandler getHandler(String commandId) { - if (fContentAssistant == null) + if (fContentAssistant == null) { throw new IllegalStateException(); + } return ((IContentAssistantExtension4)fContentAssistant).getHandler(commandId); } @@ -74,8 +75,9 @@ public IHandler getHandler(String commandId) { * uninstalled */ public void addCompletionListener(ICompletionListener listener) { - if (fContentAssistant == null) + if (fContentAssistant == null) { throw new IllegalStateException(); + } ((IContentAssistantExtension2)fContentAssistant).addCompletionListener(listener); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java index b6d391bf3d4..f5acf76da68 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java @@ -38,7 +38,7 @@ public class DefaultAnnotationHover implements IAnnotationHover { * * @since 3.4 */ - private boolean fShowLineNumber; + private final boolean fShowLineNumber; /** * Creates a new default annotation hover. @@ -69,8 +69,9 @@ public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { // optimization Annotation annotation= javaAnnotations.get(0); String message= annotation.getText(); - if (message != null && !message.trim().isEmpty()) + if (message != null && !message.trim().isEmpty()) { return formatSingleMessage(message); + } } else { @@ -80,20 +81,24 @@ public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { while (e.hasNext()) { Annotation annotation= e.next(); String message= annotation.getText(); - if (message != null && !message.trim().isEmpty()) + if (message != null && !message.trim().isEmpty()) { messages.add(message.trim()); + } } - if (messages.size() == 1) + if (messages.size() == 1) { return formatSingleMessage(messages.get(0)); + } - if (messages.size() > 1) + if (messages.size() > 1) { return formatMultipleMessages(messages); + } } } - if (fShowLineNumber && lineNumber > -1) + if (fShowLineNumber && lineNumber > -1) { return JFaceTextMessages.getFormattedString("DefaultAnnotationHover.lineNumber", Integer.toString(lineNumber + 1)); //$NON-NLS-1$ + } return null; } @@ -166,14 +171,16 @@ private IAnnotationModel getAnnotationModel(ISourceViewer viewer) { private boolean isDuplicateAnnotation(Map messagesAtPosition, Position position, String message) { if (messagesAtPosition.containsKey(position)) { Object value= messagesAtPosition.get(position); - if (message.equals(value)) + if (message.equals(value)) { return true; + } if (value instanceof List) { @SuppressWarnings("unchecked") List messages= (List) value; - if (messages.contains(message)) + if (messages.contains(message)) { return true; + } messages.add(message); } else { @@ -182,14 +189,16 @@ private boolean isDuplicateAnnotation(Map messagesAtPosition, messages.add(message); messagesAtPosition.put(position, messages); } - } else + } else { messagesAtPosition.put(position, message); + } return false; } private boolean includeAnnotation(Annotation annotation, Position position, HashMap messagesAtPosition) { - if (!isIncluded(annotation)) + if (!isIncluded(annotation)) { return false; + } String text= annotation.getText(); return (text != null && !isDuplicateAnnotation(messagesAtPosition, position, text)); @@ -197,8 +206,9 @@ private boolean includeAnnotation(Annotation annotation, Position position, Hash private List getAnnotationsForLine(ISourceViewer viewer, int line) { IAnnotationModel model= getAnnotationModel(viewer); - if (model == null) + if (model == null) { return null; + } IDocument document= viewer.getDocument(); List javaAnnotations= new ArrayList<>(); @@ -209,25 +219,29 @@ private List getAnnotationsForLine(ISourceViewer viewer, int line) { Annotation annotation= iterator.next(); Position position= model.getPosition(annotation); - if (position == null) + if (position == null) { continue; + } - if (!isRulerLine(position, document, line)) + if (!isRulerLine(position, document, line)) { continue; + } if (annotation instanceof AnnotationBag bag) { Iterator e= bag.iterator(); while (e.hasNext()) { annotation= e.next(); position= model.getPosition(annotation); - if (position != null && includeAnnotation(annotation, position, messagesAtPosition)) + if (position != null && includeAnnotation(annotation, position, messagesAtPosition)) { javaAnnotations.add(annotation); + } } continue; } - if (includeAnnotation(annotation, position, messagesAtPosition)) + if (includeAnnotation(annotation, position, messagesAtPosition)) { javaAnnotations.add(annotation); + } } return javaAnnotations; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultCharacterPairMatcher.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultCharacterPairMatcher.java index cce89f88514..08e7a3f9f12 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultCharacterPairMatcher.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultCharacterPairMatcher.java @@ -99,7 +99,9 @@ public DefaultCharacterPairMatcher(char[] chars) { @Override public IRegion match(IDocument doc, int offset) { - if (doc == null || offset < 0 || offset > doc.getLength()) return null; + if (doc == null || offset < 0 || offset > doc.getLength()) { + return null; + } try { return performMatch(doc, offset); } catch (BadLocationException ble) { @@ -114,15 +116,17 @@ public IRegion match(IDocument doc, int offset) { */ @Override public IRegion match(IDocument document, int offset, int length) { - if (document == null || offset < 0 || offset > document.getLength() || Math.abs(length) > 1) + if (document == null || offset < 0 || offset > document.getLength() || Math.abs(length) > 1) { return null; + } try { int sourceCaretOffset= offset + length; if (Math.abs(length) == 1) { char ch= length > 0 ? document.getChar(offset) : document.getChar(sourceCaretOffset); - if (!fPairs.contains(ch)) + if (!fPairs.contains(ch)) { return null; + } } int adjustment= getOffsetAdjustment(document, sourceCaretOffset, length); sourceCaretOffset+= adjustment; @@ -139,8 +143,9 @@ public IRegion match(IDocument document, int offset, int length) { */ @Override public IRegion findEnclosingPeerCharacters(IDocument document, int offset, int length) { - if (document == null || offset < 0 || offset > document.getLength()) + if (document == null || offset < 0 || offset > document.getLength()) { return null; + } //maybe a bracket is selected IRegion region= match(document, offset, length); @@ -154,8 +159,9 @@ public IRegion findEnclosingPeerCharacters(IDocument document, int offset, int l final String partition= TextUtilities.getContentType(document, fPartitioning, offset, false); DocumentPartitionAccessor partDoc= new DocumentPartitionAccessor(document, fPartitioning, partition); IRegion enclosingPeers= findEnclosingPeers(document, partDoc, offset, length, 0, document.getLength()); - if (enclosingPeers != null) + if (enclosingPeers != null) { return enclosingPeers; + } partDoc= new DocumentPartitionAccessor(document, fPartitioning, IDocument.DEFAULT_CONTENT_TYPE); return findEnclosingPeers(document, partDoc, offset, length, 0, document.getLength()); } catch (BadLocationException ble) { @@ -198,13 +204,15 @@ public boolean isRecomputationOfEnclosingPairRequired(IDocument document, IRegio try { String prevEndContentType= TextUtilities.getContentType(document, fPartitioning, previousEndOffset, false); String currEndContentType= TextUtilities.getContentType(document, fPartitioning, currentEndOffset, false); - if (!prevEndContentType.equals(currEndContentType)) + if (!prevEndContentType.equals(currEndContentType)) { return true; + } String prevStartContentType= TextUtilities.getContentType(document, fPartitioning, previousStartOffset, true); String currStartContentType= TextUtilities.getContentType(document, fPartitioning, currentStartOffset, true); - if (!prevStartContentType.equals(currStartContentType)) + if (!prevStartContentType.equals(currStartContentType)) { return true; + } int start; int end; @@ -250,8 +258,9 @@ public boolean isRecomputationOfEnclosingPairRequired(IDocument document, IRegio * @since 3.8 */ private int getOffsetAdjustment(IDocument document, int offset, int length) { - if (length == 0 || Math.abs(length) > 1 || offset >= document.getLength()) + if (length == 0 || Math.abs(length) > 1 || offset >= document.getLength()) { return 0; + } try { if (length < 0) { if (fPairs.isStartCharacter(document.getChar(offset))) { @@ -294,8 +303,9 @@ private IRegion performMatch(IDocument doc, int caretOffset) throws BadLocationE } ch= isForward ? prevChar : currChar; } else { - if (!fPairs.contains(prevChar)) + if (!fPairs.contains(prevChar)) { return null; + } isForward= fPairs.isStartCharacter(prevChar); ch= prevChar; } @@ -307,11 +317,13 @@ private IRegion performMatch(IDocument doc, int caretOffset) throws BadLocationE final DocumentPartitionAccessor partDoc= new DocumentPartitionAccessor(doc, fPartitioning, partition); int endOffset= findMatchingPeer(partDoc, ch, fPairs.getMatching(ch), isForward, isForward ? doc.getLength() : -1, searchStartPosition); - if (endOffset == -1) + if (endOffset == -1) { return null; + } final int adjustedEndOffset= isForward ? endOffset + 1 : endOffset; - if (adjustedEndOffset == adjustedOffset) + if (adjustedEndOffset == adjustedOffset) { return null; + } return new Region(Math.min(adjustedOffset, adjustedEndOffset), Math.abs(adjustedEndOffset - adjustedOffset)); } @@ -334,8 +346,9 @@ private int findMatchingPeer(DocumentPartitionAccessor doc, char start, char end while (pos != boundary) { final char c= doc.getChar(pos); if (c == end && doc.inPartition(pos)) { - if (nestingLevel == 0) + if (nestingLevel == 0) { return pos; + } nestingLevel--; } else if (c == start && doc.inPartition(pos)) { nestingLevel++; @@ -427,8 +440,9 @@ private IRegion findEnclosingPeers(IDocument document, DocumentPartitionAccessor } } pos2++; - if (pos1 < lowerBoundary || pos2 > upperBoundary) + if (pos1 < lowerBoundary || pos2 > upperBoundary) { return null; + } return new Region(pos1, pos2 - pos1); } @@ -477,7 +491,7 @@ private static class DocumentPartitionAccessor { private final IDocument fDocument; private final String fPartitioning, fPartition; private ITypedRegion fCachedPartition; - private int fLength; + private final int fLength; /** * Creates a new partitioned document for the specified document. @@ -527,16 +541,19 @@ public boolean inPartition(int pos) { */ public int getNextPosition(int pos, boolean searchForward) { final ITypedRegion partition= getPartition(pos); - if (partition == null || fPartition.equals(partition.getType())) + if (partition == null || fPartition.equals(partition.getType())) { return simpleIncrement(pos, searchForward); + } if (searchForward) { int end= partition.getOffset() + partition.getLength(); - if (pos < end) + if (pos < end) { return end; + } } else { int offset= partition.getOffset(); - if (pos > offset) + if (pos > offset) { return offset - 1; + } } return simpleIncrement(pos, searchForward); } @@ -592,8 +609,9 @@ public CharPairs(char[] pairs) { public boolean contains(char c) { char[] pairs= fPairs; for (char pair : pairs) { - if (c == pair) + if (c == pair) { return true; + } } return false; } @@ -608,8 +626,11 @@ public boolean contains(char c) { */ public boolean isOpeningCharacter(char c, boolean searchForward) { for (int i= 0; i < fPairs.length; i += 2) { - if (searchForward && getStartChar(i) == c) return true; - else if (!searchForward && getEndChar(i) == c) return true; + if (searchForward && getStartChar(i) == c) { + return true; + } else if (!searchForward && getEndChar(i) == c) { + return true; + } } return false; } @@ -643,8 +664,11 @@ public boolean isEndCharacter(char c) { */ public char getMatching(char c) { for (int i= 0; i < fPairs.length; i += 2) { - if (getStartChar(i) == c) return getEndChar(i); - else if (getEndChar(i) == c) return getStartChar(i); + if (getStartChar(i) == c) { + return getEndChar(i); + } else if (getEndChar(i) == c) { + return getStartChar(i); + } } Assert.isTrue(false); return '\0'; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java index e922e45605c..f32315dbb49 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java @@ -51,8 +51,9 @@ protected String formatSource(String content) { StringBuilder sb= new StringBuilder(content); final String tabReplacement= getTabReplacement(); for (int pos= 0; pos < sb.length(); pos++) { - if (sb.charAt(pos) == '\t') + if (sb.charAt(pos) == '\t') { sb.replace(pos, pos + 1, tabReplacement); + } } return sb.toString(); } @@ -85,14 +86,16 @@ protected String getTabReplacement() { */ private String computeContent(ISourceViewer viewer, int first, int last, int maxLines) { ILineDiffer differ= getDiffer(viewer); - if (differ == null) + if (differ == null) { return null; + } final List lines= new LinkedList<>(); for (int l= first; l <= last; l++) { ILineDiffInfo info= differ.getLineInfo(l); - if (info != null) + if (info != null) { lines.add(info); + } } return decorateText(lines, maxLines); @@ -122,21 +125,23 @@ protected String decorateText(List diffInfos, int maxLi String[] original= info.getOriginalText(); int type= info.getChangeType(); int i= 0; - if (type == ILineDiffInfo.ADDED) + if (type == ILineDiffInfo.ADDED) { added++; - else if (type == ILineDiffInfo.CHANGED) { + } else if (type == ILineDiffInfo.CHANGED) { text.append("> ").append(original.length > 0 ? original[i++] : ""); //$NON-NLS-1$ //$NON-NLS-2$ maxLines--; } else if (type == ILineDiffInfo.UNCHANGED) { maxLines++; } - if (maxLines == 0) + if (maxLines == 0) { return trimTrailing(text.toString()); + } for (; i < original.length; i++) { text.append("- ").append( original[i]); //$NON-NLS-1$ added--; - if (--maxLines == 0) + if (--maxLines == 0) { return trimTrailing(text.toString()); + } } } @@ -172,17 +177,20 @@ private String trimTrailing(String text) { private ILineDiffer getDiffer(ISourceViewer viewer) { IAnnotationModel model= viewer.getAnnotationModel(); - if (model == null) + if (model == null) { return null; + } if (model instanceof IAnnotationModelExtension) { IAnnotationModel diffModel= ((IAnnotationModelExtension)model).getAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID); - if (diffModel != null) + if (diffModel != null) { model= diffModel; + } } if (model instanceof ILineDiffer) { - if (model instanceof ILineDifferExtension2 && ((ILineDifferExtension2)model).isSuspended()) + if (model instanceof ILineDifferExtension2 && ((ILineDifferExtension2)model).isSuspended()) { return null; + } return (ILineDiffer)model; } return null; @@ -213,8 +221,9 @@ protected Point computeLineRange(ISourceViewer viewer, int line, int min, int ma */ ILineDiffer differ= getDiffer(viewer); - if (differ == null) + if (differ == null) { return new Point(-1, -1); + } // backward search @@ -263,8 +272,9 @@ private int adaptFirstLine(ISourceViewer viewer, int startLine) { if (differ != null && startLine > 0) { int l= startLine - 1; ILineDiffInfo info= differ.getLineInfo(l); - if (info != null && info.getChangeType() == ILineDiffInfo.UNCHANGED && info.getRemovedLinesBelow() > 0) + if (info != null && info.getChangeType() == ILineDiffInfo.UNCHANGED && info.getRemovedLinesBelow() > 0) { return l; + } } return startLine; } @@ -282,8 +292,9 @@ private int adaptLastLine(ISourceViewer viewer, int lastLine) { ILineDiffer differ= getDiffer(viewer); if (differ != null && lastLine > 0) { ILineDiffInfo info= differ.getLineInfo(lastLine); - if (info != null && info.getChangeType() == ILineDiffInfo.UNCHANGED) + if (info != null && info.getChangeType() == ILineDiffInfo.UNCHANGED) { return lastLine - 1; + } } return lastLine; } @@ -293,8 +304,9 @@ public ILineRange getHoverLineRange(ISourceViewer viewer, int lineNumber) { IDocument document= viewer.getDocument(); if (document != null) { Point range= computeLineRange(viewer, lineNumber, 0, Math.max(0, document.getNumberOfLines() - 1)); - if (range.x != -1 && range.y != -1) + if (range.x != -1 && range.y != -1) { return new LineRange(range.x, range.y - range.x + 1); + } } return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberChangeRulerColumn.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberChangeRulerColumn.java index 214cdd73f16..1333852da6c 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberChangeRulerColumn.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberChangeRulerColumn.java @@ -101,8 +101,9 @@ public void setModel(IAnnotationModel model) { } private void setAnnotationModel(IAnnotationModel model) { - if (fAnnotationModel != model) + if (fAnnotationModel != model) { fAnnotationModel= model; + } } @@ -129,10 +130,12 @@ public IAnnotationModel getModel() { @Override protected String createDisplayString(int line) { StringBuilder buffer= new StringBuilder(); - if (fShowNumbers) + if (fShowNumbers) { buffer.append(super.createDisplayString(line)); - if (fCharacterDisplay && getModel() != null) + } + if (fCharacterDisplay && getModel() != null) { buffer.append(fDiffPainter.getDisplayCharacter(line)); + } return buffer.toString(); } @@ -140,18 +143,21 @@ protected String createDisplayString(int line) { protected int computeNumberOfDigits() { int digits; if (fCharacterDisplay && getModel() != null) { - if (fShowNumbers) + if (fShowNumbers) { digits= super.computeNumberOfDigits() + 1; - else + } else { digits= 1; + } } else { - if (fShowNumbers) + if (fShowNumbers) { digits= super.computeNumberOfDigits(); - else + } else { digits= 0; + } } - if (fRevisionPainter.hasInformation()) + if (fRevisionPainter.hasInformation()) { digits+= fRevisionPainter.getRequiredWidth(); + } return digits; } @@ -176,17 +182,20 @@ void doPaint(GC gc, ILineRange visibleLines) { } } gc.setForeground(foreground); - if (fShowNumbers || fCharacterDisplay) + if (fShowNumbers || fCharacterDisplay) { super.doPaint(gc, visibleLines); + } } @Override public IAnnotationHover getHover() { int activeLine= getParentRuler().getLineOfLastMouseButtonActivity(); - if (fRevisionPainter.hasHover(activeLine)) + if (fRevisionPainter.hasHover(activeLine)) { return fRevisionPainter.getHover(); - if (fDiffPainter.hasHover(activeLine)) + } + if (fDiffPainter.hasHover(activeLine)) { return fDiffPainter.getHover(); + } return null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberRulerColumn.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberRulerColumn.java index f3f245f1829..2a91e3f0f91 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberRulerColumn.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineNumberRulerColumn.java @@ -70,8 +70,9 @@ class InternalListener implements ITextListener { public void textChanged(TextEvent event) { boolean fCachedRedrawState= event.getViewerRedrawState(); - if (!fCachedRedrawState) + if (!fCachedRedrawState) { return; + } if (updateNumberOfDigits()) { computeIndentations(); @@ -145,8 +146,9 @@ private void startSelecting(boolean expandExistingSelection) { IDocument document= fCachedTextViewer.getDocument(); int lineNumber= fParentRuler.getLineOfLastMouseButtonActivity(); final StyledText textWidget= fCachedTextViewer.getTextWidget(); - if (textWidget != null && !textWidget.isFocusControl()) + if (textWidget != null && !textWidget.isFocusControl()) { textWidget.setFocus(); + } if (expandExistingSelection && fCachedTextViewer instanceof ITextViewerExtension5 extension5 && textWidget != null) { // Find model cursor position int widgetCaret= textWidget.getCaretOffset(); @@ -205,9 +207,9 @@ private void expandSelection(int lineNumber) { int offset; - if (relativePosition.x < 0) + if (relativePosition.x < 0) { offset= lineInfo.getOffset(); - else { + } else { int widgetOffset= fCachedTextWidget.getOffsetAtPoint(relativePosition); if (widgetOffset != -1) { Point p= fCachedTextWidget.getLocationAtOffset(widgetOffset); @@ -228,24 +230,27 @@ private void expandSelection(int lineNumber) { int lineEndWidgetOffset; if (fCachedTextViewer instanceof ITextViewerExtension5 extension) { lineEndWidgetOffset= extension.modelOffset2WidgetOffset(lineEndOffset); - } else + } else { lineEndWidgetOffset= lineEndOffset - fCachedTextViewer.getVisibleRegion().getOffset(); + } Point p= fCachedTextWidget.getLocationAtOffset(lineEndWidgetOffset); - if (p.x < relativePosition.x) + if (p.x < relativePosition.x) { offset= lineEndOffset; - else + } else { offset= lineInfo.getOffset(); + } } } int start= Math.min(fStartLineOffset, offset); int end= Math.max(fStartLineOffset, offset); - if (lineNumber < fStartLineNumber) + if (lineNumber < fStartLineNumber) { fCachedTextViewer.setSelectedRange(end, start - end); - else + } else { fCachedTextViewer.setSelectedRange(start, end - start); + } } catch (BadLocationException x) { } @@ -288,8 +293,9 @@ private boolean autoScroll(MouseEvent event) { */ private void autoScroll(int direction) { - if (fAutoScrollDirection == direction) + if (fAutoScrollDirection == direction) { return; + } final int TIMER_INTERVAL= 5; final Display display= fCanvas.getDisplay(); @@ -360,7 +366,7 @@ public void mouseScrolled(MouseEvent e) { /** The drawable for double buffering */ private Image fBuffer; /** The internal listener */ - private ITextListener fInternalListener= new InternalListener(); + private final ITextListener fInternalListener= new InternalListener(); /** The font of this column */ private Font fFont; /** The indentation cache */ @@ -387,7 +393,7 @@ public void mouseScrolled(MouseEvent e) { * Redraw runnable lock * @since 3.0 */ - private Object fRunnableLock= new Object(); + private final Object fRunnableLock= new Object(); /** * Redraw runnable state * @since 3.0 @@ -397,7 +403,7 @@ public void mouseScrolled(MouseEvent e) { * Redraw runnable * @since 3.0 */ - private Runnable fRunnable= () -> { + private final Runnable fRunnable= () -> { synchronized (fRunnableLock) { fIsRunnablePosted= false; } @@ -411,7 +417,7 @@ public void mouseScrolled(MouseEvent e) { * * @since 3.13 */ - private Consumer lineHeightChangeHandler= t -> postRedraw(); + private final Consumer lineHeightChangeHandler= t -> postRedraw(); /** * Constructs a new vertical ruler column. @@ -445,8 +451,9 @@ protected Color getForeground() { */ public void setBackground(Color background) { fBackground= background; - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.setBackground(getBackground(fCanvas.getDisplay())); + } } /** @@ -456,8 +463,9 @@ public void setBackground(Color background) { * @return the System background color for list widgets */ protected Color getBackground(Display display) { - if (fBackground == null) + if (fBackground == null) { return display.getSystemColor(SWT.COLOR_LIST_BACKGROUND); + } return fBackground; } @@ -484,8 +492,9 @@ public int getWidth() { * @since 3.0 */ protected boolean updateNumberOfDigits() { - if (fCachedTextViewer == null) + if (fCachedTextViewer == null) { return false; + } int digits= computeNumberOfDigits(); @@ -540,8 +549,9 @@ protected void layout(boolean redraw) { * fIndentation. */ protected void computeIndentations() { - if (fCanvas == null || fCanvas.isDisposed()) + if (fCanvas == null || fCanvas.isDisposed()) { return; + } GC gc= new GC(fCanvas); try { @@ -591,9 +601,9 @@ public void controlResized(ControlEvent e) { @Override public void addMouseListener(MouseListener listener) { // see bug 40889, bug 230073 and AnnotationRulerColumn#isPropagatingMouseListener() - if (listener == fMouseHandler) + if (listener == fMouseHandler) { super.addMouseListener(listener); - else { + } else { addTypedListener(listener, SWT.MouseDoubleClick); } } @@ -602,8 +612,9 @@ public void addMouseListener(MouseListener listener) { fCanvas.setForeground(fForeground); fCanvas.addPaintListener(event -> { - if (fCachedTextViewer != null) + if (fCachedTextViewer != null) { doubleBufferPaint(event.gc); + } }); fCanvas.addDisposeListener(e -> { @@ -631,12 +642,14 @@ public void addMouseListener(MouseListener listener) { fCachedTextViewer.addTextListener(fInternalListener); if (fFont == null) { - if (!fCachedTextWidget.isDisposed()) + if (!fCachedTextWidget.isDisposed()) { fFont= fCachedTextWidget.getFont(); + } } - if (fFont != null) + if (fFont != null) { fCanvas.setFont(fFont); + } updateNumberOfDigits(); computeIndentations(); @@ -848,8 +861,9 @@ void doPaint(GC gc, ILineRange visibleLines) { int lastLine= end(visibleLines); for (int line= visibleLines.getStartLine(); line < lastLine; line++) { int widgetLine= JFaceTextUtil.modelLineToWidgetLine(fCachedTextViewer, line); - if (widgetLine == -1) + if (widgetLine == -1) { continue; + } final int offsetAtLine= fCachedTextWidget.getOffsetAtLine(widgetLine); int lineHeight = JFaceTextUtil.computeLineHeight(fCachedTextWidget, widgetLine, widgetLine + 1, 1); @@ -860,14 +874,16 @@ void doPaint(GC gc, ILineRange visibleLines) { y+= lineHeight; } else { int charCount= fCachedTextWidget.getCharCount(); - if (offsetAtLine == charCount) + if (offsetAtLine == charCount) { continue; + } // end of wrapped line final int offsetEnd= offsetAtLine + fCachedTextWidget.getLine(widgetLine).length(); - if (offsetEnd == charCount) + if (offsetEnd == charCount) { continue; + } // use height of text bounding because bounds.width changes on word wrap y+= fCachedTextWidget.getTextBounds(offsetAtLine, offsetEnd).height; @@ -957,8 +973,9 @@ protected final void postRedraw() { Display d= fCanvas.getDisplay(); if (d != null) { synchronized (fRunnableLock) { - if (fIsRunnablePosted) + if (fIsRunnablePosted) { return; + } fIsRunnablePosted= true; } d.asyncExec(fRunnable); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineRange.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineRange.java index 8d7579290d9..b8a73ee725c 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineRange.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineRange.java @@ -20,8 +20,8 @@ */ public final class LineRange implements ILineRange { - private int fStartLine; - private int fNumberOfLines; + private final int fStartLine; + private final int fNumberOfLines; /** * Creates a new line range with the given specification. diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/MatchingCharacterPainter.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/MatchingCharacterPainter.java index 64936fa3fd8..f63a54c6c1d 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/MatchingCharacterPainter.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/MatchingCharacterPainter.java @@ -49,7 +49,7 @@ public final class MatchingCharacterPainter implements IPainter, PaintListener { /** Indicates whether this painter is active */ private boolean fIsActive= false; /** The source viewer this painter is associated with */ - private ISourceViewer fSourceViewer; + private final ISourceViewer fSourceViewer; /** The viewer's widget */ private StyledText fTextWidget; /** The color in which to highlight the peer character */ @@ -59,7 +59,7 @@ public final class MatchingCharacterPainter implements IPainter, PaintListener { /** The strategy for finding matching characters */ private ICharacterPairMatcher fMatcher; /** The position tracking the matching characters */ - private Position fPairPosition= new Position(0, 0); + private final Position fPairPosition= new Position(0, 0); /** The anchor indicating whether the character is left or right of the caret */ private int fAnchor; @@ -171,18 +171,21 @@ public void deactivate(boolean redraw) { if (fIsActive) { fIsActive= false; fTextWidget.removePaintListener(this); - if (fPaintPositionManager != null) + if (fPaintPositionManager != null) { fPaintPositionManager.unmanagePosition(fPairPosition); - if (redraw) + } + if (redraw) { handleDrawRequest(null); + } } fPreviousSelection= null; } @Override public void paintControl(PaintEvent event) { - if (fTextWidget != null) + if (fTextWidget != null) { handleDrawRequest(event.gc); + } } /** @@ -192,18 +195,21 @@ public void paintControl(PaintEvent event) { */ private void handleDrawRequest(GC gc) { - if (fPairPosition.isDeleted) + if (fPairPosition.isDeleted) { return; + } int offset= fPairPosition.getOffset(); int length= fPairPosition.getLength(); - if (length < 1) + if (length < 1) { return; + } if (fSourceViewer instanceof ITextViewerExtension5 extension) { IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length)); - if (widgetRange == null) + if (widgetRange == null) { return; + } try { // don't draw if the pair position is really hidden and widgetRange just @@ -211,8 +217,9 @@ private void handleDrawRequest(GC gc) { IDocument doc= fSourceViewer.getDocument(); int startLine= doc.getLineOfOffset(offset); int endLine= doc.getLineOfOffset(offset + length); - if (extension.modelLine2WidgetLine(startLine) == -1 || extension.modelLine2WidgetLine(endLine) == -1) + if (extension.modelLine2WidgetLine(startLine) == -1 || extension.modelLine2WidgetLine(endLine) == -1) { return; + } } catch (BadLocationException e) { return; } @@ -222,8 +229,9 @@ private void handleDrawRequest(GC gc) { } else { IRegion region= fSourceViewer.getVisibleRegion(); - if (region.getOffset() > offset || region.getOffset() + region.getLength() < offset + length) + if (region.getOffset() > offset || region.getOffset() + region.getLength() < offset + length) { return; + } offset -= region.getOffset(); } @@ -231,10 +239,11 @@ private void handleDrawRequest(GC gc) { draw(gc, offset); draw(gc, offset + length - 1); } else { - if (ICharacterPairMatcher.RIGHT == fAnchor) + if (ICharacterPairMatcher.RIGHT == fAnchor) { draw(gc, offset); - else + } else { draw(gc, offset + length - 1); + } } } @@ -401,8 +410,9 @@ public void setPositionManager(IPaintPositionManager manager) { * @since 3.8 */ private void installUninstallTextListener(boolean install) { - if (!(fMatcher instanceof ICharacterPairMatcherExtension)) + if (!(fMatcher instanceof ICharacterPairMatcherExtension)) { return; + } if (install) { fTextListener= new TextListener(); @@ -428,17 +438,20 @@ private class TextListener implements ITextListener { */ @Override public void textChanged(TextEvent event) { - if (!fHighlightEnclosingPeerCharacters || !(fMatcher instanceof ICharacterPairMatcherExtension)) + if (!fHighlightEnclosingPeerCharacters || !(fMatcher instanceof ICharacterPairMatcherExtension)) { return; + } - if (!event.getViewerRedrawState()) + if (!event.getViewerRedrawState()) { return; + } String text= event.getText(); String replacedText= event.getReplacedText(); ICharacterPairMatcherExtension matcher= (ICharacterPairMatcherExtension)fMatcher; - if (searchForCharacters(text, matcher) || searchForCharacters(replacedText, matcher)) + if (searchForCharacters(text, matcher) || searchForCharacters(replacedText, matcher)) { paint(IPainter.INTERNAL); + } } /** @@ -449,8 +462,9 @@ public void textChanged(TextEvent event) { * @return true if a matched character is found, false otherwise */ private boolean searchForCharacters(String text, ICharacterPairMatcherExtension matcher) { - if (text == null) + if (text == null) { return false; + } for (int i= 0; i < text.length(); i++) { if (matcher.isMatchedChar(text.charAt(i))) { return true; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java index 709217134e3..b16655ba3b9 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java @@ -94,8 +94,9 @@ public void modelChanged(IAnnotationModel model) { @Override public void modelChanged(AnnotationModelEvent event) { - if (!event.isValid()) + if (!event.isValid()) { return; + } if (event.isWorldChange()) { update(); @@ -143,9 +144,9 @@ class FilterIterator implements Iterator { final static int IGNORE_BAGS= 1 << 3; private Iterator fIterator; - private Object fType; + private final Object fType; private Annotation fNext; - private int fStyle; + private final int fStyle; /** * Creates a new filter iterator with the given specification. @@ -185,18 +186,26 @@ private void skip() { while (fIterator.hasNext()) { Annotation next= fIterator.next(); - if (next.isMarkedDeleted()) + if (next.isMarkedDeleted()) { continue; + } - if (ignr && (next instanceof AnnotationBag)) + if (ignr && (next instanceof AnnotationBag)) { continue; + } fNext= next; Object annotationType= next.getType(); if (fType == null || fType.equals(annotationType) || !fConfiguredAnnotationTypes.contains(annotationType) && isSubtype(annotationType)) { - if (temp && pers) return; - if (pers && next.isPersistent()) return; - if (temp && !next.isPersistent()) return; + if (temp && pers) { + return; + } + if (pers && next.isPersistent()) { + return; + } + if (temp && !next.isPersistent()) { + return; + } } } fNext= null; @@ -218,8 +227,9 @@ public Annotation next() { try { return fNext; } finally { - if (fIterator != null) + if (fIterator != null) { skip(); + } } } @Override @@ -234,7 +244,7 @@ public void remove() { class HeaderPainter implements PaintListener { private Color fIndicatorColor; - private Color fSeparatorColor; + private final Color fSeparatorColor; /** * Creates a new header painter. @@ -264,8 +274,9 @@ private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topLeft, Col @Override public void paintControl(PaintEvent e) { - if (fIndicatorColor == null) + if (fIndicatorColor == null) { return; + } Point s= fHeader.getSize(); @@ -405,9 +416,9 @@ public WidgetInfos(StyledText textWidget, Canvas canvas) { /** The buffer for double buffering */ private Image fBuffer; /** The internal listener */ - private InternalListener fInternalListener= new InternalListener(); + private final InternalListener fInternalListener= new InternalListener(); /** The width of this vertical ruler */ - private int fWidth; + private final int fWidth; /** The hit detection cursor. Do not dispose. */ private Cursor fHitDetectionCursor; /** The last cursor. Do not dispose. */ @@ -417,60 +428,60 @@ public WidgetInfos(StyledText textWidget, Canvas canvas) { /** The actual annotation height */ private int fAnnotationHeight= -1; /** The annotation access */ - private IAnnotationAccess fAnnotationAccess; + private final IAnnotationAccess fAnnotationAccess; /** The header painter */ private HeaderPainter fHeaderPainter; /** * The list of annotation types to be shown in this ruler. * @since 3.0 */ - private Set fConfiguredAnnotationTypes= new HashSet<>(); + private final Set fConfiguredAnnotationTypes= new HashSet<>(); /** * The list of annotation types to be shown in the header of this ruler. * @since 3.0 */ - private Set fConfiguredHeaderAnnotationTypes= new HashSet<>(); + private final Set fConfiguredHeaderAnnotationTypes= new HashSet<>(); /** The mapping between annotation types and colors */ - private Map fAnnotationTypes2Colors= new HashMap<>(); + private final Map fAnnotationTypes2Colors= new HashMap<>(); /** The color manager */ - private ISharedTextColors fSharedTextColors; + private final ISharedTextColors fSharedTextColors; /** * All available annotation types sorted by layer. * * @since 3.0 */ - private List fAnnotationsSortedByLayer= new ArrayList<>(); + private final List fAnnotationsSortedByLayer= new ArrayList<>(); /** * All available layers sorted by layer. * This list may contain duplicates. * @since 3.0 */ - private List fLayersSortedByLayer= new ArrayList<>(); + private final List fLayersSortedByLayer= new ArrayList<>(); /** * Map of allowed annotation types. * An allowed annotation type maps to true, a disallowed * to false. * @since 3.0 */ - private Map fAllowedAnnotationTypes= new HashMap<>(); + private final Map fAllowedAnnotationTypes= new HashMap<>(); /** * Map of allowed header annotation types. * An allowed annotation type maps to true, a disallowed * to false. * @since 3.0 */ - private Map fAllowedHeaderAnnotationTypes= new HashMap<>(); + private final Map fAllowedHeaderAnnotationTypes= new HashMap<>(); /** * The cached annotations. * @since 3.0 */ - private List fCachedAnnotations= new ArrayList<>(); + private final List fCachedAnnotations= new ArrayList<>(); /** * Redraw runnable lock * @since 3.3 */ - private Object fRunnableLock= new Object(); + private final Object fRunnableLock= new Object(); /** * Redraw runnable state * @since 3.3 @@ -480,7 +491,7 @@ public WidgetInfos(StyledText textWidget, Canvas canvas) { * Redraw runnable * @since 3.3 */ - private Runnable fRunnable= () -> { + private final Runnable fRunnable= () -> { synchronized (fRunnableLock) { fIsRunnablePosted= false; } @@ -494,7 +505,7 @@ public WidgetInfos(StyledText textWidget, Canvas canvas) { * * @since 3.4 */ - private boolean fIsTemporaryAnnotationDiscolored; + private final boolean fIsTemporaryAnnotationDiscolored; /** * Tells whether saturated colors are used in the overview ruler. @@ -550,13 +561,15 @@ public int getWidth() { public void setModel(IAnnotationModel model) { if (model != fModel || model != null) { - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(fInternalListener); + } fModel= model; - if (fModel != null) + if (fModel != null) { fModel.addAnnotationModelListener(fInternalListener); + } update(); } @@ -587,8 +600,9 @@ public void mouseEnter(MouseEvent e) { fCanvas= new Canvas(parent, SWT.NO_BACKGROUND); fCanvas.addPaintListener(event -> { - if (fTextViewer != null) + if (fTextViewer != null) { doubleBufferPaint(event.gc); + } }); fCanvas.addDisposeListener(event -> { @@ -644,8 +658,9 @@ private void handleDispose() { fTextViewer= null; } - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(fInternalListener); + } if (fBuffer != null) { fBuffer.dispose(); @@ -672,8 +687,9 @@ private void doubleBufferPaint(GC dest) { Point size= fCanvas.getSize(); - if (size.x <= 0 || size.y <= 0) + if (size.x <= 0 || size.y <= 0) { return; + } if (fBuffer != null) { Rectangle r= fBuffer.getBounds(); @@ -712,11 +728,13 @@ private void cacheAnnotations() { while (iter.hasNext()) { Annotation annotation= iter.next(); - if (annotation.isMarkedDeleted()) + if (annotation.isMarkedDeleted()) { continue; + } - if (skip(annotation.getType())) + if (skip(annotation.getType())) { continue; + } fCachedAnnotations.add(annotation); } @@ -737,16 +755,18 @@ private void doPaint(GC gc) { StyledText textWidget= fTextViewer.getTextWidget(); ITextViewerExtension5 extension= null; IRegion visible= null; - if (fTextViewer instanceof ITextViewerExtension5) + if (fTextViewer instanceof ITextViewerExtension5) { extension= (ITextViewerExtension5) fTextViewer; - else + } else { visible= fTextViewer.getVisibleRegion(); // legacy support + } WidgetInfos infos= null; for (Object annotationType : fAnnotationsSortedByLayer) { - if (skip(annotationType)) + if (skip(annotationType)) { continue; + } int[] style= new int[] { FilterIterator.PERSISTENT, FilterIterator.TEMPORARY }; for (int element : style) { @@ -759,10 +779,12 @@ private void doPaint(GC gc) { Annotation a= e.next(); Position p= fModel.getPosition(a); - if (p == null) + if (p == null) { continue; - if (visible != null && !p.overlapsWith(visible.getOffset(), visible.getLength())) + } + if (visible != null && !p.overlapsWith(visible.getOffset(), visible.getLength())) { continue; + } int annotationOffset= p.getOffset(); int annotationLength= p.getLength(); @@ -774,8 +796,9 @@ private void doPaint(GC gc) { } else { ITextViewerExtension5 ext= extension; widgetRegion= ext.modelRange2WidgetRange(new Region(annotationOffset, annotationLength)); - if (widgetRegion == null) + if (widgetRegion == null) { continue; + } } if (infos == null) { @@ -821,8 +844,9 @@ private void doPaint(GC gc) { if (stroke != null) { gc.setForeground(stroke); r.y= yy; - if (yy + hh == infos.bounds.height) + if (yy + hh == infos.bounds.height) { r.y--; + } r.height= hh; gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance gc.drawRectangle(r); @@ -837,8 +861,9 @@ private void doPaint(GC gc) { if (DEBUG_DRAW) { // draw debugging guides (boundaries): - if (infos == null) + if (infos == null) { infos= new WidgetInfos(textWidget, fCanvas); + } gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_DARK_MAGENTA)); yy= infos.thumbHeight / 2; gc.drawLine(0, yy, infos.bounds.x/2, yy); @@ -867,23 +892,27 @@ private int computeY(int startLine, WidgetInfos infos) { int yy; if (infos.bounds.height > infos.writable || infos.invisibleLines <= 0) { // too few lines for relative positions: align annotations with textWidget lines yy = Math.max(0, (2 * startLine + 1) * infos.writable / (infos.maxLines * 2) - infos.bounds.y); - if (DEBUG_COMPUTE_Y) + if (DEBUG_COMPUTE_Y) { System.out.println("static: " + yy); //$NON-NLS-1$ + } } else if (startLine + 1 < infos.visibleLines / 2) { // before middle of first page: map to area from 0 to thumbHeight/2 yy= (int) (startLine * infos.thumbHeight / infos.visibleLines); // == startLine * (thumbHeight / 2) / (visibleLines / 2); - if (DEBUG_COMPUTE_Y) + if (DEBUG_COMPUTE_Y) { System.out.println("start: " + yy); //$NON-NLS-1$ + } } else if (infos.maxLines - infos.visibleLines / 2 <= startLine) { // after middle of last page: map to area from canvasHeight-1 - thumbHeight/2 to canvasHeight-1 yy= (int) (infos.bounds.height-1 - (double)infos.thumbHeight / 2 + (startLine - (infos.maxLines - infos.visibleLines / 2) + 1) * infos.thumbHeight / infos.visibleLines); - if (DEBUG_COMPUTE_Y) + if (DEBUG_COMPUTE_Y) { System.out.println("end: " + yy); //$NON-NLS-1$ + } } else { // middle of text: map to area from thumbHeight/2 to (canvasHeight-1 - thumbHeight/2) yy= (int) ((double)infos.thumbHeight/2 + (startLine + 1 - infos.visibleLines / 2) * (infos.bounds.height-1 - infos.thumbHeight) / infos.invisibleLines); - if (DEBUG_COMPUTE_Y) + if (DEBUG_COMPUTE_Y) { System.out.println("middle: " + yy); //$NON-NLS-1$ + } } // center of rectangle should be at the calculated position: yy-= ANNOTATION_HEIGHT / 2; @@ -898,8 +927,9 @@ public void update() { Display d= fCanvas.getDisplay(); if (d != null) { synchronized (fRunnableLock) { - if (fIsRunnablePosted) + if (fIsRunnablePosted) { return; + } fIsRunnablePosted= true; } d.asyncExec(fRunnable); @@ -911,8 +941,9 @@ public void update() { * Redraws the overview ruler. */ private void redraw() { - if (fTextViewer == null || fModel == null) + if (fTextViewer == null || fModel == null) { return; + } if (fCanvas != null && !fCanvas.isDisposed()) { if (VerticalRuler.AVOID_NEW_GC) { @@ -941,11 +972,13 @@ private int[] toLineNumbers(int y_coordinate, boolean annotationRect) { WidgetInfos infos= new WidgetInfos(fTextViewer.getTextWidget(), fCanvas); - if (y_coordinate >= infos.writable || y_coordinate >= infos.bounds.height || y_coordinate < 0) + if (y_coordinate >= infos.writable || y_coordinate >= infos.bounds.height || y_coordinate < 0) { return new int[] {-1, -1}; + } - if (annotationRect && ANNOTATION_HEIGHT >= infos.bounds.height / infos.maxLines) + if (annotationRect && ANNOTATION_HEIGHT >= infos.bounds.height / infos.maxLines) { annotationRect= false; + } int[] lines= new int[2]; int[] pixels; @@ -960,37 +993,46 @@ private int[] toLineNumbers(int y_coordinate, boolean annotationRect) { if (infos.bounds.height > infos.writable || infos.invisibleLines <= 0) { // too few lines for relative positions: align annotations with textWidget lines // yy = Math.max(0, (2 * startLine + 1) * infos.writable / (infos.maxLines * 2) - infos.bounds.y); - for (int i= 0; i < pixels.length; i++) + for (int i= 0; i < pixels.length; i++) { lines[i]= (int) ((pixels[i] + infos.bounds.y) * infos.maxLines / (double)infos.writable); - if (DEBUG_TO_DOCUMENT_LINE_NUMBER) + } + if (DEBUG_TO_DOCUMENT_LINE_NUMBER) { System.out.println("static y: " + y_coordinate + " => [" + lines[0] + ", " + lines[1] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } } else if (y_coordinate < infos.thumbHeight / 2) { // before middle of first page: map to area from 0 to thumbHeight/2 // yy= (int) (startLine * infos.thumbHeight / infos.visibleLines); - for (int i= 0; i < pixels.length; i++) + for (int i= 0; i < pixels.length; i++) { lines[i] = (int) (pixels[i] * infos.visibleLines / infos.thumbHeight); - if (DEBUG_TO_DOCUMENT_LINE_NUMBER) + } + if (DEBUG_TO_DOCUMENT_LINE_NUMBER) { System.out.println("start y: " + y_coordinate + " => [" + lines[0] + ", " + lines[1] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } } else if (infos.bounds.height - 1 - infos.thumbHeight / 2 < y_coordinate) { // after middle of last page: map to area from canvasHeight-1 - thumbHeight/2 to canvasHeight-1 // yy= (int) (infos.bounds.height-1 - (double)infos.thumbHeight / 2 + (startLine - (infos.maxLines - infos.visibleLines / 2) + 1) * infos.thumbHeight / infos.visibleLines); - for (int i= 0; i < pixels.length; i++) + for (int i= 0; i < pixels.length; i++) { lines[i] = (int) ((pixels[i] - (infos.bounds.height-1) + (double)infos.thumbHeight / 2) * infos.visibleLines / infos.thumbHeight - 1 + (infos.maxLines - infos.visibleLines / 2)); - if (DEBUG_TO_DOCUMENT_LINE_NUMBER) + } + if (DEBUG_TO_DOCUMENT_LINE_NUMBER) { System.out.println("end y: " + y_coordinate + " => [" + lines[0] + ", " + lines[1] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } } else { // middle of text: map to area from thumbHeight/2 to (canvasHeight-1 - thumbHeight/2) // yy= (int) ((double)infos.thumbHeight/2 + (startLine + 1 - infos.visibleLines / 2) * (infos.bounds.height-1 - infos.thumbHeight) / infos.invisibleLines); - for (int i= 0; i < pixels.length; i++) + for (int i= 0; i < pixels.length; i++) { lines[i]= (int) ((pixels[i] - (double)infos.thumbHeight/2) * infos.invisibleLines / (infos.bounds.height-1 - infos.thumbHeight) - 1 + infos.visibleLines / 2); - if (DEBUG_TO_DOCUMENT_LINE_NUMBER) + } + if (DEBUG_TO_DOCUMENT_LINE_NUMBER) { System.out.println("middle y: " + y_coordinate + " => [" + lines[0] + ", " + lines[1] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } } - if (y_coordinate < ANNOTATION_HEIGHT && y_coordinate < infos.bounds.y) + if (y_coordinate < ANNOTATION_HEIGHT && y_coordinate < infos.bounds.y) { lines[0]= 0; - else if (lines[0] < 0) + } else if (lines[0] < 0) { lines[0]= 0; + } if (annotationRect) { int y0= computeY(lines[0], infos); @@ -1003,8 +1045,9 @@ else if (lines[0] < 0) } } - if (lines[1] > infos.maxLines) + if (lines[1] > infos.maxLines) { lines[1]= infos.maxLines; + } if (fTextViewer instanceof ITextViewerExtension5 extension) { lines[0]= extension.widgetLine2ModelLine(lines[0]); @@ -1019,8 +1062,9 @@ else if (lines[0] < 0) } } - if (DEBUG_TO_DOCUMENT_LINE_NUMBER) + if (DEBUG_TO_DOCUMENT_LINE_NUMBER) { System.out.println("result: [" + lines[0] + ", " + lines[1] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return lines; } @@ -1031,8 +1075,9 @@ else if (lines[0] < 0) * @return the position of the first found annotation */ private Position getAnnotationPosition(int[] lineNumbers) { - if (lineNumbers[0] == -1) + if (lineNumbers[0] == -1) { return null; + } Position found= null; @@ -1052,15 +1097,18 @@ private Position getAnnotationPosition(int[] lineNumbers) { Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY); while (e.hasNext() && found == null) { Annotation a= e.next(); - if (a.isMarkedDeleted()) + if (a.isMarkedDeleted()) { continue; + } - if (skip(a.getType())) + if (skip(a.getType())) { continue; + } Position p= fModel.getPosition(a); - if (p == null) + if (p == null) { continue; + } int posOffset= p.getOffset(); int posEnd= posOffset + p.getLength(); @@ -1071,8 +1119,9 @@ private Position getAnnotationPosition(int[] lineNumbers) { region= d.getLineInformationOfOffset(posEnd); } - if (posOffset <= end && posEnd >= start) - found= p; + if (posOffset <= end && posEnd >= start) { + found= p; + } } } } catch (BadLocationException x) { @@ -1089,13 +1138,15 @@ private Position getAnnotationPosition(int[] lineNumbers) { * @return the best matching line or -1 if no such line can be found */ private int findBestMatchingLineNumber(int[] lineNumbers) { - if (lineNumbers == null || lineNumbers.length < 1) + if (lineNumbers == null || lineNumbers.length < 1) { return -1; + } try { Position pos= getAnnotationPosition(lineNumbers); - if (pos == null) + if (pos == null) { return -1; + } return fTextViewer.getDocument().getLineOfOffset(pos.getOffset()); } catch (BadLocationException ex) { return -1; @@ -1110,8 +1161,9 @@ private int findBestMatchingLineNumber(int[] lineNumbers) { private void handleMouseDown(MouseEvent event) { if (fTextViewer != null) { int[] lines= toLineNumbers(event.y, true); - if (lines[0] == -1) + if (lines[0] == -1) { lines= toLineNumbers(event.y, false); + } Position p= getAnnotationPosition(lines); if (p == null && event.button == 1) { try { @@ -1191,8 +1243,9 @@ public void setAnnotationTypeLayer(Object annotationType, int layer) { if (layer >= 0) { int i= 0; int size= fLayersSortedByLayer.size(); - while (i < size && layer >= fLayersSortedByLayer.get(i).intValue()) + while (i < size && layer >= fLayersSortedByLayer.get(i).intValue()) { i++; + } Integer layerObj= Integer.valueOf(layer); fLayersSortedByLayer.add(i, layerObj); fAnnotationsSortedByLayer.add(i, annotationType); @@ -1201,10 +1254,11 @@ public void setAnnotationTypeLayer(Object annotationType, int layer) { @Override public void setAnnotationTypeColor(Object annotationType, Color color) { - if (color != null) + if (color != null) { fAnnotationTypes2Colors.put(annotationType, color); - else + } else { fAnnotationTypes2Colors.remove(annotationType); + } } /** @@ -1244,8 +1298,9 @@ private boolean contains(Object annotationType, Map allowed, Se boolean covered; synchronized (fRunnableLock){ Boolean cached= allowed.get(annotationType); - if (cached != null) + if (cached != null) { return cached.booleanValue(); + } covered = isCovered(annotationType, configured); allowed.put(annotationType, covered ? Boolean.TRUE : Boolean.FALSE); @@ -1268,8 +1323,9 @@ private boolean isCovered(Object annotationType, Set configured) { if (fAnnotationAccess instanceof IAnnotationAccessExtension extension) { Iterator e= configured.iterator(); while (e.hasNext()) { - if (extension.isSubtype(annotationType,e.next())) + if (extension.isSubtype(annotationType,e.next())) { return true; + } } return false; } @@ -1300,8 +1356,9 @@ private static RGB interpolate(RGB fg, RGB bg, double scale) { * @return the grey-scale value */ private static double greyLevel(RGB rgb) { - if (rgb.red == rgb.green && rgb.green == rgb.blue) + if (rgb.red == rgb.green && rgb.green == rgb.blue) { return rgb.red; + } return (0.299 * rgb.red + 0.587 * rgb.green + 0.114 * rgb.blue + 0.5); } @@ -1324,18 +1381,20 @@ private static boolean isDark(RGB rgb) { */ private Color getColor(Object annotationType, double scale) { Color base= findColor(annotationType); - if (base == null) + if (base == null) { return null; + } RGB baseRGB= base.getRGB(); RGB background= fCanvas.getBackground().getRGB(); boolean darkBase= isDark(baseRGB); boolean darkBackground= isDark(background); - if (darkBase && darkBackground) + if (darkBase && darkBackground) { background= new RGB(255, 255, 255); - else if (!darkBase && !darkBackground) + } else if (!darkBase && !darkBackground) { background= new RGB(0, 0, 0); + } return fSharedTextColors.getColor(interpolate(baseRGB, background, scale)); } @@ -1349,16 +1408,18 @@ else if (!darkBase && !darkBackground) */ private Color findColor(Object annotationType) { Color color= fAnnotationTypes2Colors.get(annotationType); - if (color != null) + if (color != null) { return color; + } if (fAnnotationAccess instanceof IAnnotationAccessExtension extension) { Object[] superTypes= extension.getSupertypes(annotationType); if (superTypes != null) { for (Object superType : superTypes) { color= fAnnotationTypes2Colors.get(superType); - if (color != null) + if (color != null) { return color; + } } } } @@ -1390,23 +1451,27 @@ private Color getFillColor(Object annotationType, boolean temporary) { @Override public int getLineOfLastMouseButtonActivity() { - if (fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) + if (fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) { fLastMouseButtonActivityLine= -1; + } return fLastMouseButtonActivityLine; } @Override public int toDocumentLineNumber(int y_coordinate) { - if (fTextViewer == null || y_coordinate == -1) + if (fTextViewer == null || y_coordinate == -1) { return -1; + } int[] lineNumbers= toLineNumbers(y_coordinate, true); - if (lineNumbers[0] == -1) + if (lineNumbers[0] == -1) { lineNumbers= toLineNumbers(y_coordinate, false); + } int bestLine= findBestMatchingLineNumber(lineNumbers); - if (bestLine == -1 && lineNumbers.length > 0) + if (bestLine == -1 && lineNumbers.length > 0) { return lineNumbers[0]; + } return bestLine; } @@ -1450,16 +1515,18 @@ public void removeHeaderAnnotationType(Object annotationType) { * Updates the header of this ruler. */ private void updateHeader() { - if (fHeader == null || fHeader.isDisposed()) + if (fHeader == null || fHeader.isDisposed()) { return; + } fHeader.setToolTipText(null); Object colorType= null; outer: for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) { Object annotationType= fAnnotationsSortedByLayer.get(i); - if (skipInHeader(annotationType) || skip(annotationType)) + if (skipInHeader(annotationType) || skip(annotationType)) { continue; + } Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); while (e.hasNext()) { @@ -1471,12 +1538,14 @@ private void updateHeader() { } Color color= null; - if (colorType != null) + if (colorType != null) { color= findColor(colorType); + } if (color == null) { - if (fHeaderPainter != null) + if (fHeaderPainter != null) { fHeaderPainter.setColor(null); + } } else { if (fHeaderPainter == null) { fHeaderPainter= new HeaderPainter(); @@ -1493,11 +1562,13 @@ private void updateHeader() { * Updates the header tool tip text of this ruler. */ private void updateHeaderToolTipText() { - if (fHeader == null || fHeader.isDisposed()) + if (fHeader == null || fHeader.isDisposed()) { return; + } - if (fHeader.getToolTipText() != null) + if (fHeader.getToolTipText() != null) { return; + } StringBuilder overview = new StringBuilder(); @@ -1505,8 +1576,9 @@ private void updateHeaderToolTipText() { Object annotationType= fAnnotationsSortedByLayer.get(i); - if (skipInHeader(annotationType) || skip(annotationType)) + if (skipInHeader(annotationType) || skip(annotationType)) { continue; + } int count= 0; String annotationTypeLabel= null; @@ -1515,8 +1587,9 @@ private void updateHeaderToolTipText() { while (e.hasNext()) { Annotation annotation= e.next(); if (annotation != null) { - if (annotationTypeLabel == null) + if (annotationTypeLabel == null) { annotationTypeLabel= ((IAnnotationAccessExtension)fAnnotationAccess).getTypeLabel(annotation); + } count++; } } @@ -1529,8 +1602,9 @@ private void updateHeaderToolTipText() { } } - if (overview.length() > 0) + if (overview.length() > 0) { fHeader.setToolTipText(overview.toString()); + } } /** diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRulerHoverManager.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRulerHoverManager.java index e00871f0185..86feb55f7e7 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRulerHoverManager.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRulerHoverManager.java @@ -44,8 +44,9 @@ public OverviewRulerHoverManager(IOverviewRuler ruler, ISourceViewer sourceViewe StyledText textWidget= sourceViewer.getTextWidget(); if (textWidget != null) { ScrollBar verticalBar= textWidget.getVerticalBar(); - if (verticalBar != null) + if (verticalBar != null) { setMargins(verticalBar.getSize().x, 5); + } } } @@ -56,8 +57,9 @@ protected void computeInformation() { IAnnotationHover hover= getAnnotationHover(); IInformationControlCreator controlCreator= null; - if (hover instanceof IAnnotationHoverExtension) + if (hover instanceof IAnnotationHoverExtension) { controlCreator= ((IAnnotationHoverExtension)hover).getHoverControlCreator(); + } setCustomInformationControlCreator(controlCreator); setInformation(hover.getHoverInfo(getSourceViewer(), line), computeArea(location.y)); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java index 6832b9cce5d..c8965f3f66f 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java @@ -124,8 +124,9 @@ public RulerLayout(int gap) { protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { Control[] children= composite.getChildren(); Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache); - if (fVerticalRuler != null && fIsVerticalRulerVisible) + if (fVerticalRuler != null && fIsVerticalRulerVisible) { s.x += fVerticalRuler.getWidth() + fGap; + } return s; } @@ -136,8 +137,9 @@ protected void layout(Composite composite, boolean flushCache) { Rectangle trim= textWidget.computeTrim(0, 0, 0, 0); int topTrim= - trim.y; int scrollbarHeight= trim.height - topTrim; // horizontal scroll bar is only under the client area - if ((textWidget.getScrollbarsMode() & SWT.SCROLLBAR_OVERLAY) != 0) + if ((textWidget.getScrollbarsMode() & SWT.SCROLLBAR_OVERLAY) != 0) { scrollbarHeight= 0; + } int x= clArea.x; int width= clArea.width; @@ -155,11 +157,13 @@ protected void layout(Composite composite, boolean flushCache) { final Control verticalRulerControl= fVerticalRuler.getControl(); int oldWidth= verticalRulerControl.getBounds().width; int rulerHeight= clArea.height - topTrim; - if (hScrollVisible) + if (hScrollVisible) { rulerHeight-= scrollbarHeight; + } verticalRulerControl.setBounds(clArea.x, clArea.y + topTrim, verticalRulerWidth, rulerHeight); - if (flushCache && getVisualAnnotationModel() != null && oldWidth == verticalRulerWidth) + if (flushCache && getVisualAnnotationModel() != null && oldWidth == verticalRulerWidth) { verticalRulerControl.redraw(); + } x += verticalRulerWidth + fGap; width -= verticalRulerWidth + fGap; @@ -168,8 +172,9 @@ protected void layout(Composite composite, boolean flushCache) { textWidget.setBounds(x, clArea.y, width, clArea.height); if (overviewRulerWidth != -1) { - if (scrollbarHeight <= 0) + if (scrollbarHeight <= 0) { scrollbarHeight= overviewRulerWidth; + } int bottomOffset= clArea.y + clArea.height - scrollbarHeight; int[] arrowHeights= getVerticalScrollArrowHeights(textWidget, bottomOffset); @@ -209,8 +214,9 @@ protected void layout(Composite composite, boolean flushCache) { */ private int[] getVerticalScrollArrowHeights(StyledText textWidget, int bottomOffset) { ScrollBar verticalBar= textWidget.getVerticalBar(); - if (verticalBar == null || !verticalBar.getVisible()) + if (verticalBar == null || !verticalBar.getVisible()) { return new int[] { 0, 0 }; + } int[] arrowHeights= computeScrollArrowHeights(textWidget, bottomOffset); if (arrowHeights[0] > 0 || arrowHeights[1] > 0) { @@ -445,10 +451,12 @@ protected void createControl(Composite parent, int styles) { super.createControl(parent, styles); - if (fVerticalRuler != null) + if (fVerticalRuler != null) { fVerticalRuler.createControl(fComposite, this); - if (fOverviewRuler != null) + } + if (fOverviewRuler != null) { fOverviewRuler.createControl(fComposite, this); + } } /** @@ -464,8 +472,9 @@ protected Layout createLayout() { @Override public Control getControl() { - if (fComposite != null) + if (fComposite != null) { return fComposite; + } return super.getControl(); } @@ -490,25 +499,29 @@ public void setOverviewRulerAnnotationHover(IAnnotationHover annotationHover) { @Override public void configure(SourceViewerConfiguration configuration) { - if (getTextWidget() == null) + if (getTextWidget() == null) { return; + } setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this)); // install content type independent plug-ins fPresentationReconciler= configuration.getPresentationReconciler(this); - if (fPresentationReconciler != null) + if (fPresentationReconciler != null) { fPresentationReconciler.install(this); + } fReconciler= configuration.getReconciler(this); - if (fReconciler != null) + if (fReconciler != null) { fReconciler.install(this); + } fContentAssistant= configuration.getContentAssistant(this); if (fContentAssistant != null) { fContentAssistant.install(this); - if (fContentAssistant instanceof IContentAssistantExtension2 && fContentAssistant instanceof IContentAssistantExtension4) + if (fContentAssistant instanceof IContentAssistantExtension2 && fContentAssistant instanceof IContentAssistantExtension4) { fContentAssistantFacade= new ContentAssistantFacade(fContentAssistant); + } fContentAssistantInstalled= true; } @@ -521,8 +534,9 @@ public void configure(SourceViewerConfiguration configuration) { fContentFormatter= configuration.getContentFormatter(this); fInformationPresenter= configuration.getInformationPresenter(this); - if (fInformationPresenter != null) + if (fInformationPresenter != null) { fInformationPresenter.install(this); + } setUndoManager(configuration.getUndoManager(this)); @@ -557,12 +571,14 @@ public void configure(SourceViewerConfiguration configuration) { } String[] prefixes= configuration.getIndentPrefixes(this, t); - if (prefixes != null && prefixes.length > 0) + if (prefixes != null && prefixes.length > 0) { setIndentPrefixes(prefixes, t); + } prefixes= configuration.getDefaultPrefixes(this, t); - if (prefixes != null && prefixes.length > 0) + if (prefixes != null && prefixes.length > 0) { setDefaultPrefixes(prefixes, t); + } } setCodeMiningProviders(configuration.getCodeMiningProviders(this)); installTextViewer(); @@ -605,10 +621,12 @@ protected void ensureOverviewHoverManagerInstalled() { @Override public void setHoverEnrichMode(EnrichMode mode) { super.setHoverEnrichMode(mode); - if (fVerticalRulerHoveringController != null) + if (fVerticalRulerHoveringController != null) { fVerticalRulerHoveringController.getInternalAccessor().setHoverEnrichMode(mode); - if (fOverviewRulerHoveringController != null) + } + if (fOverviewRulerHoveringController != null) { fOverviewRulerHoveringController.getInternalAccessor().setHoverEnrichMode(mode); + } } @Override @@ -653,11 +671,13 @@ protected IAnnotationModel createVisualAnnotationModel(IAnnotationModel annotati */ protected void disposeVisualAnnotationModel() { if (fVisualAnnotationModel != null) { - if (getDocument() != null) + if (getDocument() != null) { fVisualAnnotationModel.disconnect(getDocument()); + } - if ( fVisualAnnotationModel instanceof IAnnotationModelExtension) + if ( fVisualAnnotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension)fVisualAnnotationModel).removeAnnotationModel(MODEL_ANNOTATION_MODEL); + } fVisualAnnotationModel= null; } @@ -678,16 +698,19 @@ public void setDocument(IDocument document, IAnnotationModel annotationModel, in fVisualAnnotationModel.connect(document); } - if (modelRangeOffset == -1 && modelRangeLength == -1) + if (modelRangeOffset == -1 && modelRangeLength == -1) { super.setDocument(document); - else + } else { super.setDocument(document, modelRangeOffset, modelRangeLength); + } - if (fVerticalRuler != null) + if (fVerticalRuler != null) { fVerticalRuler.setModel(fVisualAnnotationModel); + } - if (fOverviewRuler != null) + if (fOverviewRuler != null) { fOverviewRuler.setModel(fVisualAnnotationModel); + } } @Override @@ -743,8 +766,9 @@ public void unconfigure() { fContentAssistant.uninstall(); fContentAssistantInstalled= false; fContentAssistant= null; - if (fContentAssistantFacade != null) + if (fContentAssistantFacade != null) { fContentAssistantFacade= null; + } } if (fQuickAssistAssistant != null) { @@ -813,20 +837,25 @@ protected void handleDispose() { @Override public boolean canDoOperation(int operation) { - if (getTextWidget() == null || (!redraws() && operation != FORMAT)) + if (getTextWidget() == null || (!redraws() && operation != FORMAT)) { return false; + } - if (operation == CONTENTASSIST_PROPOSALS) + if (operation == CONTENTASSIST_PROPOSALS) { return fContentAssistant != null && fContentAssistantInstalled && isEditable(); + } - if (operation == CONTENTASSIST_CONTEXT_INFORMATION) + if (operation == CONTENTASSIST_CONTEXT_INFORMATION) { return fContentAssistant != null && fContentAssistantInstalled && isEditable(); + } - if (operation == QUICK_ASSIST) + if (operation == QUICK_ASSIST) { return fQuickAssistAssistant != null && fQuickAssistAssistantInstalled && isEditable(); + } - if (operation == INFORMATION) + if (operation == INFORMATION) { return fInformationPresenter != null; + } if (operation == FORMAT) { return fContentFormatter != null && isEditable(); @@ -918,10 +947,11 @@ protected Point rememberSelection() { try { final Position position; - if (selection instanceof IBlockTextSelection) + if (selection instanceof IBlockTextSelection) { position= new ColumnPosition(selection.getOffset(), selection.getLength(), ((IBlockTextSelection) selection).getStartColumn(), ((IBlockTextSelection) selection).getEndColumn()); - else + } else { position= new Position(selection.getOffset(), selection.getLength()); + } document.addPosition(fSelectionCategory, position); fSelections.push(position); @@ -959,8 +989,9 @@ protected void restoreSelection() { } } - if (fSelections.isEmpty()) + if (fSelections.isEmpty()) { clearRememberedSelection(); + } } catch (BadPositionCategoryException exception) { // Should not happen } catch (BadLocationException x) { @@ -970,8 +1001,9 @@ protected void restoreSelection() { } protected void clearRememberedSelection() { - if (!fSelections.isEmpty()) + if (!fSelections.isEmpty()) { fSelections.clear(); + } IDocument document= getDocument(); if (document != null && fSelectionUpdater != null) { @@ -989,8 +1021,9 @@ protected void clearRememberedSelection() { @Override public void doOperation(int operation) { - if (getTextWidget() == null || (!redraws() && operation != FORMAT)) + if (getTextWidget() == null || (!redraws() && operation != FORMAT)) { return; + } switch (operation) { case CONTENTASSIST_PROPOSALS: @@ -1071,8 +1104,9 @@ public void doOperation(int operation) { } restoreSelection(); - if (context != null) + if (context != null) { context.dispose(); + } } return; } @@ -1098,8 +1132,9 @@ protected void updateSlaveDocuments(IDocument masterDocument) { Position p= child.getParentDocumentRange(); try { - if (!updateSlaveDocument(child, p.getOffset(), p.getLength())) + if (!updateSlaveDocument(child, p.getOffset(), p.getLength())) { child.repairLineInformation(); + } } catch (BadLocationException e) { // ignore @@ -1117,8 +1152,9 @@ public void enableOperation(int operation, boolean enable) { case CONTENTASSIST_PROPOSALS: case CONTENTASSIST_CONTEXT_INFORMATION: { - if (fContentAssistant == null) + if (fContentAssistant == null) { return; + } if (enable) { if (!fContentAssistantInstalled) { @@ -1133,8 +1169,9 @@ public void enableOperation(int operation, boolean enable) { } case QUICK_ASSIST: { - if (fQuickAssistAssistant == null) + if (fQuickAssistAssistant == null) { return; + } if (enable) { if (!fQuickAssistAssistantInstalled) { @@ -1171,8 +1208,9 @@ public void setRangeIndication(int start, int length, boolean moveCursor) { public IRegion getRangeIndication() { if (fRangeIndicator != null && fVisualAnnotationModel != null) { Position position= fVisualAnnotationModel.getPosition(fRangeIndicator); - if (position != null) + if (position != null) { return new Region(position.getOffset(), position.getLength()); + } } return null; @@ -1180,8 +1218,9 @@ public IRegion getRangeIndication() { @Override public void removeRangeIndication() { - if (fRangeIndicator != null && fVisualAnnotationModel != null) + if (fRangeIndicator != null && fVisualAnnotationModel != null) { fVisualAnnotationModel.removeAnnotation(fRangeIndicator); + } } @Override @@ -1189,12 +1228,13 @@ public void showAnnotations(boolean show) { boolean old= fIsVerticalRulerVisible; fIsVerticalRulerVisible= (fVerticalRuler != null && (show || !isVerticalRulerOnlyShowingAnnotations())); - if (old != fIsVerticalRulerVisible && fComposite != null && !fComposite.isDisposed()) + if (old != fIsVerticalRulerVisible && fComposite != null && !fComposite.isDisposed()) { fComposite.layout(); + } - if (fIsVerticalRulerVisible && show) + if (fIsVerticalRulerVisible && show) { ensureAnnotationHoverManagerInstalled(); - else if (fVerticalRulerHoveringController != null) { + } else if (fVerticalRulerHoveringController != null) { fVerticalRulerHoveringController.dispose(); fVerticalRulerHoveringController= null; } @@ -1207,8 +1247,9 @@ else if (fVerticalRulerHoveringController != null) { * @since 3.3 */ private boolean isVerticalRulerOnlyShowingAnnotations() { - if (fVerticalRuler instanceof VerticalRuler) + if (fVerticalRuler instanceof VerticalRuler) { return true; + } if (fVerticalRuler instanceof CompositeRuler) { Iterator iter= ((CompositeRuler)fVerticalRuler).getDecoratorIterator(); @@ -1258,8 +1299,9 @@ public void showAnnotationsOverview(boolean show) { boolean old= fIsOverviewRulerVisible; fIsOverviewRulerVisible= (show && fOverviewRuler != null); if (old != fIsOverviewRulerVisible) { - if (fComposite != null && !fComposite.isDisposed()) + if (fComposite != null && !fComposite.isDisposed()) { fComposite.layout(); + } if (fIsOverviewRulerVisible) { ensureOverviewHoverManagerInstalled(); } else if (fOverviewRulerHoveringController != null) { @@ -1271,8 +1313,9 @@ public void showAnnotationsOverview(boolean show) { @Override public IAnnotationHover getCurrentAnnotationHover() { - if (fVerticalRulerHoveringController == null) + if (fVerticalRulerHoveringController == null) { return null; + } return fVerticalRulerHoveringController.getCurrentAnnotationHover(); } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewerConfiguration.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewerConfiguration.java index 2b6f97d46e2..a951b5e21ce 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewerConfiguration.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewerConfiguration.java @@ -86,7 +86,7 @@ public int getTabWidth(ISourceViewer sourceViewer) { /** * Returns the line space for the given source viewer. This implementation always returns 0. - * + * * @param sourceViewer the source viewer to be configured by this configuration * @return the line space * @see org.eclipse.swt.custom.StyledText#setLineSpacing(int) @@ -252,10 +252,11 @@ protected String[] getIndentPrefixesForTab(int tabWidth) { char[] spaceChars= new char[i]; Arrays.fill(spaceChars, ' '); String spaces= new String(spaceChars); - if (i < tabWidth) + if (i < tabWidth) { indentPrefixes[i]= spaces + '\t'; - else + } else { indentPrefixes[i]= new String(spaces); + } } indentPrefixes[tabWidth + 1]= ""; //$NON-NLS-1$ return indentPrefixes; @@ -314,8 +315,9 @@ public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String * @since 2.1 */ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { - if (stateMask == ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK) + if (stateMask == ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK) { return getTextHover(sourceViewer, contentType); + } return null; } @@ -397,8 +399,9 @@ public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { * @since 3.1 */ public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) { - if (sourceViewer == null) + if (sourceViewer == null) { return null; + } return new IHyperlinkDetector[] { new URLHyperlinkDetector() }; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/TextInvocationContext.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/TextInvocationContext.java index e07a8038ec0..8a58e3b1375 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/TextInvocationContext.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/TextInvocationContext.java @@ -26,9 +26,9 @@ */ public class TextInvocationContext implements IQuickAssistInvocationContext { - private ISourceViewer fSourceViewer; - private int fOffset; - private int fLength; + private final ISourceViewer fSourceViewer; + private final int fOffset; + private final int fLength; public TextInvocationContext(ISourceViewer sourceViewer, int offset, int length) { fSourceViewer= sourceViewer; diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java index 6d3976a02b7..cc681382d3e 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java @@ -64,8 +64,9 @@ class InternalListener implements IViewportListener, IAnnotationModelListener, I @Override public void viewportChanged(int verticalPosition) { - if (verticalPosition != fScrollPos) + if (verticalPosition != fScrollPos) { redraw(); + } } @Override @@ -75,8 +76,9 @@ public void modelChanged(IAnnotationModel model) { @Override public void textChanged(TextEvent e) { - if (fTextViewer != null && e.getViewerRedrawState()) + if (fTextViewer != null && e.getViewerRedrawState()) { redraw(); + } } } @@ -106,14 +108,14 @@ public void textChanged(TextEvent e) { /** The line of the last mouse button activity */ private int fLastMouseButtonActivityLine= -1; /** The internal listener */ - private InternalListener fInternalListener= new InternalListener(); + private final InternalListener fInternalListener= new InternalListener(); /** The width of this vertical ruler */ - private int fWidth; + private final int fWidth; /** * The annotation access of this vertical ruler * @since 3.0 */ - private IAnnotationAccess fAnnotationAccess; + private final IAnnotationAccess fAnnotationAccess; /** * Constructs a vertical ruler with the given width. @@ -150,8 +152,9 @@ public Control createControl(Composite parent, ITextViewer textViewer) { fCanvas= new Canvas(parent, SWT.NO_BACKGROUND); fCanvas.addPaintListener(event -> { - if (fTextViewer != null) + if (fTextViewer != null) { doubleBufferPaint(event.gc); + } }); fCanvas.addDisposeListener(e -> { @@ -201,8 +204,9 @@ private void handleDispose() { fTextViewer= null; } - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(fInternalListener); + } if (fBuffer != null) { fBuffer.dispose(); @@ -220,8 +224,9 @@ private void doubleBufferPaint(GC dest) { Point size= fCanvas.getSize(); - if (size.x <= 0 || size.y <= 0) + if (size.x <= 0 || size.y <= 0) { return; + } if (fBuffer != null) { Rectangle r= fBuffer.getBounds(); @@ -249,10 +254,11 @@ private void doPaint(GC gc, int width, int height) { gc.setBackground(fCanvas.getBackground()); gc.fillRectangle(0, 0, width, height); - if (fTextViewer instanceof ITextViewerExtension5) + if (fTextViewer instanceof ITextViewerExtension5) { doPaint1(gc); - else + } else { doPaint(gc); + } } /** @@ -286,12 +292,14 @@ private int getInclusiveTopIndexStartOffset() { */ protected void doPaint(GC gc) { - if (fModel == null || fTextViewer == null) + if (fModel == null || fTextViewer == null) { return; + } IAnnotationAccessExtension annotationAccessExtension= null; - if (fAnnotationAccess instanceof IAnnotationAccessExtension) + if (fAnnotationAccess instanceof IAnnotationAccessExtension) { annotationAccessExtension= (IAnnotationAccessExtension) fAnnotationAccess; + } StyledText styledText= fTextViewer.getTextWidget(); IDocument doc= fTextViewer.getDocument(); @@ -323,22 +331,25 @@ protected void doPaint(GC gc) { Annotation annotation= iter.next(); int lay= IAnnotationAccessExtension.DEFAULT_LAYER; - if (annotationAccessExtension != null) + if (annotationAccessExtension != null) { lay= annotationAccessExtension.getLayer(annotation); - else if (annotation instanceof IAnnotationPresentation) { + } else if (annotation instanceof IAnnotationPresentation) { annotationPresentation= (IAnnotationPresentation)annotation; lay= annotationPresentation.getLayer(); } maxLayer= Math.max(maxLayer, lay+1); // dynamically update layer maximum - if (lay != layer) // wrong layer: skip annotation + if (lay != layer) { // wrong layer: skip annotation continue; + } Position position= fModel.getPosition(annotation); - if (position == null) + if (position == null) { continue; + } - if (!position.overlapsWith(topLeft, viewPort)) + if (!position.overlapsWith(topLeft, viewPort)) { continue; + } try { @@ -346,14 +357,17 @@ else if (annotation instanceof IAnnotationPresentation) { int length= position.getLength(); int startLine= doc.getLineOfOffset(offset); - if (startLine < topLine) + if (startLine < topLine) { startLine= topLine; + } int endLine= startLine; - if (length > 0) + if (length > 0) { endLine= doc.getLineOfOffset(offset + length - 1); - if (endLine > bottomLine) + } + if (endLine > bottomLine) { endLine= bottomLine; + } startLine -= topLine; endLine -= topLine; @@ -366,10 +380,11 @@ else if (annotation instanceof IAnnotationPresentation) { r.height= JFaceTextUtil.computeLineHeight(styledText, startLine, endLine + 1, (lines+1)); - if (r.y < d.y && annotationAccessExtension != null) // annotation within visible area + if (r.y < d.y && annotationAccessExtension != null) { // annotation within visible area annotationAccessExtension.paint(annotation, gc, fCanvas, r); - else if (annotationPresentation != null) + } else if (annotationPresentation != null) { annotationPresentation.paint(gc, fCanvas, r); + } } catch (BadLocationException e) { } @@ -386,12 +401,14 @@ else if (annotationPresentation != null) */ protected void doPaint1(GC gc) { - if (fModel == null || fTextViewer == null) + if (fModel == null || fTextViewer == null) { return; + } IAnnotationAccessExtension annotationAccessExtension= null; - if (fAnnotationAccess instanceof IAnnotationAccessExtension) + if (fAnnotationAccess instanceof IAnnotationAccessExtension) { annotationAccessExtension= (IAnnotationAccessExtension) fAnnotationAccess; + } ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer; StyledText textWidget= fTextViewer.getTextWidget(); @@ -410,31 +427,36 @@ protected void doPaint1(GC gc) { Annotation annotation= iter.next(); int lay= IAnnotationAccessExtension.DEFAULT_LAYER; - if (annotationAccessExtension != null) + if (annotationAccessExtension != null) { lay= annotationAccessExtension.getLayer(annotation); - else if (annotation instanceof IAnnotationPresentation) { + } else if (annotation instanceof IAnnotationPresentation) { annotationPresentation= (IAnnotationPresentation)annotation; lay= annotationPresentation.getLayer(); } maxLayer= Math.max(maxLayer, lay+1); // dynamically update layer maximum - if (lay != layer) // wrong layer: skip annotation + if (lay != layer) { // wrong layer: skip annotation continue; + } Position position= fModel.getPosition(annotation); - if (position == null) + if (position == null) { continue; + } IRegion widgetRegion= extension.modelRange2WidgetRange(new Region(position.getOffset(), position.getLength())); - if (widgetRegion == null) + if (widgetRegion == null) { continue; + } int startLine= extension.widgetLineOfWidgetOffset(widgetRegion.getOffset()); - if (startLine == -1) + if (startLine == -1) { continue; + } int endLine= extension.widgetLineOfWidgetOffset(widgetRegion.getOffset() + Math.max(widgetRegion.getLength() -1, 0)); - if (endLine == -1) + if (endLine == -1) { continue; + } r.x= 0; r.y= JFaceTextUtil.computeLineHeight(textWidget, 0, startLine, startLine) - fScrollPos; @@ -444,10 +466,11 @@ else if (annotation instanceof IAnnotationPresentation) { r.height= JFaceTextUtil.computeLineHeight(textWidget, startLine, endLine + 1, lines+1); - if (r.y < dimension.y && annotationAccessExtension != null) // annotation within visible area + if (r.y < dimension.y && annotationAccessExtension != null) { // annotation within visible area annotationAccessExtension.paint(annotation, gc, fCanvas, r); - else if (annotationPresentation != null) + } else if (annotationPresentation != null) { annotationPresentation.paint(gc, fCanvas, r); + } } } } @@ -485,13 +508,15 @@ private void redraw() { public void setModel(IAnnotationModel model) { if (model != fModel) { - if (fModel != null) + if (fModel != null) { fModel.removeAnnotationModelListener(fInternalListener); + } fModel= model; - if (fModel != null) + if (fModel != null) { fModel.addAnnotationModelListener(fInternalListener); + } update(); } @@ -510,23 +535,26 @@ public int getWidth() { @Override public int getLineOfLastMouseButtonActivity() { IDocument doc= fTextViewer.getDocument(); - if (doc == null || fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) + if (doc == null || fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) { fLastMouseButtonActivityLine= -1; + } return fLastMouseButtonActivityLine; } @Override public int toDocumentLineNumber(int y_coordinate) { - if (fTextViewer == null || y_coordinate == -1) + if (fTextViewer == null || y_coordinate == -1) { return -1; + } StyledText text= fTextViewer.getTextWidget(); int line= text.getLineIndex(y_coordinate); if (line == text.getLineCount() - 1) { // check whether y_coordinate exceeds last line - if (y_coordinate > text.getLinePixel(line + 1)) + if (y_coordinate > text.getLinePixel(line + 1)) { return -1; + } } return widgetLine2ModelLine(fTextViewer, line); @@ -573,8 +601,9 @@ public void setLocationOfLastMouseButtonActivity(int x, int y) { */ @Deprecated public void addMouseListener(MouseListener listener) { - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.addMouseListener(listener); + } } /** @@ -586,7 +615,8 @@ public void addMouseListener(MouseListener listener) { */ @Deprecated public void removeMouseListener(MouseListener listener) { - if (fCanvas != null && !fCanvas.isDisposed()) + if (fCanvas != null && !fCanvas.isDisposed()) { fCanvas.removeMouseListener(listener); + } } } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java index 3d77a6df519..71abab71e9a 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/InlinedAnnotationSupport.java @@ -509,8 +509,9 @@ public T findExistingAnnotation(Position p private Object getLockObject(IAnnotationModel annotationModel) { if (annotationModel instanceof ISynchronizable) { Object lock= ((ISynchronizable) annotationModel).getLockObject(); - if (lock != null) + if (lock != null) { return lock; + } } return annotationModel; } @@ -521,16 +522,18 @@ private Object getLockObject(IAnnotationModel annotationModel) { private void removeInlinedAnnotations() { IAnnotationModel annotationModel= fViewer.getAnnotationModel(); - if (annotationModel == null || fInlinedAnnotations == null) + if (annotationModel == null || fInlinedAnnotations == null) { return; + } synchronized (getLockObject(annotationModel)) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension) annotationModel).replaceAnnotations( fInlinedAnnotations.toArray(new Annotation[fInlinedAnnotations.size()]), null); } else { - for (AbstractInlinedAnnotation annotation : fInlinedAnnotations) + for (AbstractInlinedAnnotation annotation : fInlinedAnnotations) { annotationModel.removeAnnotation(annotation); + } } fInlinedAnnotations= null; } @@ -590,16 +593,19 @@ Font getFont(int style) { Device device= styledText.getDisplay(); switch (style) { case SWT.BOLD: - if (boldFont != null) + if (boldFont != null) { return boldFont; + } return boldFont= new Font(device, getFontData(style)); case SWT.ITALIC: - if (italicFont != null) + if (italicFont != null) { return italicFont; + } return italicFont= new Font(device, getFontData(style)); case SWT.BOLD | SWT.ITALIC: - if (boldItalicFont != null) + if (boldItalicFont != null) { return boldItalicFont; + } return boldItalicFont= new Font(device, getFontData(style)); default: return regularFont; @@ -624,12 +630,15 @@ FontData[] getFontData(int style) { * Dispose the font. */ void disposeFont() { - if (boldFont != null) + if (boldFont != null) { boldFont.dispose(); - if (italicFont != null) + } + if (italicFont != null) { italicFont.dispose(); - if (boldItalicFont != null) + } + if (boldItalicFont != null) { boldItalicFont.dispose(); + } boldFont= italicFont= boldItalicFont= null; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/Positions.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/Positions.java index a9bd09f2ca5..4dceb75a2c5 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/Positions.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/source/inlined/Positions.java @@ -53,12 +53,13 @@ private static int getLeadingSpaces(String line) { int counter= 0; char[] chars= line.toCharArray(); for (char c : chars) { - if (c == '\t') + if (c == '\t') { counter++; - else if (c == ' ') + } else if (c == ' ') { counter++; - else + } else { break; + } } return counter; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/InclusivePositionUpdater.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/InclusivePositionUpdater.java index 2b415409896..d31740023d5 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/InclusivePositionUpdater.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/InclusivePositionUpdater.java @@ -53,18 +53,19 @@ public void update(DocumentEvent event) { Position position= positions[i]; - if (position.isDeleted()) + if (position.isDeleted()) { continue; + } int offset= position.getOffset(); int length= position.getLength(); int end= offset + length; - if (offset > eventOffset + eventOldLength) + if (offset > eventOffset + eventOldLength) { // position comes way // after change - shift position.setOffset(offset + deltaLength); - else if (end < eventOffset) { + } else if (end < eventOffset) { // position comes way before change - // leave alone } else if (offset <= eventOffset && end >= eventOffset + eventOldLength) { diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/PositionBasedCompletionProposal.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/PositionBasedCompletionProposal.java index 53561b51cf9..bf155485e81 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/PositionBasedCompletionProposal.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/PositionBasedCompletionProposal.java @@ -38,19 +38,19 @@ final class PositionBasedCompletionProposal implements ICompletionProposal, ICompletionProposalExtension2 { /** The string to be displayed in the completion proposal popup */ - private String fDisplayString; + private final String fDisplayString; /** The replacement string */ - private String fReplacementString; + private final String fReplacementString; /** The replacement position. */ - private Position fReplacementPosition; + private final Position fReplacementPosition; /** The cursor position after this proposal has been applied */ - private int fCursorPosition; + private final int fCursorPosition; /** The image to be displayed in the completion proposal popup */ - private Image fImage; + private final Image fImage; /** The context information of this proposal */ - private IContextInformation fContextInformation; + private final IContextInformation fContextInformation; /** The additional info of this proposal */ - private String fAdditionalProposalInfo; + private final String fAdditionalProposalInfo; /** * Creates a new completion proposal based on the provided information. The replacement string is @@ -114,8 +114,9 @@ public Image getImage() { @Override public String getDisplayString() { - if (fDisplayString != null) + if (fDisplayString != null) { return fDisplayString; + } return fReplacementString; } @@ -141,8 +142,9 @@ public void unselected(ITextViewer viewer) { public boolean validate(IDocument document, int offset, DocumentEvent event) { try { String content= document.get(fReplacementPosition.getOffset(), offset - fReplacementPosition.getOffset()); - if (fReplacementString.startsWith(content)) + if (fReplacementString.startsWith(content)) { return true; + } } catch (BadLocationException e) { // ignore concurrently modified document } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java index 6e989eb5ae0..57316607327 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java @@ -58,14 +58,16 @@ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int ITextSelection selection= (ITextSelection) viewer.getSelectionProvider().getSelection(); // adjust offset to end of normalized selection - if (selection.getOffset() == offset) + if (selection.getOffset() == offset) { offset= selection.getOffset() + selection.getLength(); + } String prefix= extractPrefix(viewer, offset); Region region= new Region(offset - prefix.length(), prefix.length()); TemplateContext context= createContext(viewer, region); - if (context == null) + if (context == null) { return new ICompletionProposal[0]; + } context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection //$NON-NLS-1$ @@ -78,8 +80,9 @@ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int } catch (TemplateException e) { continue; } - if (template.matches(prefix, context.getContextType().getId())) + if (template.matches(prefix, context.getContextType().getId())) { matches.add(createProposal(template, context, (IRegion) region, getRelevance(template, prefix))); + } } Collections.sort(matches, fgProposalComparator); @@ -174,8 +177,9 @@ protected TemplateContext createContext(ITextViewer viewer, IRegion region) { * @see #extractPrefix(ITextViewer, int) */ protected int getRelevance(Template template, String prefix) { - if (template.getName().startsWith(prefix)) + if (template.getName().startsWith(prefix)) { return 90; + } return 0; } @@ -192,14 +196,16 @@ protected int getRelevance(Template template, String prefix) { protected String extractPrefix(ITextViewer viewer, int offset) { int i= offset; IDocument document= viewer.getDocument(); - if (i > document.getLength()) + if (i > document.getLength()) { return ""; //$NON-NLS-1$ + } try { while (i > 0) { char ch= document.getChar(i - 1); - if (!Character.isJavaIdentifierPart(ch)) + if (!Character.isJavaIdentifierPart(ch)) { break; + } i--; } diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateProposal.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateProposal.java index 38052fc368e..37e368017d7 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateProposal.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateProposal.java @@ -56,7 +56,7 @@ public class TemplateProposal implements ICompletionProposal, ICompletionProposa private final TemplateContext fContext; private final Image fImage; private final IRegion fRegion; - private int fRelevance; + private final int fRelevance; private IRegion fSelectedRegion; // initialized by apply() private String fDisplayString; @@ -183,8 +183,9 @@ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { for (int i= 0; i != variables.length; i++) { TemplateVariable variable= variables[i]; - if (variable.isUnambiguous()) + if (variable.isUnambiguous()) { continue; + } LinkedPositionGroup group= new LinkedPositionGroup(); @@ -202,17 +203,20 @@ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { proposals[j]= new PositionBasedCompletionProposal(values[j], pos, length); } - if (proposals.length > 1) + if (proposals.length > 1) { first= new ProposalPosition(document, offsets[0] + start, length, proposals); - else + } else { first= new LinkedPosition(document, offsets[0] + start, length); + } } - for (int j= 0; j != offsets.length; j++) - if (j == 0) + for (int j= 0; j != offsets.length; j++) { + if (j == 0) { group.addPosition(first); - else + } else { group.addPosition(new LinkedPosition(document, offsets[j] + start, length)); + } + } model.addGroup(group); hasPositions= true; @@ -282,8 +286,9 @@ private int getCaretOffset(TemplateBuffer buffer) { TemplateVariable[] variables= buffer.getVariables(); for (int i= 0; i != variables.length; i++) { TemplateVariable variable= variables[i]; - if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) + if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) { return variable.getOffsets()[0]; + } } return buffer.getString().length(); diff --git a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java index d3ab1c0495c..5cc3df15647 100644 --- a/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java +++ b/bundles/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java @@ -39,7 +39,7 @@ */ public class TemplateStore extends TemplateStoreCore { /** The preference store. */ - private IPreferenceStore fPreferenceStore; + private final IPreferenceStore fPreferenceStore; /** * The property listener, if any is registered, null otherwise. @@ -116,12 +116,13 @@ public final void startListeningForPreferenceChanges() { * save operation, and clients may trigger reloading by listening to preference store * updates. */ - if (!fIgnorePreferenceStoreChanges && getKey().equals(event.getProperty())) + if (!fIgnorePreferenceStoreChanges && getKey().equals(event.getProperty())) { try { load(); } catch (IOException x) { handleException(x); } + } }; fPreferenceStore.addPropertyChangeListener(fPropertyListener); } @@ -151,8 +152,9 @@ public final void stopListeningForPreferenceChanges() { public void save() throws IOException { ArrayList custom= new ArrayList<>(); for (TemplatePersistenceData data : internalGetTemplates()) { - if (data.isCustom() && !(data.isUserAdded() && data.isDeleted())) // don't save deleted user-added templates + if (data.isCustom() && !(data.isUserAdded() && data.isDeleted())) { // don't save deleted user-added templates custom.add(data); + } } StringWriter output= new StringWriter(); @@ -162,8 +164,9 @@ public void save() throws IOException { fIgnorePreferenceStoreChanges= true; try { fPreferenceStore.setValue(getKey(), output.toString()); - if (fPreferenceStore instanceof IPersistentPreferenceStore) + if (fPreferenceStore instanceof IPersistentPreferenceStore) { ((IPersistentPreferenceStore)fPreferenceStore).save(); + } } finally { fIgnorePreferenceStoreChanges= false; } @@ -178,8 +181,9 @@ public void save() throws IOException { @Override public void restoreDefaults(boolean doSave) { String oldValue= null; - if (!doSave) + if (!doSave) { oldValue= fPreferenceStore.getString(getKey()); + } try { fIgnorePreferenceStoreChanges= true;