Skip to content

Instantly share code, notes, and snippets.

@fmjrey
Created April 20, 2011 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmjrey/931936 to your computer and use it in GitHub Desktop.
Save fmjrey/931936 to your computer and use it in GitHub Desktop.
Groovy Monkey script that opens Eclipse color picker
/*
* Menu: Color Picker
* Script-Path: /GroovyMonkeyScripts/monkey/Color_Picker.gm
* Kudos: fmjrey
* License: LGPL
* Job: UIJob
* DOM: http://groovy-monkey.sourceforge.net/update/plugins/net.sf.groovyMonkey.dom
*/
/*
* Color Picker script
* ===================
* https://gist.github.com/931936
* To use this script you must install first the Groovy Monkey plugin v0.6.1 or later.
* You can get it at http://groovy.codehaus.org/Groovy+Monkey
* Once installed a new menu Groovy Monkey is shown.
* Use the examples option of this new menu to download the examples
* and create a GroovyMonkeyScripts project.
* Then use the Create New Script option, name the menu "Color Picker" and paste this
* script into the new file.
* Usage:
* Just run the script from the Groovy Monkey menu, or Crtl+Alt+M to run the last script.
* If the currently selected text is recognized as an html color it will be
* selected in the color picker window.
* The selected color will be inserted at the cursor position, possibly replacing current
* selection.
* Enjoy!
*/
import java.awt.Color
import org.eclipse.swt.graphics.RGB
import org.eclipse.jface.text.ITextSelection
import org.eclipse.swt.custom.StyledText
import org.eclipse.swt.widgets.Control
import org.eclipse.ui.texteditor.ITextEditor
import org.eclipse.swt.widgets.ColorDialog
def String color2String(Color c) {
String r = (c.getRed() < 16) ? "0" + Integer.toHexString(c.getRed()) : Integer.toHexString(c.getRed());
String g = (c.getGreen() < 16) ? "0" + Integer.toHexString(c.getGreen()) : Integer.toHexString(c.getGreen());
String b = (c.getBlue() < 16) ? "0" + Integer.toHexString(c.getBlue()) : Integer.toHexString(c.getBlue());
return "#" + r + g + b;
}
def Color string2Color(String s) {
result = null;
try {
result = parse(s)
} catch (Throwable t) {
//out.println "Error parsing selectedText: ${t.getMessage()}"
}
return result
}
def String rgb2String(RGB rgb) {
StringBuffer sb = new StringBuffer('#')
sb.append((rgb.red < 16) ? "0" + Integer.toHexString(rgb.red) : Integer.toHexString(rgb.red))
sb.append((rgb.green < 16) ? "0" + Integer.toHexString(rgb.green) : Integer.toHexString(rgb.green))
sb.append((rgb.blue < 16) ? "0" + Integer.toHexString(rgb.blue) : Integer.toHexString(rgb.blue))
return sb.toString();
}
editor = window.getActivePage()?.getActiveEditor()?.getAdapter(ITextEditor.class)
if (!editor) return
selection = editor?.getSelectionProvider()?.getSelection()
if (selection != null && !(selection instanceof ITextSelection)) return
selectedText = selection ? selection.getText() : null
//out.println "Selected text = ${selectedText}"
selectedColor = string2Color(selectedText)
selectedRGB = selectedColor ? new RGB(selectedColor.getRed(),selectedColor.getGreen(), selectedColor.getBlue()) : null
dialog = new ColorDialog(window.getShell())
if (selectedRGB) {
dialog.setRGB(selectedRGB)
}
newRGB = dialog.open()
if (newRGB && !newRGB.equals(selectedRGB)) {
newColorString = rgb2String(newRGB);
if (selectedText) {
// replace
document = editor.getDocumentProvider()?.getDocument(editor.getEditorInput());
if (!document) return
document.replace(selection.getOffset(), selection.getLength(), newColorString);
editor.selectAndReveal(selection.getOffset(), newColorString.length());
} else {
// insert
document = editor.getDocumentProvider()?.getDocument(editor.getEditorInput());
if (!document) return
StyledText styledText = (StyledText) editor.getAdapter(Control.class);
int offset = styledText.getCaretOffset();
document.replace(offset, 0, newColorString);
}
}
/******************************************************************************
* CODE BELOW COPIED FROM
* http://jsap.cvs.sourceforge.net/viewvc/jsap/JSAP/src/java/com/martiansoftware/jsap/stringparsers/ColorStringParser.java?view=markup
* The only difference is that ParseException has been replaced with Exception.
*/
/*
* Simple utility for creating ParseExceptions, as there are so many
* opportunities to throw them.
* @param s the ParseException's message.
* @return a new ParseException with the specified message.
*/
private Exception colorException(String s) {
return (
new Exception("Unable to convert '" + s + "' to a Color."));
}
/*
* Parses a hexadecimal String into a Color.
* @param hexString the hexadecimal String to parse.
* @return a Color object based upon the specified color string.
* @throws ParseException if the specified String cannot be interpreted as
* a Color.
*/
private Color parseHexColor(String hexString) throws Exception {
Color result = null;
int hexLength = hexString.length();
if ((hexLength != 7) && (hexLength != 9)) {
throw (colorException(hexString));
}
try {
int red = Integer.parseInt(hexString.substring(1, 3), 16);
int green = Integer.parseInt(hexString.substring(3, 5), 16);
int blue = Integer.parseInt(hexString.substring(5, 7), 16);
if (hexLength == 7) {
result = new Color(red, green, blue);
} else {
int alpha = Integer.parseInt(hexString.substring(7, 9), 16);
result = new Color(red, green, blue, alpha);
}
} catch (NumberFormatException e) {
throw (colorException(hexString));
}
return (result);
}
/*
* Parses a 3- or 4-tuple of comma-separated floats into a Color.
* @param floatString the String to parse.
* @return a Color object based upon the specified String.
* @throws ParseException if the specified String cannot be interpreted as
* a Color.
*/
private Color parseFloatTuple(String floatString) throws Exception {
String[] tuple = tupleToArray(floatString);
Color result = null;
try {
float red = Float.parseFloat(tuple[0]);
float green = Float.parseFloat(tuple[1]);
float blue = Float.parseFloat(tuple[2]);
if (tuple.length == 3) {
result = new Color(red, green, blue);
} else {
float alpha = Float.parseFloat(tuple[3]);
result = new Color(red, green, blue, alpha);
}
} catch (NumberFormatException e) {
throw (colorException(floatString));
}
return (result);
}
/*
* Parses a 3- or 4-tuple of comma-separated integers into a Color.
* @param intString the String to parse.
* @return a Color object based upon the specified color String.
* @throws ParseException if the specified String cannot be interpreted as
* a Color.
*/
private Color parseIntTuple(String intString) throws Exception {
String[] tuple = tupleToArray(intString);
Color result = null;
try {
int red = Integer.parseInt(tuple[0]);
int green = Integer.parseInt(tuple[1]);
int blue = Integer.parseInt(tuple[2]);
if (tuple.length == 3) {
result = new Color(red, green, blue);
} else {
int alpha = Integer.parseInt(tuple[3]);
result = new Color(red, green, blue, alpha);
}
} catch (NumberFormatException e) {
throw (colorException(intString));
}
return (result);
}
/*
* Parses a String into a Color by name (names lifted from java.awt.Color).
* @param colorName the name of the desired Color.
* @return a Color object based upon the specified color name.
* @throws ParseException if the specified String is not a valid color name.
*/
private Color parseColorName(String colorName) throws Exception {
Color result = null;
if (colorName.equalsIgnoreCase("black")) {
result = Color.black;
} else if (colorName.equalsIgnoreCase("blue")) {
result = Color.blue;
} else if (colorName.equalsIgnoreCase("cyan")) {
result = Color.cyan;
} else if (colorName.equalsIgnoreCase("gray")) {
result = Color.gray;
} else if (colorName.equalsIgnoreCase("green")) {
result = Color.green;
} else if (colorName.equalsIgnoreCase("lightGray")) {
result = Color.lightGray;
} else if (colorName.equalsIgnoreCase("magenta")) {
result = Color.magenta;
} else if (colorName.equalsIgnoreCase("orange")) {
result = Color.orange;
} else if (colorName.equalsIgnoreCase("pink")) {
result = Color.pink;
} else if (colorName.equalsIgnoreCase("red")) {
result = Color.red;
} else if (colorName.equalsIgnoreCase("white")) {
result = Color.white;
} else if (colorName.equalsIgnoreCase("yellow")) {
result = Color.yellow;
} else {
throw (colorException(colorName));
}
return (result);
}
/*
* Parses a 3- or 4-tuple, comma separated, to an array.
* @param s the String to be parsed to an array.
* @return the parsed String as a 3- or 4-element array of Strings.
* @throws ParseException if the specified String contains fewer than 3 or
* more than 4 elements.
*/
private String[] tupleToArray(String s) throws Exception {
String[] result = null;
StringTokenizer tokenizer = new StringTokenizer(s, ",", true);
int tokenCount = tokenizer.countTokens();
if (tokenCount == 5) {
result = new String[3];
} else if (tokenCount == 7) {
result = new String[4];
} else {
throw (colorException(s));
}
result[0] = tokenizer.nextToken();
tokenizer.nextToken();
result[1] = tokenizer.nextToken();
tokenizer.nextToken();
result[2] = tokenizer.nextToken();
if (tokenCount == 7) {
tokenizer.nextToken();
result[3] = tokenizer.nextToken();
}
return (result);
}
/*
* Parses java.awt.Color objects from Strings. Color information can be
* specified in a variety
* of formats:
*
* <ul>
* <li>RGB, as integers in the range 0-255, separated by commas
* (e.g., "123,45,6")</li>
* <li>RGB, as floats in the range 0.0-1.0, separated by commas
* (e.g., "0.123,0.45,0.6")</li>
* <li>RGB, as hexadecimal strings following the '#' character
* (e.g., "#1234ef")</li>
* <li>By name, as matching the names of the color fields of java.awt.Color
* (case-insensitive).
* (e.g., "black")</li>
* <li>RGBAlpha, as integers in the range 0-255, separated by commas
* (e.g., "123,45,6,128")</li>
* <li>RGBAlpha, as floats in the range 0.0-1.0, separated by commas
* (e.g., "0.123,0.45,0.6,.5")</li>
* <li>RGBAlpha, as hexadecimal strings following the '#' character
* (e.g., "#1234efab")</li>
* </ul>
*
* If the specified argument does not match any of these formats, a
* ParseException is thrown.
* @param arg the String to convert to a Color object.
* @return the Color specified by arg.
* @throws ParseException if arg cannot be interpreted as a Color as
* described above.
*/
public Object parse(String arg) throws Exception {
Color result = null;
if (arg.charAt(0) == '#') {
result = parseHexColor(arg);
} else if (arg.indexOf(".") >= 0) {
result = parseFloatTuple(arg);
} else if (arg.indexOf(",") >= 0) {
result = parseIntTuple(arg);
} else {
result = parseColorName(arg);
}
return (result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment