Updated to support Java 11, but only Java 8 features

This commit is contained in:
SuspiciousActivity committed 2018-09-26 17:19:03 +02:00
1 parent 58c8e90c81
commit 89f9753d8b
19 files changed
+1877 -2145

No files matched your search

@@ -32,31 +32,30 @@ import org.fife.ui.rsyntaxtextarea.templates.CodeTemplate;
* Manages "code templates."
* <p>
*
* All methods in this class are synchronized for thread safety, but as a
* best practice, you should probably only modify the templates known to a
* All methods in this class are synchronized for thread safety, but as a best
* practice, you should probably only modify the templates known to a
* <code>CodeTemplateManager</code> on the EDT. Modifying a
* <code>CodeTemplate</code> retrieved from a <code>CodeTemplateManager</code>
* while <em>not</em> on the EDT could cause problems.
* <p>
*
* For more flexible boilerplate code insertion, consider using the
* <a href=
* For more flexible boilerplate code insertion, consider using the <a href=
* "http://javadoc.fifesoft.com/autocomplete/org/fife/ui/autocomplete/TemplateCompletion.html">
* TemplateCompletion class</a> in the
* <a href="https://github.com/bobbylight/AutoComplete">AutoComplete
* add-on library</a>.
* <a href="https://github.com/bobbylight/AutoComplete">AutoComplete add-on
* library</a>.
*
* @author Robert Futrell
* @version 1.0
*/
public class CodeTemplateManager {
private int maxTemplateIDLength;
private List<CodeTemplate> templates;
private Segment s;
private TemplateComparator comparator;
private File directory;
/**
* Constructor.
*/
@@ -65,15 +64,13 @@ public class CodeTemplateManager {
comparator = new TemplateComparator();
templates = new ArrayList<CodeTemplate>();
}
/**
* Registers the specified template with this template manager.
*
* @param template
* The template to register.
* @throws IllegalArgumentException
* If <code>template</code> is
* <code>null</code>.
* @param template The template to register.
* @throws IllegalArgumentException If <code>template</code> is
* <code>null</code>.
* @see #removeTemplate(CodeTemplate)
* @see #removeTemplate(String)
*/
@@ -84,13 +81,12 @@ public class CodeTemplateManager {
templates.add(template);
sortTemplates();
}
/**
* Returns the template that should be inserted at the current caret
* position, assuming the trigger character was pressed.
* Returns the template that should be inserted at the current caret position,
* assuming the trigger character was pressed.
*
* @param textArea
* The text area that's getting text inserted into it.
* @param textArea The text area that's getting text inserted into it.
* @return A template that should be inserted, if appropriate, or
* <code>null</code> if no template should be inserted.
*/
@@ -100,7 +96,6 @@ public class CodeTemplateManager {
try {
Document doc = textArea.getDocument();
doc.getText(caretPos - charsToGet, charsToGet, s);
@SuppressWarnings("unchecked")
int index = Collections.binarySearch(templates, s, comparator);
return index >= 0 ? (CodeTemplate) templates.get(index) : null;
} catch (BadLocationException ble) {
@@ -108,7 +103,7 @@ public class CodeTemplateManager {
throw new InternalError("Error in CodeTemplateManager");
}
}
/**
* Returns the number of templates this manager knows about.
*
@@ -117,7 +112,7 @@ public class CodeTemplateManager {
public synchronized int getTemplateCount() {
return templates.size();
}
/**
* Returns the templates currently available.
*
@@ -127,29 +122,26 @@ public class CodeTemplateManager {
CodeTemplate[] temp = new CodeTemplate[templates.size()];
return templates.toArray(temp);
}
/**
* Returns whether the specified character is a valid character for a
* <code>CodeTemplate</code> id.
*
* @param ch
* The character to check.
* @param ch The character to check.
* @return Whether the character is a valid template character.
*/
public static final boolean isValidChar(char ch) {
return RSyntaxUtilities.isLetterOrDigit(ch) || ch == '_';
}
/**
* Returns the specified code template.
*
* @param template
* The template to remove.
* @return <code>true</code> if the template was removed, <code>false</code>
* if the template was not in this template manager.
* @throws IllegalArgumentException
* If <code>template</code> is
* <code>null</code>.
* @param template The template to remove.
* @return <code>true</code> if the template was removed, <code>false</code> if
* the template was not in this template manager.
* @throws IllegalArgumentException If <code>template</code> is
* <code>null</code>.
* @see #removeTemplate(String)
* @see #addTemplate(CodeTemplate)
*/
@@ -160,16 +152,14 @@ public class CodeTemplateManager {
// TODO: Do a binary search
return templates.remove(template);
}
/**
* Returns the code template with the specified id.
*
* @param id
* The id to check for.
* @return The code template that was removed, or <code>null</code> if
* there was no template with the specified ID.
* @throws IllegalArgumentException
* If <code>id</code> is <code>null</code>.
* @param id The id to check for.
* @return The code template that was removed, or <code>null</code> if there was
* no template with the specified ID.
* @throws IllegalArgumentException If <code>id</code> is <code>null</code>.
* @see #removeTemplate(CodeTemplate)
* @see #addTemplate(CodeTemplate)
*/
@@ -187,14 +177,12 @@ public class CodeTemplateManager {
}
return null;
}
/**
* Replaces the current set of available templates with the ones
* specified.
* Replaces the current set of available templates with the ones specified.
*
* @param newTemplates
* The new set of templates. Note that we will
* be taking a shallow copy of these and sorting them.
* @param newTemplates The new set of templates. Note that we will be taking a
* shallow copy of these and sorting them.
*/
public synchronized void replaceTemplates(CodeTemplate[] newTemplates) {
templates.clear();
@@ -205,7 +193,7 @@ public class CodeTemplateManager {
}
sortTemplates(); // Also recomputes maxTemplateIDLength.
}
/**
* Saves all templates as XML files in the current template directory.
*
@@ -243,14 +231,13 @@ public class CodeTemplateManager {
}
return wasSuccessful;
}
/**
* Sets the directory in which to look for templates. Calling this
* method adds any new templates found in the specified directory to
* the templates already registered.
* Sets the directory in which to look for templates. Calling this method adds
* any new templates found in the specified directory to the templates already
* registered.
*
* @param dir
* The new directory in which to look for templates.
* @param dir The new directory in which to look for templates.
* @return The new number of templates in this template manager, or
* <code>-1</code> if the specified directory does not exist.
*/
@@ -285,11 +272,10 @@ public class CodeTemplateManager {
}
return -1;
}
/**
* Removes any null entries in the current set of templates (if
* any), sorts the remaining templates, and computes the new
* maximum template ID length.
* Removes any null entries in the current set of templates (if any), sorts the
* remaining templates, and computes the new maximum template ID length.
*/
private synchronized void sortTemplates() {
// Get the maximum length of a template ID.
@@ -307,15 +293,14 @@ public class CodeTemplateManager {
}
Collections.sort(templates);
}
/**
* A comparator that takes a <code>CodeTemplate</code> as its first
* parameter and a <code>Segment</code> as its second, and knows
* to compare the template's ID to the segment's text.
* A comparator that takes a <code>CodeTemplate</code> as its first parameter
* and a <code>Segment</code> as its second, and knows to compare the template's
* ID to the segment's text.
*/
@SuppressWarnings("rawtypes")
private static class TemplateComparator implements Comparator, Serializable {
@Override
public int compare(Object template, Object segment) {
// Get template start index (0) and length.
@@ -345,12 +330,12 @@ public class CodeTemplateManager {
return len1 - len2;
}
}
/**
* A file filter that accepts only XML files.
*/
private static class XMLFileFilter implements FileFilter {
@Override
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".xml");
@@ -15,19 +15,18 @@ import javax.swing.KeyStroke;
import org.fife.ui.rtextarea.RTADefaultInputMap;
/**
* The default input map for an <code>RSyntaxTextArea</code>.
* Currently, the new key bindings include:
* The default input map for an <code>RSyntaxTextArea</code>. Currently, the new
* key bindings include:
* <ul>
* <li>Shift+Tab indents the current line or currently selected lines
* to the left.
* <li>Shift+Tab indents the current line or currently selected lines to the
* left.
* </ul>
*
* @author Robert Futrell
* @version 1.0
*/
@SuppressWarnings({ "checkstyle:linelength" })
public class RSyntaxTextAreaDefaultInputMap extends RTADefaultInputMap {
/**
* Constructs the default input map for an <code>RSyntaxTextArea</code>.
*/
@@ -60,18 +59,23 @@ public class RSyntaxTextAreaDefaultInputMap extends RTADefaultInputMap {
// (unfortunately) don't have a ToggleCommentAction for *nix
// out-of-the-box.
// Applications can add one easily enough if they want one.
put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, defaultMod), RSyntaxTextAreaEditorKit.rstaToggleCommentAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, defaultMod),
RSyntaxTextAreaEditorKit.rstaToggleCommentAction);
}
put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultMod), RSyntaxTextAreaEditorKit.rstaGoToMatchingBracketAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultMod),
RSyntaxTextAreaEditorKit.rstaGoToMatchingBracketAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, defaultMod), RSyntaxTextAreaEditorKit.rstaCollapseFoldAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, defaultMod), RSyntaxTextAreaEditorKit.rstaExpandFoldAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultMod), RSyntaxTextAreaEditorKit.rstaCollapseAllFoldsAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY, defaultMod), RSyntaxTextAreaEditorKit.rstaExpandAllFoldsAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultMod),
RSyntaxTextAreaEditorKit.rstaCollapseAllFoldsAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY, defaultMod),
RSyntaxTextAreaEditorKit.rstaExpandAllFoldsAction);
// NOTE: no modifiers => mapped to keyTyped. If we had "0" as a second
// second parameter, we'd get the template action (keyPressed) AND the
// default space action (keyTyped).
// put(KeyStroke.getKeyStroke(' '),
// RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, defaultShift), RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, defaultShift),
RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction);
}
}
File diff suppressed because it is too large. Load diff
+34 -47
View File
@@ -28,9 +28,8 @@ import javax.swing.JPanel;
* @author Robert Futrell
* @version 0.6
*/
@SuppressWarnings({ "checkstyle:visibilitymodifier" })
public class Style implements Cloneable {
public static final Color DEFAULT_FOREGROUND = Color.BLACK;
public static final Color DEFAULT_BACKGROUND = null;
public static final Font DEFAULT_FONT = null;
@@ -39,62 +38,52 @@ public class Style implements Cloneable {
public boolean underline;
public Font font;
public FontMetrics fontMetrics;
/**
* Creates a new style defaulting to black foreground, no
* background, and no styling.
* Creates a new style defaulting to black foreground, no background, and no
* styling.
*/
public Style() {
this(DEFAULT_FOREGROUND);
}
/**
* Creates a new style with the specified foreground and no styling.
*
* @param fg
* The foreground color to use.
* @param fg The foreground color to use.
*/
public Style(Color fg) {
this(fg, DEFAULT_BACKGROUND);
}
/**
* Creates a new style with the specified colors and no styling.
*
* @param fg
* The foreground color to use.
* @param bg
* The background color to use.
* @param fg The foreground color to use.
* @param bg The background color to use.
*/
public Style(Color fg, Color bg) {
this(fg, bg, DEFAULT_FONT);
}
/**
* Creates a new style.
*
* @param fg
* The foreground color to use.
* @param bg
* The background color to use.
* @param font
* The font for this syntax scheme.
* @param fg The foreground color to use.
* @param bg The background color to use.
* @param font The font for this syntax scheme.
*/
public Style(Color fg, Color bg, Font font) {
this(fg, bg, font, false);
}
/**
* Creates a new style.
*
* @param fg
* The foreground color to use.
* @param bg
* The background color to use.
* @param font
* The font for this syntax scheme.
* @param underline
* Whether or not to underline tokens with this style.
* @param fg The foreground color to use.
* @param bg The background color to use.
* @param font The font for this syntax scheme.
* @param underline Whether or not to underline tokens with this style.
*/
public Style(Color fg, Color bg, Font font, boolean underline) {
foreground = fg;
@@ -106,15 +95,14 @@ public class Style implements Cloneable {
// rendering
// hints!
}
/**
* Returns whether or not two (possibly <code>null</code>) objects are
* equal.
* Returns whether or not two (possibly <code>null</code>) objects are equal.
*/
private boolean areEqual(Object o1, Object o2) {
return (o1 == null && o2 == null) || (o1 != null && o1.equals(o2));
}
/**
* Returns a deep copy of this object.
*
@@ -136,34 +124,32 @@ public class Style implements Cloneable {
clone.fontMetrics = fontMetrics;
return clone;
}
/**
* Returns whether or not two syntax schemes are equal.
*
* @param o2
* The object with which to compare this syntax scheme.
* @return Whether or not these two syntax schemes represent the same
* scheme.
* @param o2 The object with which to compare this syntax scheme.
* @return Whether or not these two syntax schemes represent the same scheme.
*/
@Override
public boolean equals(Object o2) {
if (o2 instanceof Style) {
Style ss2 = (Style) o2;
if (this.underline == ss2.underline && areEqual(foreground, ss2.foreground) && areEqual(background, ss2.background)
&& areEqual(font, ss2.font) && areEqual(fontMetrics, ss2.fontMetrics)) {
if (this.underline == ss2.underline && areEqual(foreground, ss2.foreground)
&& areEqual(background, ss2.background) && areEqual(font, ss2.font)
&& areEqual(fontMetrics, ss2.fontMetrics)) {
return true;
}
}
return false;
}
/**
* Computes the hash code to use when adding this syntax scheme to
* hash tables.
* Computes the hash code to use when adding this syntax scheme to hash tables.
* <p>
*
* This method is implemented, since {@link #equals(Object)} is implemented,
* to keep FindBugs happy.
* This method is implemented, since {@link #equals(Object)} is implemented, to
* keep FindBugs happy.
*
* @return The hash code.
*/
@@ -178,7 +164,7 @@ public class Style implements Cloneable {
}
return hashCode;
}
/**
* Returns a string representation of this style.
*
@@ -186,6 +172,7 @@ public class Style implements Cloneable {
*/
@Override
public String toString() {
return "[Style: foreground: " + foreground + ", background: " + background + ", underline: " + underline + ", font: " + font + "]";
return "[Style: foreground: " + foreground + ", background: " + background + ", underline: " + underline
+ ", font: " + font + "]";
}
}
+116 -145
View File
@@ -24,8 +24,8 @@ import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* The set of colors and styles used by an <code>RSyntaxTextArea</code> to
* color tokens.
* The set of colors and styles used by an <code>RSyntaxTextArea</code> to color
* tokens.
* <p>
* You can use this class to programmatically set the fonts and colors used in
* an RSyntaxTextArea, but for more powerful, externalized control, consider
@@ -35,20 +35,18 @@ import org.xml.sax.helpers.XMLReaderFactory;
* @version 1.0
* @see Theme
*/
@SuppressWarnings({ "checkstyle:magicnumber" })
public class SyntaxScheme implements Cloneable, TokenTypes {
private Style[] styles;
private static final String VERSION = "*ver1";
/**
* Creates a color scheme that either has all color values set to
* a default value or set to <code>null</code>.
* Creates a color scheme that either has all color values set to a default
* value or set to <code>null</code>.
*
* @param useDefaults
* If <code>true</code>, all color values will
* be set to default colors; if <code>false</code>, all colors
* will be initially <code>null</code>.
* @param useDefaults If <code>true</code>, all color values will be set to
* default colors; if <code>false</code>, all colors will be
* initially <code>null</code>.
*/
public SyntaxScheme(boolean useDefaults) {
styles = new Style[DEFAULT_NUM_TOKEN_TYPES];
@@ -56,50 +54,43 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
restoreDefaults(null);
}
}
/**
* Creates a default color scheme.
*
* @param baseFont
* The base font to use. Keywords will be a bold version
* of this font, and comments will be an italicized version of
* this
* font.
* @param baseFont The base font to use. Keywords will be a bold version of this
* font, and comments will be an italicized version of this
* font.
*/
public SyntaxScheme(Font baseFont) {
this(baseFont, true);
}
/**
* Creates a default color scheme.
*
* @param baseFont
* The base font to use. Keywords will be a bold version
* of this font, and comments will be an italicized version of
* this
* font.
* @param fontStyles
* Whether bold and italic should be used in the scheme
* (vs. all tokens using a plain font).
* @param baseFont The base font to use. Keywords will be a bold version of
* this font, and comments will be an italicized version of
* this font.
* @param fontStyles Whether bold and italic should be used in the scheme (vs.
* all tokens using a plain font).
*/
public SyntaxScheme(Font baseFont, boolean fontStyles) {
styles = new Style[DEFAULT_NUM_TOKEN_TYPES];
restoreDefaults(baseFont, fontStyles);
}
/**
* Changes the "base font" for this syntax scheme. This is called by
* <code>RSyntaxTextArea</code> when its font changes via
* <code>setFont()</code>. This looks for tokens that use a derivative of
* the text area's old font (but bolded and/or italicized) and make them
* use the new font with those stylings instead. This is desirable because
* most programmers prefer a single font to be used in their text editor,
* but might want bold (say for keywords) or italics.
* <code>setFont()</code>. This looks for tokens that use a derivative of the
* text area's old font (but bolded and/or italicized) and make them use the new
* font with those stylings instead. This is desirable because most programmers
* prefer a single font to be used in their text editor, but might want bold
* (say for keywords) or italics.
*
* @param old
* The old font of the text area.
* @param font
* The new font of the text area.
* @param old The old font of the text area.
* @param font The new font of the text area.
*/
void changeBaseFont(Font old, Font font) {
for (int i = 0; i < styles.length; i++) {
@@ -113,7 +104,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
}
}
/**
* Returns a deep copy of this color scheme.
*
@@ -137,15 +128,13 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
return shcs;
}
/**
* Tests whether this color scheme is the same as another color scheme.
*
* @param otherScheme
* The color scheme to compare to.
* @return <code>true</code> if this color scheme and
* <code>otherScheme</code> are the same scheme;
* <code>false</code> otherwise.
* @param otherScheme The color scheme to compare to.
* @return <code>true</code> if this color scheme and <code>otherScheme</code>
* are the same scheme; <code>false</code> otherwise.
*/
@Override
public boolean equals(Object otherScheme) {
@@ -167,24 +156,22 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
return true;
}
/**
* Returns a hex string representing an RGB color, of the form
* <code>"$rrggbb"</code>.
*
* @param c
* The color.
* @param c The color.
* @return The string representation of the color.
*/
private static String getHexString(Color c) {
return "$" + Integer.toHexString((c.getRGB() & 0xffffff) + 0x1000000).substring(1);
}
/**
* Returns the specified style.
*
* @param index
* The index of the style.
* @param index The index of the style.
* @return The style.
* @see #setStyle(int, Style)
* @see #getStyleCount()
@@ -192,7 +179,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
public Style getStyle(int index) {
return styles[index];
}
/**
* Returns the number of styles.
*
@@ -202,14 +189,14 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
public int getStyleCount() {
return styles.length;
}
/**
* Used by third party implementors e.g. SquirreL SQL. Most applications do
* not need to call this method.
* Used by third party implementors e.g. SquirreL SQL. Most applications do not
* need to call this method.
* <p>
* Note that the returned array is not a copy of the style data; editing the
* array will modify the styles used by any <code>RSyntaxTextArea</code>
* using this scheme.
* array will modify the styles used by any <code>RSyntaxTextArea</code> using
* this scheme.
*
* @return The style array.
* @see #setStyles(Style[])
@@ -217,10 +204,10 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
public Style[] getStyles() {
return styles;
}
/**
* This is implemented to be consistent with {@link #equals(Object)}.
* This is a requirement to keep FindBugs happy.
* This is implemented to be consistent with {@link #equals(Object)}. This is a
* requirement to keep FindBugs happy.
*
* @return The hash code for this object.
*/
@@ -238,24 +225,20 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
return hashCode;
}
/**
* Loads a syntax scheme from an input stream.
* <p>
*
* Consider using the {@link Theme} class for saving and loading RSTA
* styles rather than using this API.
* Consider using the {@link Theme} class for saving and loading RSTA styles
* rather than using this API.
*
* @param baseFont
* The font to use as the "base" for the syntax scheme.
* If this is <code>null</code>, a default monospaced font is
* used.
* @param in
* The stream to load from. It is up to the caller to close this
* stream when they are done.
* @param baseFont The font to use as the "base" for the syntax scheme. If this
* is <code>null</code>, a default monospaced font is used.
* @param in The stream to load from. It is up to the caller to close this
* stream when they are done.
* @return The syntax scheme.
* @throws IOException
* If an IO error occurs.
* @throws IOException If an IO error occurs.
*/
public static SyntaxScheme load(Font baseFont, InputStream in) throws IOException {
if (baseFont == null) {
@@ -263,42 +246,40 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
return SyntaxSchemeLoader.load(baseFont, in);
}
/**
* Loads a syntax highlighting color scheme from a string created from
* <code>toCommaSeparatedString</code>. This method is useful for saving
* and restoring color schemes.
* <code>toCommaSeparatedString</code>. This method is useful for saving and
* restoring color schemes.
* <p>
*
* Consider using the {@link Theme} class for saving and loading RSTA
* styles rather than using this API.
* Consider using the {@link Theme} class for saving and loading RSTA styles
* rather than using this API.
*
* @param string
* A string generated from {@link #toCommaSeparatedString()}.
* @param string A string generated from {@link #toCommaSeparatedString()}.
* @return A color scheme.
* @see #toCommaSeparatedString()
*/
public static SyntaxScheme loadFromString(String string) {
return loadFromString(string, DEFAULT_NUM_TOKEN_TYPES);
}
/**
* Loads a syntax highlighting color scheme from a string created from
* <code>toCommaSeparatedString</code>. This method is useful for saving
* and restoring color schemes.
* <code>toCommaSeparatedString</code>. This method is useful for saving and
* restoring color schemes.
* <p>
*
* Consider using the {@link Theme} class for saving and loading RSTA
* styles rather than using this API.
* Consider using the {@link Theme} class for saving and loading RSTA styles
* rather than using this API.
*
* @param string
* A string generated from {@link #toCommaSeparatedString()}.
* @param tokenTypeCount
* The number of token types saved in this string.
* This should be the number of token types saved by your custom
* SyntaxScheme subclass,
* or {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES} if you used the
* standard implementation (which most people will).
* @param string A string generated from
* {@link #toCommaSeparatedString()}.
* @param tokenTypeCount The number of token types saved in this string. This
* should be the number of token types saved by your
* custom SyntaxScheme subclass, or
* {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES} if you used
* the standard implementation (which most people will).
* @return A color scheme.
* @see #loadFromString(String)
* @see #toCommaSeparatedString()
@@ -314,7 +295,8 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
int tokenCount = tokenTypeCount * 7 + 1; // Version string
if (tokens.length != tokenCount) {
throw new Exception("Not enough tokens in packed color scheme: expected " + tokenCount + ", found " + tokens.length);
throw new Exception("Not enough tokens in packed color scheme: expected " + tokenCount + ", found "
+ tokens.length);
}
// Use StyleContext to create fonts to get composite fonts for
// Asian glyphs.
@@ -359,7 +341,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
return scheme;
}
void refreshFontMetrics(Graphics2D g2d) {
// It is assumed that any rendering hints are already applied to g2d.
for (int i = 0; i < styles.length; i++) {
@@ -369,29 +351,24 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
}
}
/**
* Restores all colors and fonts to their default values.
*
* @param baseFont
* The base font to use when creating this scheme. If
* this is <code>null</code>, then a default monospaced font is
* used.
* @param baseFont The base font to use when creating this scheme. If this is
* <code>null</code>, then a default monospaced font is used.
*/
public void restoreDefaults(Font baseFont) {
restoreDefaults(baseFont, true);
}
/**
* Restores all colors and fonts to their default values.
*
* @param baseFont
* The base font to use when creating this scheme. If
* this is <code>null</code>, then a default monospaced font is
* used.
* @param fontStyles
* Whether bold and italic should be used in the scheme
* (vs. all tokens using a plain font).
* @param baseFont The base font to use when creating this scheme. If this is
* <code>null</code>, then a default monospaced font is used.
* @param fontStyles Whether bold and italic should be used in the scheme (vs.
* all tokens using a plain font).
*/
public void restoreDefaults(Font baseFont, boolean fontStyles) {
// Colors used by tokens.
@@ -469,40 +446,36 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
}
}
/**
* Sets a style to use when rendering a token type.
*
* @param type
* The token type.
* @param style
* The style for the token type.
* @param type The token type.
* @param style The style for the token type.
* @see #getStyle(int)
*/
public void setStyle(int type, Style style) {
styles[type] = style;
}
/**
* Used by third party implementors e.g. SquirreL SQL. Most applications do
* not need to call this method; individual styles can be set via
* Used by third party implementors e.g. SquirreL SQL. Most applications do not
* need to call this method; individual styles can be set via
* {@link #setStyle(int, Style)}.
*
* @param styles
* The new array of styles to use. Note that this should
* have length of at least
* {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES}.
* @param styles The new array of styles to use. Note that this should have
* length of at least {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES}.
* @see #setStyle(int, Style)
* @see #getStyles()
*/
public void setStyles(Style[] styles) {
this.styles = styles;
}
/**
* Returns the color represented by a string. If the first char in the
* string is '<code>$</code>', it is assumed to be in hex, otherwise it is
* assumed to be decimal. So, for example, both of these:
* Returns the color represented by a string. If the first char in the string is
* '<code>$</code>', it is assumed to be in hex, otherwise it is assumed to be
* decimal. So, for example, both of these:
*
* <pre>
* "$00ff00"
@@ -511,8 +484,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
*
* will return <code>new Color(0, 255, 0)</code>.
*
* @param s
* The string to evaluate.
* @param s The string to evaluate.
* @return The color.
*/
private static Color stringToColor(String s) {
@@ -521,28 +493,26 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
char ch = s.charAt(0);
return new Color((ch == '$' || ch == '#') ? Integer.parseInt(s.substring(1), 16) : Integer.parseInt(s));
}
/**
* Returns this syntax highlighting scheme as a comma-separated list of
* values as follows:
* Returns this syntax highlighting scheme as a comma-separated list of values
* as follows:
* <ul>
* <li>If a color is non-null, it is added as a 24-bit integer
* of the form <code>((r&lt;*lt;16) | (g&lt;*lt;8) | (b))</code>; if
* it is <code>null</code>, it is added as "<i>-,</i>".
* <li>If a color is non-null, it is added as a 24-bit integer of the form
* <code>((r&lt;*lt;16) | (g&lt;*lt;8) | (b))</code>; if it is
* <code>null</code>, it is added as "<i>-,</i>".
* <li>The font and style (bold/italic) is added as an integer like so:
* "<i>family,</i> <i>style,</i> <i>size</i>".
* <li>The entire syntax highlighting scheme is thus one long string of
* color schemes of the format "<i>i,[fg],[bg],uline,[style]</i>,
* where:
* <li>The entire syntax highlighting scheme is thus one long string of color
* schemes of the format "<i>i,[fg],[bg],uline,[style]</i>, where:
* <ul>
* <li><code>i</code> is the index of the syntax scheme.
* <li><i>fg</i> and <i>bg</i> are the foreground and background
* colors for the scheme, and may be null (represented by
* <code>-</code>).
* <li><code>uline</code> is whether or not the font should be
* underlined, and is either <code>t</code> or <code>f</code>.
* <li><code>style</code> is the <code>family,style,size</code>
* triplet described above.
* <li><i>fg</i> and <i>bg</i> are the foreground and background colors for the
* scheme, and may be null (represented by <code>-</code>).
* <li><code>uline</code> is whether or not the font should be underlined, and
* is either <code>t</code> or <code>f</code>.
* <li><code>style</code> is the <code>family,style,size</code> triplet
* described above.
* </ul>
* </ul>
*
@@ -566,26 +536,27 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
sb.append(ss.underline ? "t," : "f,");
Font font = ss.font;
if (font != null) {
sb.append(font.getFamily()).append(',').append(font.getStyle()).append(',').append(font.getSize()).append(',');
sb.append(font.getFamily()).append(',').append(font.getStyle()).append(',').append(font.getSize())
.append(',');
} else {
sb.append("-,,,");
}
}
return sb.substring(0, sb.length() - 1); // Take off final ','.
}
/**
* Loads a <code>SyntaxScheme</code> from an XML file.
*/
private static class SyntaxSchemeLoader extends DefaultHandler {
private Font baseFont;
private SyntaxScheme scheme;
SyntaxSchemeLoader(Font baseFont) {
scheme = new SyntaxScheme(baseFont);
}
public static SyntaxScheme load(Font baseFont, InputStream in) throws IOException {
SyntaxSchemeLoader parser = null;
try {
@@ -601,7 +572,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
}
return parser.scheme;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
if ("style".equals(qName)) {
+60 -77
View File
@@ -62,17 +62,16 @@ import org.xml.sax.helpers.DefaultHandler;
* for various tasks.
* <p>
*
* Note that to save a <code>Theme</code> via {@link #save(OutputStream)},
* you must currently create a <code>Theme</code> from a text area wrapped in
* an <code>RTextScrollPane</code>, so that the color information for the
* gutter can be retrieved.
* Note that to save a <code>Theme</code> via {@link #save(OutputStream)}, you
* must currently create a <code>Theme</code> from a text area wrapped in an
* <code>RTextScrollPane</code>, so that the color information for the gutter
* can be retrieved.
*
* @author Robert Futrell
* @version 1.0
*/
@SuppressWarnings({ "checkstyle:visibilitymodifier" })
public class Theme {
public Font baseFont;
public Color bgColor;
public Color caretColor;
@@ -103,14 +102,13 @@ public class Theme {
public Color foldIndicatorFG;
public Color foldBG;
public Color armedFoldBG;
/**
* Private constructor, used when loading from a stream.
*
* @param baseFont
* The default font to use for any "base font" properties
* not specified in the theme XML. If this is <code>null</code>,
* a default monospaced font will be used.
* @param baseFont The default font to use for any "base font" properties not
* specified in the theme XML. If this is <code>null</code>, a
* default monospaced font will be used.
*/
private Theme(Font baseFont) {
// Optional fields that require a default value.
@@ -118,13 +116,12 @@ public class Theme {
secondaryLanguages = new Color[3];
activeLineRangeColor = Gutter.DEFAULT_ACTIVE_LINE_RANGE_COLOR;
}
/**
* Creates a theme from an RSyntaxTextArea. It should be contained in
* an <code>RTextScrollPane</code> to get all gutter color information.
* Creates a theme from an RSyntaxTextArea. It should be contained in an
* <code>RTextScrollPane</code> to get all gutter color information.
*
* @param textArea
* The text area.
* @param textArea The text area.
*/
public Theme(RSyntaxTextArea textArea) {
baseFont = textArea.getFont();
@@ -165,12 +162,11 @@ public class Theme {
armedFoldBG = gutter.getArmedFoldBackground();
}
}
/**
* Applies this theme to a text area.
*
* @param textArea
* The text area to apply this theme to.
* @param textArea The text area to apply this theme to.
*/
public void apply(RSyntaxTextArea textArea) {
textArea.setFont(baseFont);
@@ -212,7 +208,7 @@ public class Theme {
gutter.setArmedFoldBackground(armedFoldBG);
}
}
private static String colorToString(Color c) {
int color = c.getRGB() & 0xffffff;
StringBuilder stringBuilder = new StringBuilder(Integer.toHexString(color));
@@ -221,7 +217,7 @@ public class Theme {
}
return stringBuilder.toString();
}
/**
* Returns the default selection background color to use if "default" is
* specified in a theme.
@@ -243,7 +239,7 @@ public class Theme {
}
return c;
}
/**
* Returns the default selection background color to use if "default" is
* specified in a theme.
@@ -264,10 +260,10 @@ public class Theme {
}
return c;
}
/**
* Returns the default "selected text" color to use if "default" is
* specified in a theme.
* Returns the default "selected text" color to use if "default" is specified in
* a theme.
*
* @return The default selection foreground color to use.
* @see #getDefaultSelectionBG()
@@ -285,16 +281,13 @@ public class Theme {
}
return c;
}
/**
* Returns the specified font.
*
* @param family
* The font family.
* @param style
* The style of font.
* @param size
* The size of the font.
* @param family The font family.
* @param style The style of font.
* @param size The size of the font.
* @return The font.
*/
private static Font getFont(String family, int style, int size) {
@@ -302,35 +295,30 @@ public class Theme {
StyleContext sc = StyleContext.getDefaultStyleContext();
return sc.getFont(family, style, size);
}
/**
* Loads a theme.
*
* @param in
* The input stream to read from. This will be closed when this
* method returns.
* @param in The input stream to read from. This will be closed when this method
* returns.
* @return The theme.
* @throws IOException
* If an IO error occurs.
* @throws IOException If an IO error occurs.
* @see #save(OutputStream)
*/
public static Theme load(InputStream in) throws IOException {
return load(in, null);
}
/**
* Loads a theme.
*
* @param in
* The input stream to read from. This will be closed when this
* method returns.
* @param baseFont
* The default font to use for any "base font" properties
* not specified in the theme XML. If this is <code>null</code>,
* a default monospaced font will be used.
* @param in The input stream to read from. This will be closed when this
* method returns.
* @param baseFont The default font to use for any "base font" properties not
* specified in the theme XML. If this is <code>null</code>, a
* default monospaced font will be used.
* @return The theme.
* @throws IOException
* If an IO error occurs.
* @throws IOException If an IO error occurs.
* @see #save(OutputStream)
*/
public static Theme load(InputStream in, Font baseFont) throws IOException {
@@ -343,14 +331,12 @@ public class Theme {
}
return theme;
}
/**
* Saves this theme to an output stream.
*
* @param out
* The output stream to write to.
* @throws IOException
* If an IO error occurs.
* @param out The output stream to write to.
* @throws IOException If an IO error occurs.
* @see #load(InputStream)
*/
public void save(OutputStream out) throws IOException {
@@ -495,11 +481,11 @@ public class Theme {
bout.close();
}
}
/**
* Returns the color represented by a string. The input is expected to
* be a 6-digit hex string, optionally prefixed by a '$'. For example,
* either of the following:
* Returns the color represented by a string. The input is expected to be a
* 6-digit hex string, optionally prefixed by a '$'. For example, either of the
* following:
*
* <pre>
* "$00ff00"
@@ -508,18 +494,17 @@ public class Theme {
*
* will return <code>new Color(0, 255, 0)</code>.
*
* @param s
* The string to evaluate.
* @param s The string to evaluate.
* @return The color.
*/
private static Color stringToColor(String s) {
return stringToColor(s, null);
}
/**
* Returns the color represented by a string. The input is expected to
* be a 6-digit hex string, optionally prefixed by a '$'. For example,
* either of the following:
* Returns the color represented by a string. The input is expected to be a
* 6-digit hex string, optionally prefixed by a '$'. For example, either of the
* following:
*
* <pre>
* "$00ff00"
@@ -528,11 +513,9 @@ public class Theme {
*
* will return <code>new Color(0, 255, 0)</code>.
*
* @param s
* The string to evaluate.
* @param defaultVal
* The color to use if <code>s</code> is
* "<code>default</code>".
* @param s The string to evaluate.
* @param defaultVal The color to use if <code>s</code> is
* "<code>default</code>".
* @return The color.
*/
private static Color stringToColor(String s, Color defaultVal) {
@@ -547,24 +530,24 @@ public class Theme {
}
return null;
}
/**
* Loads a <code>SyntaxScheme</code> from an XML file.
*/
private static class XmlHandler extends DefaultHandler {
private Theme theme;
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
throw e;
}
public static void load(Theme theme, InputStream in) throws IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
@@ -584,7 +567,7 @@ public class Theme {
throw new IOException(se.toString());
}
}
private static int parseInt(Attributes attrs, String attr, int def) {
int value = def;
String temp = attrs.getValue(attr);
@@ -597,12 +580,12 @@ public class Theme {
}
return value;
}
@Override
public InputSource resolveEntity(String publicID, String systemID) throws SAXException {
return new InputSource(getClass().getResourceAsStream("themes/theme.dtd"));
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
if ("background".equals(qName)) {
@@ -787,7 +770,7 @@ public class Theme {
}
}
}
@Override
public void warning(SAXParseException e) throws SAXException {
throw e;
+207 -237
View File
@@ -22,19 +22,18 @@ import javax.swing.text.Utilities;
* <b>Note:</b> The instances of <code>Token</code> returned by
* {@link RSyntaxDocument}s are pooled and should always be treated as
* immutable. They should not be cast to <code>TokenImpl</code> and modified.
* Modifying tokens you did not create yourself can and will result in
* rendering issues and/or runtime exceptions. You have been warned!
* Modifying tokens you did not create yourself can and will result in rendering
* issues and/or runtime exceptions. You have been warned!
*
* @author Robert Futrell
* @version 0.3
*/
@SuppressWarnings({ "checkstyle:visibilitymodifier" })
public class TokenImpl implements Token {
/**
* The text this token represents. This is implemented as a segment so we
* can point directly to the text in the document without having to make a
* copy of it.
* The text this token represents. This is implemented as a segment so we can
* point directly to the text in the document without having to make a copy of
* it.
*/
public char[] text;
public int textOffset;
@@ -59,11 +58,11 @@ public class TokenImpl implements Token {
* The language this token is in, <code>&gt;= 0</code>.
*/
private int languageIndex;
/**
* Creates a "null" token. The token itself is not null; rather, it
* signifies that it is the last token in a linked list of tokens and
* that it is not part of a "multi-line token."
* Creates a "null" token. The token itself is not null; rather, it signifies
* that it is the last token in a linked list of tokens and that it is not part
* of a "multi-line token."
*/
public TokenImpl() {
this.text = null;
@@ -74,69 +73,55 @@ public class TokenImpl implements Token {
hyperlink = false;
nextToken = null;
}
/**
* Constructor.
*
* @param line
* The segment from which to get the token.
* @param beg
* The first character's position in <code>line</code>.
* @param end
* The last character's position in <code>line</code>.
* @param startOffset
* The offset into the document at which this
* token begins.
* @param type
* A token type listed as "generic" above.
* @param languageIndex
* The language index for this token.
* @param line The segment from which to get the token.
* @param beg The first character's position in <code>line</code>.
* @param end The last character's position in <code>line</code>.
* @param startOffset The offset into the document at which this token begins.
* @param type A token type listed as "generic" above.
* @param languageIndex The language index for this token.
*/
public TokenImpl(Segment line, int beg, int end, int startOffset, int type, int languageIndex) {
this(line.array, beg, end, startOffset, type, languageIndex);
}
/**
* Constructor.
*
* @param line
* The segment from which to get the token.
* @param beg
* The first character's position in <code>line</code>.
* @param end
* The last character's position in <code>line</code>.
* @param startOffset
* The offset into the document at which this
* token begins.
* @param type
* A token type listed as "generic" above.
* @param languageIndex
* The language index for this token.
* @param line The segment from which to get the token.
* @param beg The first character's position in <code>line</code>.
* @param end The last character's position in <code>line</code>.
* @param startOffset The offset into the document at which this token begins.
* @param type A token type listed as "generic" above.
* @param languageIndex The language index for this token.
*/
public TokenImpl(char[] line, int beg, int end, int startOffset, int type, int languageIndex) {
this();
set(line, beg, end, startOffset, type);
setLanguageIndex(languageIndex);
}
/**
* Creates this token as a copy of the passed-in token.
*
* @param t2
* The token from which to make a copy.
* @param t2 The token from which to make a copy.
*/
public TokenImpl(Token t2) {
this();
copyFrom(t2);
}
@Override
public StringBuilder appendHTMLRepresentation(StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily) {
return appendHTMLRepresentation(sb, textArea, fontFamily, false);
}
@Override
public StringBuilder appendHTMLRepresentation(StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily, boolean tabsToSpaces) {
public StringBuilder appendHTMLRepresentation(StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily,
boolean tabsToSpaces) {
SyntaxScheme colorScheme = textArea.getSyntaxScheme();
Style scheme = colorScheme.getStyle(getType());
Font font = textArea.getFontForTokenType(getType());// scheme.font;
@@ -177,18 +162,15 @@ public class TokenImpl implements Token {
}
return sb;
}
/**
* Appends an HTML version of the lexeme of this token (i.e. no style
* HTML, but replacing chars such as <code>\t</code>, <code>&lt;</code>
* and <code>&gt;</code> with their escapes).
* Appends an HTML version of the lexeme of this token (i.e. no style HTML, but
* replacing chars such as <code>\t</code>, <code>&lt;</code> and
* <code>&gt;</code> with their escapes).
*
* @param textArea
* The text area.
* @param sb
* The buffer to append to.
* @param tabsToSpaces
* Whether to convert tabs into spaces.
* @param textArea The text area.
* @param sb The buffer to append to.
* @param tabsToSpaces Whether to convert tabs into spaces.
* @return The same buffer.
*/
private StringBuilder appendHtmlLexeme(RSyntaxTextArea textArea, StringBuilder sb, boolean tabsToSpaces) {
@@ -199,64 +181,64 @@ public class TokenImpl implements Token {
while (i < textOffset + textCount) {
char ch = text[i];
switch (ch) {
case ' ':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append(lastWasSpace ? "&nbsp;" : " ");
lastWasSpace = true;
break;
case '\t':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
if (tabsToSpaces && tabStr == null) {
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < textArea.getTabSize(); j++) {
stringBuilder.append("&nbsp;");
}
tabStr = stringBuilder.toString();
case ' ':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append(lastWasSpace ? "&nbsp;" : " ");
lastWasSpace = true;
break;
case '\t':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
if (tabsToSpaces && tabStr == null) {
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < textArea.getTabSize(); j++) {
stringBuilder.append("&nbsp;");
}
sb.append(tabsToSpaces ? tabStr : "&#09;");
lastWasSpace = false;
break;
case '&':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&amp;");
lastWasSpace = false;
break;
case '<':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&lt;");
lastWasSpace = false;
break;
case '>':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&gt;");
lastWasSpace = false;
break;
case '\'':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&#39;");
lastWasSpace = false;
break;
case '"':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&#34;");
lastWasSpace = false;
break;
case '/': // OWASP-recommended to escape even though unnecessary
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&#47;");
lastWasSpace = false;
break;
default:
lastWasSpace = false;
break;
tabStr = stringBuilder.toString();
}
sb.append(tabsToSpaces ? tabStr : "&#09;");
lastWasSpace = false;
break;
case '&':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&amp;");
lastWasSpace = false;
break;
case '<':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&lt;");
lastWasSpace = false;
break;
case '>':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&gt;");
lastWasSpace = false;
break;
case '\'':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&#39;");
lastWasSpace = false;
break;
case '"':
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&#34;");
lastWasSpace = false;
break;
case '/': // OWASP-recommended to escape even though unnecessary
sb.append(text, lastI, i - lastI);
lastI = i + 1;
sb.append("&#47;");
lastWasSpace = false;
break;
default:
lastWasSpace = false;
break;
}
i++;
}
@@ -265,23 +247,22 @@ public class TokenImpl implements Token {
}
return sb;
}
@Override
public char charAt(int index) {
return text[textOffset + index];
}
@Override
public boolean containsPosition(int pos) {
return pos >= getOffset() && pos < getOffset() + textCount;
}
/**
* Makes one token point to the same text segment, and have the same value
* as another token.
* Makes one token point to the same text segment, and have the same value as
* another token.
*
* @param t2
* The token from which to copy.
* @param t2 The token from which to copy.
*/
public void copyFrom(Token t2) {
text = t2.getTextArray();
@@ -293,12 +274,12 @@ public class TokenImpl implements Token {
languageIndex = t2.getLanguageIndex();
nextToken = t2.getNextToken();
}
@Override
public int documentToToken(int pos) {
return pos + (textOffset - getOffset());
}
@Override
public boolean endsWith(char[] ch) {
if (ch == null || ch.length > textCount) {
@@ -312,7 +293,7 @@ public class TokenImpl implements Token {
}
return true;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
@@ -322,21 +303,21 @@ public class TokenImpl implements Token {
return false;
}
Token t2 = (Token) obj;
return offset == t2.getOffset() && type == t2.getType() && languageIndex == t2.getLanguageIndex() && hyperlink == t2.isHyperlink()
&& ((getLexeme() == null && t2.getLexeme() == null) || (getLexeme() != null && getLexeme().equals(t2.getLexeme())));
return offset == t2.getOffset() && type == t2.getType() && languageIndex == t2.getLanguageIndex()
&& hyperlink == t2.isHyperlink() && ((getLexeme() == null && t2.getLexeme() == null)
|| (getLexeme() != null && getLexeme().equals(t2.getLexeme())));
}
@Override
public int getEndOffset() {
return offset + textCount;
}
/**
* Returns a <code>String</code> of the form "#xxxxxx" good for use
* in HTML, representing the given color.
* Returns a <code>String</code> of the form "#xxxxxx" good for use in HTML,
* representing the given color.
*
* @param color
* The color to get a string for.
* @param color The color to get a string for.
* @return The HTML form of the color. If <code>color</code> is
* <code>null</code>, <code>#000000</code> is returned.
*/
@@ -358,39 +339,39 @@ public class TokenImpl implements Token {
}
return "#" + hexRed + hexGreen + hexBlue;
}
@Override
public String getHTMLRepresentation(RSyntaxTextArea textArea) {
StringBuilder buf = new StringBuilder();
appendHTMLRepresentation(buf, textArea, true);
return buf.toString();
}
@Override
public int getLanguageIndex() {
return languageIndex;
}
@Override
public Token getLastNonCommentNonWhitespaceToken() {
Token last = null;
for (Token t = this; t != null && t.isPaintable(); t = t.getNextToken()) {
switch (t.getType()) {
case COMMENT_DOCUMENTATION:
case COMMENT_EOL:
case COMMENT_MULTILINE:
case COMMENT_KEYWORD:
case COMMENT_MARKUP:
case WHITESPACE:
break;
default:
last = t;
break;
case COMMENT_DOCUMENTATION:
case COMMENT_EOL:
case COMMENT_MULTILINE:
case COMMENT_KEYWORD:
case COMMENT_MARKUP:
case WHITESPACE:
break;
default:
last = t;
break;
}
}
return last;
}
@Override
public Token getLastPaintableToken() {
Token t = this;
@@ -403,12 +384,12 @@ public class TokenImpl implements Token {
}
return null;
}
@Override
public String getLexeme() {
return text == null ? null : new String(text, textOffset, textCount);
}
@Override
public int getListOffset(RSyntaxTextArea textArea, TabExpander e, float x0, float x) {
// If the coordinate in question is before this line's start, quit.
@@ -449,17 +430,17 @@ public class TokenImpl implements Token {
// If we didn't find anything, return the end position of the text.
return last;
}
@Override
public Token getNextToken() {
return nextToken;
}
@Override
public int getOffset() {
return offset;
}
@Override
public int getOffsetBeforeX(RSyntaxTextArea textArea, TabExpander e, float startX, float endBeforeX) {
FontMetrics fm = textArea.getFontMetricsForTokenType(getType());
@@ -484,27 +465,27 @@ public class TokenImpl implements Token {
// If we got here, the whole token fit in (endBeforeX-startX) pixels.
return getOffset() + textCount - 1;
}
@Override
public char[] getTextArray() {
return text;
}
@Override
public int getTextOffset() {
return textOffset;
}
@Override
public int getType() {
return type;
}
@Override
public float getWidth(RSyntaxTextArea textArea, TabExpander e, float x0) {
return getWidthUpTo(textCount, textArea, e, x0);
}
@Override
public float getWidthUpTo(int numChars, RSyntaxTextArea textArea, TabExpander e, float x0) {
float width = x0;
@@ -535,12 +516,12 @@ public class TokenImpl implements Token {
}
return width - x0;
}
@Override
public int hashCode() {
return offset + (getLexeme() == null ? 0 : getLexeme().hashCode());
}
@Override
public boolean is(char[] lexeme) {
if (textCount == lexeme.length) {
@@ -553,7 +534,7 @@ public class TokenImpl implements Token {
}
return false;
}
@Override
public boolean is(int type, char[] lexeme) {
if (this.getType() == type && textCount == lexeme.length) {
@@ -566,67 +547,67 @@ public class TokenImpl implements Token {
}
return false;
}
@Override
public boolean is(int type, String lexeme) {
return this.getType() == type && textCount == lexeme.length() && lexeme.equals(getLexeme());
}
@Override
public boolean isComment() {
return getType() >= Token.COMMENT_EOL && getType() <= Token.COMMENT_MARKUP;
}
@Override
public boolean isCommentOrWhitespace() {
return isComment() || isWhitespace();
}
@Override
public boolean isHyperlink() {
return hyperlink;
}
@Override
public boolean isIdentifier() {
return getType() == IDENTIFIER;
}
@Override
public boolean isLeftCurly() {
return getType() == SEPARATOR && isSingleChar('{');
}
@Override
public boolean isRightCurly() {
return getType() == SEPARATOR && isSingleChar('}');
}
@Override
public boolean isPaintable() {
return getType() > Token.NULL;
}
@Override
public boolean isSingleChar(char ch) {
return textCount == 1 && text[textOffset] == ch;
}
@Override
public boolean isSingleChar(int type, char ch) {
return this.getType() == type && isSingleChar(ch);
}
@Override
public boolean isWhitespace() {
return getType() == WHITESPACE;
}
@Override
public int length() {
return textCount;
}
@Override
public Rectangle listOffsetToView(RSyntaxTextArea textArea, TabExpander e, int pos, int x0, Rectangle rect) {
int stableX = x0; // Cached ending x-coord. of last tab or token.
@@ -678,49 +659,46 @@ public class TokenImpl implements Token {
rect.width = 1;
return rect;
}
/**
* Makes this token start at the specified offset into the document.
* <p>
*
* <b>Note:</b> You should not modify <code>Token</code> instances you
* did not create yourself (e.g., came from an
* <code>RSyntaxDocument</code>). If you do, rendering issues and/or
* runtime exceptions will likely occur. You have been warned!
* <b>Note:</b> You should not modify <code>Token</code> instances you did not
* create yourself (e.g., came from an <code>RSyntaxDocument</code>). If you do,
* rendering issues and/or runtime exceptions will likely occur. You have been
* warned!
*
* @param pos
* The offset into the document this token should start at.
* Note that this token must already contain this position; if
* it doesn't, an exception is thrown.
* @throws IllegalArgumentException
* If pos is not already contained by
* this token.
* @param pos The offset into the document this token should start at. Note that
* this token must already contain this position; if it doesn't, an
* exception is thrown.
* @throws IllegalArgumentException If pos is not already contained by this
* token.
* @see #moveOffset(int)
*/
public void makeStartAt(int pos) {
if (pos < getOffset() || pos >= (getOffset() + textCount)) {
throw new IllegalArgumentException("pos " + pos + " is not in range " + getOffset() + "-" + (getOffset() + textCount - 1));
throw new IllegalArgumentException(
"pos " + pos + " is not in range " + getOffset() + "-" + (getOffset() + textCount - 1));
}
int shift = pos - getOffset();
setOffset(pos);
textOffset += shift;
textCount -= shift;
}
/**
* Moves the starting offset of this token.
* <p>
*
* <b>Note:</b> You should not modify <code>Token</code> instances you
* did not create yourself (e.g., came from an
* <code>RSyntaxDocument</code>). If you do, rendering issues and/or
* runtime exceptions will likely occur. You have been warned!
* <b>Note:</b> You should not modify <code>Token</code> instances you did not
* create yourself (e.g., came from an <code>RSyntaxDocument</code>). If you do,
* rendering issues and/or runtime exceptions will likely occur. You have been
* warned!
*
* @param amt
* The amount to move the starting offset. This should be
* between <code>0</code> and <code>textCount</code>, inclusive.
* @throws IllegalArgumentException
* If <code>amt</code> is an invalid value.
* @param amt The amount to move the starting offset. This should be between
* <code>0</code> and <code>textCount</code>, inclusive.
* @throws IllegalArgumentException If <code>amt</code> is an invalid value.
* @see #makeStartAt(int)
*/
public void moveOffset(int amt) {
@@ -731,21 +709,16 @@ public class TokenImpl implements Token {
textOffset += amt;
textCount -= amt;
}
/**
* Sets the value of this token to a particular segment of a document.
* The "next token" value is cleared.
* Sets the value of this token to a particular segment of a document. The "next
* token" value is cleared.
*
* @param line
* The segment from which to get the token.
* @param beg
* The first character's position in <code>line</code>.
* @param end
* The last character's position in <code>line</code>.
* @param offset
* The offset into the document at which this token begins.
* @param type
* A token type listed as "generic" above.
* @param line The segment from which to get the token.
* @param beg The first character's position in <code>line</code>.
* @param end The last character's position in <code>line</code>.
* @param offset The offset into the document at which this token begins.
* @param type A token type listed as "generic" above.
*/
public void set(final char[] line, final int beg, final int end, final int offset, final int type) {
this.text = line;
@@ -755,61 +728,56 @@ public class TokenImpl implements Token {
this.setOffset(offset);
nextToken = null;
}
/**
* Sets whether this token is a hyperlink.
*
* @param hyperlink
* Whether this token is a hyperlink.
* @param hyperlink Whether this token is a hyperlink.
* @see #isHyperlink()
*/
@Override
public void setHyperlink(boolean hyperlink) {
this.hyperlink = hyperlink;
}
/**
* Sets the language index for this token. If this value is positive, it
* denotes a specific "secondary" language this token represents (such as
* JavaScript code or CSS embedded in an HTML file). If this value is
* <code>0</code>, this token is in the "main" language being edited.
* Negative values are invalid and treated as <code>0</code>.
* Sets the language index for this token. If this value is positive, it denotes
* a specific "secondary" language this token represents (such as JavaScript
* code or CSS embedded in an HTML file). If this value is <code>0</code>, this
* token is in the "main" language being edited. Negative values are invalid and
* treated as <code>0</code>.
*
* @param languageIndex
* The new language index. A value of
* <code>0</code> denotes the "main" language, any positive value
* denotes a specific secondary language. Negative values will
* be treated as <code>0</code>.
* @param languageIndex The new language index. A value of <code>0</code>
* denotes the "main" language, any positive value denotes
* a specific secondary language. Negative values will be
* treated as <code>0</code>.
* @see #getLanguageIndex()
*/
@Override
public void setLanguageIndex(int languageIndex) {
this.languageIndex = languageIndex;
}
/**
* Sets the "next token" pointer of this token to point to the specified
* token.
* Sets the "next token" pointer of this token to point to the specified token.
*
* @param nextToken
* The new next token.
* @param nextToken The new next token.
* @see #getNextToken()
*/
public void setNextToken(Token nextToken) {
this.nextToken = nextToken;
}
/**
* Sets the offset into the document at which this token resides.
*
* @param offset
* The new offset into the document.
* @param offset The new offset into the document.
* @see #getOffset()
*/
public void setOffset(int offset) {
this.offset = offset;
}
/**
* {@inheritDoc}
*/
@@ -817,7 +785,7 @@ public class TokenImpl implements Token {
public void setType(int type) {
this.type = type;
}
/**
* {@inheritDoc}
*/
@@ -833,7 +801,7 @@ public class TokenImpl implements Token {
}
return false;
}
/**
* {@inheritDoc}
*/
@@ -841,18 +809,20 @@ public class TokenImpl implements Token {
public int tokenToDocument(int pos) {
return pos + (getOffset() - textOffset);
}
/**
* Returns this token as a <code>String</code>, which is useful for
* debugging.
* Returns this token as a <code>String</code>, which is useful for debugging.
*
* @return A string describing this token.
*/
@Override
public String toString() {
return "[Token: " + (getType() == Token.NULL ? "<null token>"
: "text: '" + (text == null ? "<null>" : getLexeme() + "'; " + "offset: " + getOffset() + "; type: " + getType() + "; "
+ "isPaintable: " + isPaintable() + "; nextToken==null: " + (nextToken == null)))
return "[Token: "
+ (getType() == Token.NULL ? "<null token>"
: "text: '" + (text == null ? "<null>"
: getLexeme() + "'; " + "offset: " + getOffset() + "; type: " + getType() + "; "
+ "isPaintable: " + isPaintable() + "; nextToken==null: "
+ (nextToken == null)))
+ "]";
}
}
+57 -67
View File
@@ -9,12 +9,13 @@ import javax.swing.text.TabExpander;
* @version 1.0
*/
public final class TokenUtils {
private TokenUtils() {}
private TokenUtils() {
}
/**
* Modifies the passed-in token list to start at the specified offset.
* For example, if the token list covered positions 20-60 in the document
* Modifies the passed-in token list to start at the specified offset. For
* example, if the token list covered positions 20-60 in the document
* (inclusive) like so:
*
* <pre>
@@ -22,50 +23,46 @@ public final class TokenUtils {
* 20 30 31 40 41 50 51 60
* </pre>
*
* and you used this method to make the token list start at position 44,
* then the token list would be modified to be the following:
* and you used this method to make the token list start at position 44, then
* the token list would be modified to be the following:
*
* <pre>
* [part-of-old-token3] -&gt; [token4]
* 44 50 51 60
* </pre>
*
* Tokens that come before the specified position are forever lost, and
* the token containing that position is made to begin at that position if
* Tokens that come before the specified position are forever lost, and the
* token containing that position is made to begin at that position if
* necessary. All token types remain the same as they were originally.
* <p>
*
* This method can be useful if you are only interested in part of a token
* list (i.e., the line it represents), but you don't want to modify the
* token list yourself.
* This method can be useful if you are only interested in part of a token list
* (i.e., the line it represents), but you don't want to modify the token list
* yourself.
*
* @param tokenList
* The list to make start at the specified position.
* This parameter is modified.
* @param pos
* The position at which the new token list is to start. If
* this position is not in the passed-in token list,
* returned token list will either be <code>null</code> or the
* unpaintable token(s) at the end of the passed-in token list.
* @param e
* How to expand tabs.
* @param textArea
* The text area from which the token list came.
* @param x0
* The initial x-pixel position of the old token list.
* @param tokenList The list to make start at the specified position. This
* parameter is modified.
* @param pos The position at which the new token list is to start. If
* this position is not in the passed-in token list, returned
* token list will either be <code>null</code> or the
* unpaintable token(s) at the end of the passed-in token list.
* @param e How to expand tabs.
* @param textArea The text area from which the token list came.
* @param x0 The initial x-pixel position of the old token list.
* @return Information about the "sub" token list. This will be
* <code>null</code> if <code>pos</code> was not a valid offset
* into the token list.
* <code>null</code> if <code>pos</code> was not a valid offset into the
* token list.
* @see #getSubTokenList(Token, int, TabExpander, RSyntaxTextArea, float,
* TokenImpl)
*/
public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea, float x0) {
public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea,
float x0) {
return getSubTokenList(tokenList, pos, e, textArea, x0, null);
}
/**
* Modifies the passed-in token list to start at the specified offset.
* For example, if the token list covered positions 20-60 in the document
* Modifies the passed-in token list to start at the specified offset. For
* example, if the token list covered positions 20-60 in the document
* (inclusive) like so:
*
* <pre>
@@ -73,48 +70,42 @@ public final class TokenUtils {
* 20 30 31 40 41 50 51 60
* </pre>
*
* and you used this method to make the token list start at position 44,
* then the token list would be modified to be the following:
* and you used this method to make the token list start at position 44, then
* the token list would be modified to be the following:
*
* <pre>
* [part-of-old-token3] -&gt; [token4]
* 44 50 51 60
* </pre>
*
* Tokens that come before the specified position are forever lost, and
* the token containing that position is made to begin at that position if
* Tokens that come before the specified position are forever lost, and the
* token containing that position is made to begin at that position if
* necessary. All token types remain the same as they were originally.
* <p>
*
* This method can be useful if you are only interested in part of a token
* list (i.e., the line it represents), but you don't want to modify the
* token list yourself.
* This method can be useful if you are only interested in part of a token list
* (i.e., the line it represents), but you don't want to modify the token list
* yourself.
*
* @param tokenList
* The list to make start at the specified position.
* This parameter is modified.
* @param pos
* The position at which the new token list is to start. If
* this position is not in the passed-in token list,
* returned token list will either be <code>null</code> or the
* unpaintable token(s) at the end of the passed-in token list.
* @param e
* How to expand tabs.
* @param textArea
* The text area from which the token list came.
* @param x0
* The initial x-pixel position of the old token list.
* @param tempToken
* A temporary token to use when creating the token list
* result. This may be <code>null</code> but callers can pass in
* a "buffer" token for performance if desired.
* @param tokenList The list to make start at the specified position. This
* parameter is modified.
* @param pos The position at which the new token list is to start. If
* this position is not in the passed-in token list, returned
* token list will either be <code>null</code> or the
* unpaintable token(s) at the end of the passed-in token list.
* @param e How to expand tabs.
* @param textArea The text area from which the token list came.
* @param x0 The initial x-pixel position of the old token list.
* @param tempToken A temporary token to use when creating the token list
* result. This may be <code>null</code> but callers can pass
* in a "buffer" token for performance if desired.
* @return Information about the "sub" token list. This will be
* <code>null</code> if <code>pos</code> was not a valid offset
* into the token list.
* <code>null</code> if <code>pos</code> was not a valid offset into the
* token list.
* @see #getSubTokenList(Token, int, TabExpander, RSyntaxTextArea, float)
*/
public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea, float x0,
TokenImpl tempToken) {
public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea,
float x0, TokenImpl tempToken) {
if (tempToken == null) {
tempToken = new TokenImpl();
}
@@ -142,23 +133,22 @@ public final class TokenUtils {
return new TokenSubList(tokenList, x0);
// return null;
}
/**
* A sub-list of tokens.
*/
@SuppressWarnings({ "checkstyle:visibilitymodifier" })
public static class TokenSubList {
/**
* The "sub" token list.
*/
public Token tokenList;
/**
* The width, in pixels, of the part of the token list "removed from
* the front." This way, you know the x-offset of the "new" token list.
* The width, in pixels, of the part of the token list "removed from the front."
* This way, you know the x-offset of the "new" token list.
*/
public float x;
public TokenSubList(Token tokenList, float x) {
this.tokenList = tokenList;
this.x = x;
@@ -34,34 +34,32 @@ import javax.swing.event.MouseInputAdapter;
* @author Robert Futrell
* @version 1.0
*/
@SuppressWarnings({ "checkstyle:magicnumber" })
class SizeGrip extends JPanel {
/**
* The size grip to use if we're on OS X.
*/
private transient Image osxSizeGrip;
SizeGrip() {
MouseHandler adapter = new MouseHandler();
addMouseListener(adapter);
addMouseMotionListener(adapter);
setPreferredSize(new Dimension(16, 16));
}
/**
* Overridden to ensure that the cursor for this component is appropriate
* for the orientation.
* Overridden to ensure that the cursor for this component is appropriate for
* the orientation.
*
* @param o
* The new orientation.
* @param o The new orientation.
*/
@Override
public void applyComponentOrientation(ComponentOrientation o) {
possiblyFixCursor(o.isLeftToRight());
super.applyComponentOrientation(o);
}
/**
* Creates and returns the OS X size grip image.
*
@@ -93,12 +91,11 @@ class SizeGrip extends JPanel {
}
return image;
}
/**
* Paints this panel.
*
* @param g
* The graphics context.
* @param g The graphics context.
*/
@Override
protected void paintComponent(Graphics g) {
@@ -146,13 +143,12 @@ class SizeGrip extends JPanel {
g.fillRect(2, height - 9, 2, 2);
}
}
/**
* Ensures that the cursor for this component is appropriate for the
* orientation.
*
* @param ltr
* Whether the current component orientation is LTR.
* @param ltr Whether the current component orientation is LTR.
*/
protected void possiblyFixCursor(boolean ltr) {
int cursor = Cursor.NE_RESIZE_CURSOR;
@@ -163,7 +159,7 @@ class SizeGrip extends JPanel {
setCursor(Cursor.getPredefinedCursor(cursor));
}
}
@Override
public void updateUI() {
super.updateUI();
@@ -177,23 +173,21 @@ class SizeGrip extends JPanel {
osxSizeGrip = null;
}
}
/**
* Listens for mouse events on this panel and resizes the parent window
* appropriately.
*/
private class MouseHandler extends MouseInputAdapter {
/*
* NOTE: We use SwingUtilities.convertPointToScreen() instead of just
* using
* the locations relative to the corner component because the latter
* proved
* buggy - stretch the window too wide and some kind of arithmetic error
* started happening somewhere - our window would grow way too large.
* NOTE: We use SwingUtilities.convertPointToScreen() instead of just using the
* locations relative to the corner component because the latter proved buggy -
* stretch the window too wide and some kind of arithmetic error started
* happening somewhere - our window would grow way too large.
*/
private Point origPos;
@Override
public void mouseDragged(MouseEvent e) {
Point newPos = e.getPoint();
@@ -223,13 +217,13 @@ class SizeGrip extends JPanel {
}
origPos.setLocation(newPos);
}
@Override
public void mousePressed(MouseEvent e) {
origPos = e.getPoint();
SwingUtilities.convertPointToScreen(origPos, SizeGrip.this);
}
@Override
public void mouseReleased(MouseEvent e) {
origPos = null;