Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refact: minor code cleanup #749

Merged
merged 8 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,7 @@ private MatchInjectionsResult matchInjections(final List<Injection> injections,
final List<String> scopes = stack.contentNameScopesList != null ? stack.contentNameScopesList.getScopeNames()
: Collections.emptyList();

for (int i = 0, len = injections.size(); i < len; i++) {
final var injection = injections.get(i);
for (final Injection injection : injections) {
if (!injection.matches(scopes)) {
// injection selector doesn't match stack
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ public static ScopeStack from(final String first) {
@Nullable
public static ScopeStack from(final String... segments) {
ScopeStack result = null;
for (var i = 0; i < segments.length; i++) {
result = new ScopeStack(result, segments[i]);
for (final String segment : segments) {
result = new ScopeStack(result, segment);
}
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,7 @@ public static Theme resolveParsedThemeRules(final List<ParsedThemeRule> _parsedT
final var defaults = StyleAttributes.of(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));

final var root = new ThemeTrieElement(new ThemeTrieElementRule(0, null, FontStyle.NotSet, 0, 0), Collections.emptyList());
for (int i = 0, len = parsedThemeRules.size(); i < len; i++) {
final var rule = parsedThemeRules.get(i);
for (final ParsedThemeRule rule : parsedThemeRules) {
root.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ public final class LanguageConfigurationMessages extends NLS {
public static String LanguageConfigurationPreferencePage_description;
public static String LanguageConfigurationPreferencePage_description2;
public static String LanguageConfigurationPreferencePage_button_add;
public static String LanguageConfigurationPreferencePage_path;
public static String LanguageConfigurationPreferencePage_column_source;
public static String LanguageConfigurationPreferencePage_button_remove;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ public Object execute(@Nullable final ExecutionEvent event) throws ExecutionExce
}

final ContentTypeInfo info = ContentTypeHelper.findContentTypes(document);
if (info == null)
return null;
if (info == null)
return null;

final var contentTypes = info.getContentTypes();
final var command = event.getCommand();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ public final class FoldingRules {
* - the regex should start with '^'
* - regexp flags (i, g) are ignored
*/
public final class FoldingMarkers {
public static final class FoldingMarkers {
public final RegExPattern start;
public final RegExPattern end;

public FoldingMarkers(RegExPattern start, RegExPattern end) {
public FoldingMarkers(final RegExPattern start, final RegExPattern end) {
this.start = start;
this.end = end;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ boolean matchClose(final String afterEnterText) {
private final List<OnEnterRule> regExpRules;

public OnEnterSupport(final @Nullable List<CharacterPair> brackets, final @Nullable List<OnEnterRule> regExpRules) {
for (final var charPair : (brackets != null ? brackets : DEFAULT_BRACKETS)) {
for (final var charPair : brackets != null ? brackets : DEFAULT_BRACKETS) {
final var openRegExp = createOpenBracketRegExp(charPair.open);
final var closeRegExp = createCloseBracketRegExp(charPair.close);
if (openRegExp != null && closeRegExp != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public boolean test(final int value) {
/*
* replace common indentation of all lines
*/
final var sb = new StringBuilder(Math.max(0, multiLineString.length() - (indentDetector.lineCount * existingIndent)));
final var sb = new StringBuilder(Math.max(0, multiLineString.length() - indentDetector.lineCount * existingIndent));
final class IdentReplacer extends CharConsumer {
int skippedIndentOfLine = 0;
boolean isEmptyLine = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ public final class TMUIMessages extends NLS {
public static String SelectGrammarWizardPage_file_label;
public static String SelectGrammarWizardPage_file_error_required;
public static String SelectGrammarWizardPage_file_error_load;
public static String SelectGrammarWizardPage_file_error_invalid;

public static String CreateThemeAssociationWizardPage_title;
public static String CreateThemeAssociationWizardPage_description;
Expand All @@ -96,12 +95,7 @@ public final class TMUIMessages extends NLS {
public static String CreateThemeAssociationWizardPage_grammar_error_required;
public static String CreateThemeAssociationWizardPage_whenDark_text;

// TMPresentationReconciler register dialog confirmation
public static String TMPresentationReconciler_register_dialog_title;
public static String TMPresentationReconciler_register_dialog_message;

static {
NLS.initializeMessages(BUNDLE_NAME, TMUIMessages.class);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ SelectGrammarWizardPage_description=Specify the TextMate grammar file *.tmLangua
SelectGrammarWizardPage_file_label=File:
SelectGrammarWizardPage_file_error_required=TextMate grammar file is required.
SelectGrammarWizardPage_file_error_load=Error while loading the TextMate grammar file: "{0}".
SelectGrammarWizardPage_file_error_invalid=The file is not a TextMate grammar file. It cannot retrieve the scope name.

CreateThemeAssociationWizardPage_title=Specify the theme to use with a given grammar
CreateThemeAssociationWizardPage_description=Choose the theme to use for your grammar when an E4 Theme is activated.
Expand All @@ -80,7 +79,3 @@ CreateThemeAssociationWizardPage_grammar_text= with the grammar:
CreateThemeAssociationWizardPage_theme_error_required=Theme is required
CreateThemeAssociationWizardPage_grammar_error_required=Grammar is required
CreateThemeAssociationWizardPage_whenDark_text=when Eclipse Dark theme is activated?

# TMPresentationReconciler dialog
TMPresentationReconciler_register_dialog_title=Register the grammar?
TMPresentationReconciler_register_dialog_message=TextMate grammar cannot be found for the file "{0}". Do you want to register it?
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public final class GrammarPreferencePage extends AbstractPreferencePage {
// Managers
private IGrammarRegistryManager.EditSession grammarManager = TMEclipseRegistryPlugin.getGrammarRegistryManager().newEditSession();
private IThemeManager.EditSession themeManager = ThemeManager.getInstance().newEditSession();
private ISnippetManager snippetManager = TMUIPlugin.getSnippetManager();
private final ISnippetManager snippetManager = TMUIPlugin.getSnippetManager();

private TableWidget<IGrammarDefinition> grammarsTable = lazyNonNull();

Expand Down Expand Up @@ -123,7 +123,7 @@ protected void createColumns() {
final var contentTypes = grammarManager.getContentTypesForScope(def.getScope());
yield contentTypes == null
? null
: contentTypes.stream().map(ct -> ct.getName())
: contentTypes.stream().map(IContentType::getName)
.distinct()
.sorted()
.collect(Collectors.joining(", "));
Expand Down Expand Up @@ -323,28 +323,29 @@ private void fillContentTypeTab(final IGrammarDefinition definition) {
}

private void fillThemeTab(final IGrammarDefinition definition) {
final var selectedAssociation = themeAssociationsWidget.getTable().getFirstSelectedElement();
final TableWidget<IThemeAssociation> themeAssociationsTable = themeAssociationsWidget.getTable();
final IThemeAssociation selectedAssociation = themeAssociationsTable.getFirstSelectedElement();

themeAssociationsWidget.setGrammarDefinition(definition);

// restore theme selection
if (selectedAssociation != null) {
for (IThemeAssociation association : themeAssociationsWidget.getTable().getElements()) {
if (association.getThemeId().equals(selectedAssociation.getThemeId())) {
themeAssociationsWidget.getTable().setSelection(association);
break;
}
}
if (selectedAssociation == null) {
// ensure that by default a TM theme is selected that matches the Eclipse theme's dark/light mode
final boolean isDarkEclipse = themeManager.getDefaultTheme().isDark();
themeAssociationsTable.setSelection(association -> association.isWhenDark() == isDarkEclipse);
} else {
// restore theme selection
themeAssociationsTable.setSelection(association -> association.getThemeId().equals(selectedAssociation.getThemeId()));
}
}

private void createThemePreview(final Composite parent) {
final var label = new Label(parent, SWT.NONE);
label.setText(TMUIMessages.GrammarPreferencePage_preview);
var data = new GridData();
final var data = new GridData();
data.horizontalSpan = 2;
label.setLayoutData(data);

grammarPreview = new TMViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
grammarPreview = new TMViewer(parent, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);

// Don't set caret to 'null' as this causes https://bugs.eclipse.org/293263
// viewer.getTextWidget().setCaret(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ protected Control createContents(final @NonNullByDefault({}) Composite parent) {
final var control = new VerticalSplitPane(parent, 1, 1) {

@Override
protected void configureUpperArea(Composite parent) {
protected void configureUpperArea(final Composite parent) {
createThemesTable(parent);
createThemeDetailsView(parent);
}

@Override
protected void configureLowerArea(Composite parent) {
protected void configureLowerArea(final Composite parent) {
createThemePreview(parent);
}
}.getControl();
Expand Down Expand Up @@ -171,7 +171,7 @@ protected void createButtons() {
? themeFileName.substring(0, themeFileName.lastIndexOf('.'))
: rawTheme.getName());
return new Theme(name, themePath.toAbsolutePath().toString(), name, false);
} catch (Exception ex) {
} catch (final Exception ex) {
MessageDialog.openError(getShell(), "Invalid theme file", "Failed to parse [" + themePath + "]: " + ex);
return null;
}
Expand Down Expand Up @@ -252,7 +252,7 @@ private void createThemePreview(final Composite parent) {
grammarsCombo.getCombo().select(0);
}

themePreview = new TMViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
themePreview = new TMViewer(parent, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);

// Don't set caret to 'null' as this causes https://bugs.eclipse.org/293263
// viewer.getTextWidget().setCaret(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected IToken getJFaceTextToken(final IStyle style) {
return getJFaceTextTokenReturnValueCache.computeIfAbsent(style, this::getJFaceTextTokenUncached);
}

private IToken getJFaceTextTokenUncached(IStyle style) {
private IToken getJFaceTextTokenUncached(final IStyle style) {
final @Nullable RGB styleFGColor = style.getColor();
final @Nullable RGB styleBGColor = style.getBackgroundColor();
final var colors = ColorManager.getInstance();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public TMThemeTokenProvider(final IThemeSource.ContentType contentType, final In
}

protected @Nullable Color getEditorColor(final String... names) {
for (String name : names) {
for (final String name : names) {
final String colorHexCode = castNullable(theme.getEditorColors().get(name));
if (colorHexCode == null)
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,10 @@ private static InputStream getContents(final ITextFileBuffer buffer) throws Core
if (path != null) {
if (path.isAbsolute()) {
final var file = path.toFile();
if(file.exists()) {
if (file.exists()) {
try {
return new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException ex) {
} catch (final FileNotFoundException ex) {
TMUIPlugin.logError(ex);
}
}
Expand Down Expand Up @@ -226,8 +226,7 @@ private static IEditorInput getEditorInput(final IDocument document) {
if (listeners != null) {
// Get AbstractDocumentProvider#ElementInfo
final Object[] l = listeners.getListeners();
for (int i = 0; i < l.length; i++) {
final Object /* AbstractDocumentProvider#ElementInfo */ info = l[i];
for (final Object /* AbstractDocumentProvider#ElementInfo */ info : l) {
try {
/* The element for which the info is stored */
final Object input = ClassHelper.getFieldValue(info, "fElement");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ private static void updateTextMarkers(final ITMDocumentModel docModel, final int
final Object lineNumberAttr = marker.getAttribute(IMarker.LINE_NUMBER);
if (lineNumberAttr instanceof final Integer lineNumber)
return lineNumber;
} catch (CoreException ex) {
} catch (final CoreException ex) {
if (marker.exists())
TMUIPlugin.logError(ex);
}
Expand Down Expand Up @@ -220,7 +220,7 @@ private static boolean removeMatchingMarker(final List<IMarker> markers, final S
it.remove();
return true;
}
} catch (CoreException ex) {
} catch (final CoreException ex) {
if (marker.exists())
TMUIPlugin.logError(ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public void modifyText(final @Nullable ModifyEvent e) {

private static @Nullable FontMetrics fontMetrics;

public static int convertHeightInCharsToPixels(int chars) {
public static int convertHeightInCharsToPixels(final int chars) {
if (fontMetrics == null) {
final GC gc = new GC(getActiveShell());
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,45 +31,44 @@
*/
public final class TMViewer extends SourceViewer {

private final class TMSourceViewerConfiguration extends SourceViewerConfiguration {
@Override
public IPresentationReconciler getPresentationReconciler(final @Nullable ISourceViewer sourceViewer) {
return reconciler;
}
}

private final TMPresentationReconciler reconciler = new TMPresentationReconciler();

public TMViewer(final Composite parent, final IVerticalRuler ruler, final int styles) {
this(parent, ruler, null, false, styles);
public TMViewer(final Composite parent, final int styles) {
this(parent, null, null, false, styles);
}

public TMViewer(final Composite parent, @Nullable final IVerticalRuler verticalRuler,
@Nullable final IOverviewRuler overviewRuler,
public TMViewer(final Composite parent, final @Nullable IVerticalRuler verticalRuler, final @Nullable IOverviewRuler overviewRuler,
final boolean showAnnotationsOverview, final int styles) {
super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
configure(new TMSourceViewerConfiguration());
}

private final class TMSourceViewerConfiguration extends SourceViewerConfiguration {
@Override
public IPresentationReconciler getPresentationReconciler(@Nullable final ISourceViewer sourceViewer) {
return reconciler;
}
}

public void setGrammar(@Nullable final IGrammar grammar) {
public void setGrammar(final @Nullable IGrammar grammar) {
reconciler.setGrammar(grammar);
if (getDocument() == null) {
super.setDocument(new Document());
setDocument(new Document());
}
}

public void setTheme(final ITheme theme) {
reconciler.setTheme(theme);
final StyledText styledText = getTextWidget();
styledText.setFont(JFaceResources.getTextFont());
styledText.setForeground(null);
styledText.setBackground(null);
theme.initializeViewerColors(styledText);
getTextWidget().setFont(JFaceResources.getTextFont());
}

public void setText(final String text) {
if (getDocument() == null) {
super.setDocument(new Document());
setDocument(new Document());
}
getDocument().set(text);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;

import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jface.layout.TableColumnLayout;
Expand Down Expand Up @@ -133,7 +134,7 @@ protected Object[] getElements(final @Nullable Object input) {

@SuppressWarnings("unchecked")
@Override
public T getElementAt(int index) {
public T getElementAt(final int index) {
return (T) super.getElementAt(index);
}

Expand Down Expand Up @@ -205,7 +206,15 @@ public void setSelection(@SuppressWarnings("unchecked") final T... selection) {
setSelection(new StructuredSelection(selection));
}

public void setSelection(boolean reveal, @SuppressWarnings("unchecked") final T... selection) {
public void setSelection(final List<T> selection) {
setSelection(new StructuredSelection(selection));
}

public void setSelection(final Predicate<T> selector) {
setSelection(getElements().stream().filter(selector).toList());
}

public void setSelection(final boolean reveal, @SuppressWarnings("unchecked") final T... selection) {
setSelection(selection);
if (reveal) {
reveal(selection[0]);
Expand All @@ -216,7 +225,7 @@ public void setSelection(boolean reveal, @SuppressWarnings("unchecked") final T.
* @param col 0-based column index
* @param sortDirection {@link SWT#DOWN} or {@link SWT#UP}
*/
public void setSortColumn(final int col, int sortDirection) {
public void setSortColumn(final int col, final int sortDirection) {
viewerComparator.setColumns(col, secondarySortColumns.get(col));
viewerComparator.setDirection(sortDirection);
getTable().setSortDirection(viewerComparator.getDirection());
Expand Down
Loading
Loading