Make first real commit: copy of CaRMetal 4.2.8

This commit is contained in:
Glen Whitney 2018-09-04 22:51:42 -04:00
parent 002acfc88e
commit c312811084
1120 changed files with 226843 additions and 1 deletions

View file

@ -0,0 +1,337 @@
# Sun Public License Notice
#
# The contents of this file are subject to the Sun Public License
# Version 1.0 (the "License"). You may not use this file except in
# compliance with the License. A copy of the License is available at
# http://www.sun.com/
#
# The Original Code is NetBeans. The Initial Developer of the Original
# Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
# Microsystems, Inc. All Rights Reserved.
#Palette names
basic=Primary colors
svg=SVG/X11 color constants
swing=Swing constants
system=System colors
recent=Recent colors
tip=Click and hold combinations of Ctrl/Shift/Alt to switch palettes
tip.mac=Click and hold combinations of Command/Shift/Alt to switch palettes
#SVG/X11 Color constants
# 240,248,255
aliceblue=Alice blue
# 250,235,215
antiquewhite=Antique white
# 0,255,255
aqua=Aqua
# 127,255,212
aquamarine=Aquamarine
# 240,255,255
azure=Azure
# 245,245,220
beige=Beige
# 255,228,196
bisque=Bisque
# 0,0,0
black=Black
# 255,235,205
blanchedalmond=Blanched almond
# 0,0,255
blue=Blue
# 138,43,226
blueviolet=Blue violet
# 165,42,42
brown=Brown
# 222,184,135
burlywood=Burly wood
# 95,158,160
cadetblue=Cadet blue
# 127,255,0
chartreuse=Chartreuse
# 210,105,30
chocolate=Chocolate
# 255,127,80
coral=Coral
# 100,149,237
cornflowerblue=Cornflower blue
# 255,248,220
cornsilk=Corn silk
# 220,20,60
crimson=Crimson
# 0,255,255
cyan=Cyan
# 0,0,139
darkblue=Dark blue
# 0,139,139
darkcyan=Dark cyan
# 184,134,11
darkgoldenrod=Dark goldenrod
# 169,169,169
darkgray=Dark gray
# 0,100,0
darkgreen=Dark green
# 169,169,169
darkgrey=Dark grey
# 189,183,107
darkkhaki=Dark khaki
# 139,0,139
darkmagenta=Dark magenta
# 85,107,47
darkolivegreen=Dark olive green
# 255,140,0
darkorange=Dark orange
# 153,50,204
darkorchid=Dark orchid
# 139,0,0
darkred=Dark red
# 233,150,122
darksalmon=Dark salmon
# 143,188,143
darkseagreen=Dark sea green
# 72,61,139
darkslateblue=Dark slate blue
# 47,79,79
darkslategray=Dark slate gray
# 47,79,79
darkslategrey=Dark slate grey
# 0,206,209
darkturquoise=Dark turquoise
# 148,0,211
darkviolet=Dark violet
# 255,20,147
deeppink=Deep pink
# 0,191,255
deepskyblue=Deep sky blue
# 105,105,105
dimgray=Dim gray
# 105,105,105
dimgrey=Dim grey
# 30,144,255
dodgerblue=Dodger blue
# 178,34,34
firebrick=Fire brick
# 255,250,240
floralwhite=Floral white
# 34,139,34
forestgreen=Forest green
# 255,0,255
fuchsia=Fuchsia
# 220,220,220
gainsboro=Gainsboro
# 248,248,255
ghostwhite=Ghost white
# 255,215,0
gold=Gold
# 218,165,32
goldenrod=Goldenrod
# 128,128,128
gray=Gray
# 128,128,128
grey=Grey
# 0,128,0
green=Green
# 173,255,47
greenyellow=Green yellow
# 240,255,240
honeydew=Honeydew
# 255,105,180
hotpink=Hot pink
# 205,92,92
indianred=Indian red
# 75,0,130
indigo=Indigo
# 255,255,240
ivory=Ivory
# 240,230,140
khaki=Khaki
# 230,230,250
lavender=Lavender
# 255,240,245
lavenderblush=Lavender blush
# 124,252,0
lawngreen=Lawn green
# 255,250,205
lemonchiffon=Lemon chiffon
# 173,216,230
lightblue=Light blue
# 240,128,128
lightcoral=Light coral
# 224,255,255
lightcyan=Light cyan
# 250,250,210
lightgoldenrodyellow=Light goldenrod yellow
# 211,211,211
lightgray=Light gray
# 144,238,144
lightgreen=Light green
# 211,211,211
lightgrey=Light grey
# 255,182,193
lightpink=Light pink
# 255,160,122
lightsalmon=Light salmon
# 32,178,170
lightseagreen=Light sea green
# 135,206,250
lightskyblue=Light sky blue
# 119,136,153
lightslategray=Light slate gray
# 119,136,153
lightslategrey=Light slate grey
# 176,196,222
lightsteelblue=Light steel blue
# 255,255,224
lightyellow=Light yellow
# 0,255,0
lime=Lime
# 50,205,50
limegreen=Lime green
# 250,240,230
linen=Linen
# 255,0,255
magenta=Magenta
# 128,0,0
maroon=Maroon
# 102,205,170
mediumaquamarine=Medium aquamarine
# 0,0,205
mediumblue=Medium blue
# 186,85,211
mediumorchid=Medium orchid
# 147,112,219
mediumpurple=Medium purple
# 60,179,113
mediumseagreen=Medium sea green
# 123,104,238
mediumslateblue=Medium slate blue
# 0,250,154
mediumspringgreen=Medium spring green
# 72,209,204
mediumturquoise=Medium turquoise
# 199,21,133
mediumvioletred=Medium violet red
# 25,25,112
midnightblue=Midnight blue
# 245,255,250
mintcream=Mint cream
# 255,228,225
mistyrose=Misty rose
# 255,228,181
moccasin=Moccasin
# 255,222,173
navajowhite=Navajo white
# 0,0,128
navy=Navy
# 253,245,230
oldlace=Old lace
# 128,128,0
olive=Olive
# 107,142,35
olivedrab=Olivedrab
# 255,165,0
orange=Orange
# 255,69,0
orangered=Orange red
# 218,112,214
orchid=Orchid
# 238,232,170
palegoldenrod=Pale goldenrod
# 152,251,152
palegreen=Pale green
# 175,238,238
paleturquoise=Pale turquoise
# 219,112,147
palevioletred=Pale violet red
# 255,239,213
papayawhip=Papaya whip
# 255,218,185
peachpuff=Peach puff
# 205,133,63
peru=Peru
# 255,192,203
pink=Pink
# 221,160,221
plum=Plum
# 176,224,230
powderblue=Powder blue
# 128,0,128
purple=Purple
# 255,0,0
red=Red
# 188,143,143
rosybrown=Rosy brown
# 65,105,225
royalblue=Royal blue
# 139,69,19
saddlebrown=Saddle brown
# 250,128,114
salmon=Salmon
# 244,164,96
sandybrown=Sandy brown
# 46,139,87
seagreen=Sea green
# 255,245,238
seashell=Seashell
# 160,82,45
sienna=Sienna
# 192,192,192
silver=Silver
# 135,206,235
skyblue=Sky blue
# 106,90,205
slateblue=Slate blue
# 112,128,144
slategray=Slate gray
# 112,128,144
slategrey=Slate grey
# 255,250,250
snow=Snow
# 0,255,127
springgreen=Spring green
# 70,130,180
steelblue=Steel blue
# 210,180,140
tan=Tan
# 0,128,128
teal=Teal
# 216,191,216
thistle=Thistle
# 255,99,71
tomato=Tomato
# 64,224,208
turquoise=Turquoise
# 238,130,238
violet=Violet
# 245,222,179
wheat=Wheat
# 255,255,255
white=White
# 245,245,245
whitesmoke=White smoke
# 255,255,0
yellow=Yellow
# 154,205,50
yellowgreen=Yellow green
# Continuous palette names
satSmall=Saturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 1f, false),
unsatSmall=Desaturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 0.4f, false),
satSmallHoriz=Saturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 1f, true),
unsatSmallHoriz=Desaturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 0.4f, true),
satLarge=Saturated colors
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 1f, false),
unsatLarge=Desaturated colors
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 0.4f, false),
satLargeHoriz=Saturated colors
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 1f, true),
unsatLargeHoriz=Desaturated colors
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 0.4f, true)
chooseColor="Choose a Color"

View file

@ -0,0 +1,333 @@
# Sun Public License Notice
#
# The contents of this file are subject to the Sun Public License
# Version 1.0 (the "License"). You may not use this file except in
# compliance with the License. A copy of the License is available at
# http://www.sun.com/
#
# The Original Code is NetBeans. The Initial Developer of the Original
# Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
# Microsystems, Inc. All Rights Reserved.
#Palette names
basic=Primary colors
svg=SVG/X11 color constants
swing=Swing constants
system=System colors
recent=Recent colors
#SVG/X11 Color constants
# 240,248,255
aliceblue=Alice blue
# 250,235,215
antiquewhite=Antique white
# 0,255,255
aqua=Aqua
# 127,255,212
aquamarine=Aquamarine
# 240,255,255
azure=Azure
# 245,245,220
beige=Beige
# 255,228,196
bisque=Bisque
# 0,0,0
black=Black
# 255,235,205
blanchedalmond=Blanched almond
# 0,0,255
blue=Blue
# 138,43,226
blueviolet=Blue violet
# 165,42,42
brown=Brown
# 222,184,135
burlywood=Burly wood
# 95,158,160
cadetblue=Cadet blue
# 127,255,0
chartreuse=Chartreuse
# 210,105,30
chocolate=Chocolate
# 255,127,80
coral=Coral
# 100,149,237
cornflowerblue=Cornflower blue
# 255,248,220
cornsilk=Corn silk
# 220,20,60
crimson=Crimson
# 0,255,255
cyan=Cyan
# 0,0,139
darkblue=Dark blue
# 0,139,139
darkcyan=Dark cyan
# 184,134,11
darkgoldenrod=Dark goldenrod
# 169,169,169
darkgray=Dark gray
# 0,100,0
darkgreen=Dark green
# 169,169,169
darkgrey=Dark grey
# 189,183,107
darkkhaki=Dark khaki
# 139,0,139
darkmagenta=Dark magenta
# 85,107,47
darkolivegreen=Dark olive green
# 255,140,0
darkorange=Dark orange
# 153,50,204
darkorchid=Dark orchid
# 139,0,0
darkred=Dark red
# 233,150,122
darksalmon=Dark salmon
# 143,188,143
darkseagreen=Dark sea green
# 72,61,139
darkslateblue=Dark slate blue
# 47,79,79
darkslategray=Dark slate gray
# 47,79,79
darkslategrey=Dark slate grey
# 0,206,209
darkturquoise=Dark turquoise
# 148,0,211
darkviolet=Dark violet
# 255,20,147
deeppink=Deep pink
# 0,191,255
deepskyblue=Deep sky blue
# 105,105,105
dimgray=Dim gray
# 105,105,105
dimgrey=Dim grey
# 30,144,255
dodgerblue=Dodger blue
# 178,34,34
firebrick=Fire brick
# 255,250,240
floralwhite=Floral white
# 34,139,34
forestgreen=Forest green
# 255,0,255
fuchsia=Fuchsia
# 220,220,220
gainsboro=Gainsboro
# 248,248,255
ghostwhite=Ghost white
# 255,215,0
gold=Gold
# 218,165,32
goldenrod=Goldenrod
# 128,128,128
gray=Gray
# 128,128,128
grey=Grey
# 0,128,0
green=Green
# 173,255,47
greenyellow=Green yellow
# 240,255,240
honeydew=Honeydew
# 255,105,180
hotpink=Hot pink
# 205,92,92
indianred=Indian red
# 75,0,130
indigo=Indigo
# 255,255,240
ivory=Ivory
# 240,230,140
khaki=Khaki
# 230,230,250
lavender=Lavender
# 255,240,245
lavenderblush=Lavender blush
# 124,252,0
lawngreen=Lawn green
# 255,250,205
lemonchiffon=Lemon chiffon
# 173,216,230
lightblue=Light blue
# 240,128,128
lightcoral=Light coral
# 224,255,255
lightcyan=Light cyan
# 250,250,210
lightgoldenrodyellow=Light goldenrod yellow
# 211,211,211
lightgray=Light gray
# 144,238,144
lightgreen=Light green
# 211,211,211
lightgrey=Light grey
# 255,182,193
lightpink=Light pink
# 255,160,122
lightsalmon=Light salmon
# 32,178,170
lightseagreen=Light sea green
# 135,206,250
lightskyblue=Light sky blue
# 119,136,153
lightslategray=Light slate gray
# 119,136,153
lightslategrey=Light slate grey
# 176,196,222
lightsteelblue=Light steel blue
# 255,255,224
lightyellow=Light yellow
# 0,255,0
lime=Lime
# 50,205,50
limegreen=Lime green
# 250,240,230
linen=Linen
# 255,0,255
magenta=Magenta
# 128,0,0
maroon=Maroon
# 102,205,170
mediumaquamarine=Medium aquamarine
# 0,0,205
mediumblue=Medium blue
# 186,85,211
mediumorchid=Medium orchid
# 147,112,219
mediumpurple=Medium purple
# 60,179,113
mediumseagreen=Medium sea green
# 123,104,238
mediumslateblue=Medium slate blue
# 0,250,154
mediumspringgreen=Medium spring green
# 72,209,204
mediumturquoise=Medium turquoise
# 199,21,133
mediumvioletred=Medium violet red
# 25,25,112
midnightblue=Midnight blue
# 245,255,250
mintcream=Mint cream
# 255,228,225
mistyrose=Misty rose
# 255,228,181
moccasin=Moccasin
# 255,222,173
navajowhite=Navajo white
# 0,0,128
navy=Navy
# 253,245,230
oldlace=Old lace
# 128,128,0
olive=Olive
# 107,142,35
olivedrab=Olivedrab
# 255,165,0
orange=Orange
# 255,69,0
orangered=Orange red
# 218,112,214
orchid=Orchid
# 238,232,170
palegoldenrod=Pale goldenrod
# 152,251,152
palegreen=Pale green
# 175,238,238
paleturquoise=Pale turquoise
# 219,112,147
palevioletred=Pale violet red
# 255,239,213
papayawhip=Papaya whip
# 255,218,185
peachpuff=Peach puff
# 205,133,63
peru=Peru
# 255,192,203
pink=Pink
# 221,160,221
plum=Plum
# 176,224,230
powderblue=Powder blue
# 128,0,128
purple=Purple
# 255,0,0
red=Red
# 188,143,143
rosybrown=Rosy brown
# 65,105,225
royalblue=Royal blue
# 139,69,19
saddlebrown=Saddle brown
# 250,128,114
salmon=Salmon
# 244,164,96
sandybrown=Sandy brown
# 46,139,87
seagreen=Sea green
# 255,245,238
seashell=Seashell
# 160,82,45
sienna=Sienna
# 192,192,192
silver=Silver
# 135,206,235
skyblue=Sky blue
# 106,90,205
slateblue=Slate blue
# 112,128,144
slategray=Slate gray
# 112,128,144
slategrey=Slate grey
# 255,250,250
snow=Snow
# 0,255,127
springgreen=Spring green
# 70,130,180
steelblue=Steel blue
# 210,180,140
tan=Tan
# 0,128,128
teal=Teal
# 216,191,216
thistle=Thistle
# 255,99,71
tomato=Tomato
# 64,224,208
turquoise=Turquoise
# 238,130,238
violet=Violet
# 245,222,179
wheat=Wheat
# 255,255,255
white=White
# 245,245,245
whitesmoke=White smoke
# 255,255,0
yellow=Yellow
# 154,205,50
yellowgreen=Yellow green
# Continuous palette names
satSmall=Saturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 1f, false),
unsatSmall=Desaturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 0.4f, false),
satSmallHoriz=Saturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 1f, true),
unsatSmallHoriz=Desaturated colors
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 0.4f, true),
satLarge=Saturated colors - large
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 1f, false),
unsatLarge=Desaturated colors - large
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 0.4f, false),
satLargeHoriz=Saturated colors - large
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 1f, true),
unsatLargeHoriz=Desaturated colors - large
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 0.4f, true)

View file

@ -0,0 +1,42 @@
# Sun Public License Notice
#
# The contents of this file are subject to the Sun Public License
# Version 1.0 (the "License"). You may not use this file except in
# compliance with the License. A copy of the License is available at
# http://www.sun.com/
#
# The Original Code is NetBeans. The Initial Developer of the Original
# Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
# Microsystems, Inc. All Rights Reserved.
#Palette names
basic=Primary colors
svg=Constantes SVG/X11
swing=Constantes
system=System colors
recent=Recent colors
tip=Click and hold combinations of Ctrl/Shift/Alt to switch palettes
tip.mac=Click and hold combinations of Command/Shift/Alt to switch palettes
# Continuous palette names
satSmall=Couleurs satur\u00E9es
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 1f, false),
unsatSmall=Couleurs d\u00E9satur\u00E9es
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 0.4f, false),
satSmallHoriz=Couleurs satur\u00E9es
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 1f, true),
unsatSmallHoriz=Couleurs d\u00E9satur\u00E9es
#SMALL_SPEC_WIDTH, SMALL_SPEC_HEIGHT, 0.4f, true),
satLarge=Couleurs satur\u00E9es
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 1f, false),
unsatLarge=Couleurs d\u00E9satur\u00E9es
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 0.4f, false),
satLargeHoriz=Couleurs satur\u00E9es
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 1f, true),
unsatLargeHoriz=Couleurs d\u00E9satur\u00E9es
#LARGE_SPEC_WIDTH, LARGE_SPEC_HEIGHT, 0.4f, true)
chooseColor="Choisir une couleur"

View file

@ -0,0 +1,112 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.metal.MetalLookAndFeel;
/**
* Default border for the color chooser, which uses bevels that lighten/darken
* the selected color, and includes slightly different painting logic for Metal
* LAF.
*
* @author Tim Boudreau
*/
class CCBorder implements Border {
public Insets getBorderInsets(final Component c) {
Insets result;
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel) {
result = new Insets(2, 2, 1, 1);
} else {
result = new Insets(1, 1, 1, 1);
}
return result;
}
public boolean isBorderOpaque() {
return true;
}
public void paintBorder(final Component c, final Graphics g, final int x,
final int y, final int w, final int h) {
final ColorChooser cc = (ColorChooser) c;
if (!cc.isEnabled()) {
g.setColor(cc.getColor());
g.fillRect(x, y, w, h);
return;
}
Color col = cc.transientColor() == null ? cc.getColor() : cc
.transientColor();
if (cc == null) {
col = c.getBackground();
if (col == null) {
col = Color.BLACK;
}
}
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel) {
g.setColor(darken(col));
g.drawLine(x, y, x + w - 1, y);
g.drawLine(x, y, x, y + h - 1);
g.drawLine(x + w - 1, y + h - 1, x, y + h - 1);
g.drawLine(x + w - 1, y + h - 1, x + w - 1, y);
g.setColor(brighten(col));
g.drawLine(x + w - 2, y + h - 2, x + 1, y + h - 2);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + 1);
} else {
g.setColor(darken(col));
g.drawLine(x + w - 1, y + h - 1, x, y + h - 1);
g.drawLine(x + w - 1, y + h - 1, x + w - 1, y);
g.setColor(brighten(col));
g.drawLine(x, y, x + w - 1, y);
g.drawLine(x, y, x, y + h - 1);
}
}
/** Slightly more subtle than Color.darker() */
private static final Color darken(final Color c) {
final int amount = 30;
final int r = normalizeToByte(c.getRed() - amount);
final int g = normalizeToByte(c.getGreen() - amount);
final int b = normalizeToByte(c.getGreen() - amount);
return new Color(r, g, b);
}
/** Slightly more subtle than Color.brighter() */
private static final Color brighten(final Color c) {
final int amount = 30;
final int r = normalizeToByte(c.getRed() + amount);
final int g = normalizeToByte(c.getGreen() + amount);
final int b = normalizeToByte(c.getGreen() + amount);
return new Color(r, g, b);
}
/** Ensure an int is within the possible range for a byte */
private static final int normalizeToByte(final int i) {
return Math.min(255, Math.max(0, i));
}
}

View file

@ -0,0 +1,156 @@
*******************************************************
* Colorchooser Dual License Header and License Notice *
*******************************************************
Colorchooser is dual licensed with Common Development and Distribution License (CDDL) and the GNU General Public License (GPL) with Classpath exception.
*******************************************************
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
1. Definitions.
1.1. ÒContributorÓ means each individual or entity that creates or contributes to the creation of Modifications.
1.2. ÒContributor VersionÓ means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor.
1.3. ÒCovered SoftwareÓ means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof.
1.4. ÒExecutableÓ means the Covered Software in any form other than Source Code.
1.5. ÒInitial DeveloperÓ means the individual or entity that first makes Original Software available under this License.
1.6. ÒLarger WorkÓ means a work which combines Covered Software or portions thereof with code not governed by the terms of this License.
1.7. ÒLicenseÓ means this document.
1.8. ÒLicensableÓ means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
1.9 ÒModificationsÓ means the Source Code and Executable form of any of the following:
A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications;
B. Any new file that contains any part of the Original Software or previous Modification; or
C. Any new file that is contributed or otherwise made available under the terms of this License.
1.10. ÒOriginal SoftwareÓ means the Source Code and Executable form of computer software code that is originally released under this License.
1.11. ÒPatent ClaimsÓ means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
1.12. ÒSource CodeÓ means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code.
1.13. ÒYouÓ (or ÒYourÓ) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, ÒYouÓ includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, ÒcontrolÓ means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
2. License Grants.
2.1. The Initial Developer Grant.
Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof).
(c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License.
(d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices.
2.2. Contributor Grant.
Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
(c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party.
(d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor.
3. Distribution Obligations.
3.1. Availability of Source Code.
Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange.
3.2. Modifications.
The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License.
3.3. Required Notices.
You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer.
3.4. Application of Additional Terms.
You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipientsÕ rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
3.5. Distribution of Executable Versions.
You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipientÕs rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer.
3.6. Larger Works.
You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software.
4. Versions of the License.
4.1. New Versions.
Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License.
4.2. Effect of New Versions.
You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward.
4.3. Modified Versions.
When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License.
5. DISCLAIMER OF WARRANTY.
COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN ÒAS ISÓ BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
6. TERMINATION.
6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as ÒParticipantÓ) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant.
6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination.
7. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYÕS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
8. U.S. GOVERNMENT END USERS.
The Covered Software is a Òcommercial item,Ó as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of Òcommercial computer softwareÓ (as that term is defined at 48 C.F.R. ¤252.227-7014(a)(1)) and Òcommercial computer software documentationÓ as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License.
9. MISCELLANEOUS.
This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictionÕs conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneysÕ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software.
10. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL)
The code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California.
*******************************************************
The GNU General Public License (GPL) Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
One line to give the program's name and a brief idea of what it does.
Copyright (C)
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.
"CLASSPATH" EXCEPTION TO THE GPL VERSION 2
Certain source files distributed by Sun Microsystems, Inc. are subject to the following clarification and special exception to the GPL Version 2, but only where Sun has expressly included in the particular source file's header the words:
"Sun designates this particular file as subject to the "Classpath" exception as provided by Sun in the License file that accompanied this code."
Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License Version 2 cover the whole combination.
As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.

View file

@ -0,0 +1,398 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.swing.JComponent;
import javax.swing.UIManager;
/**
* A color chooser which can pop up a pluggable set of palettes. The palette
* displayed is controlled by combinations of the alt and shift and ctrl
* (command on macintosh) keys. Will fire an action event when a color is
* selected. For accessibility, it will show a standard Swing color chooser if
* focused and either space or enter are pressed.
* <p>
* By default, supports two sets of palettes - a set of 4 continuous palettes
* and a set of 4 tiled, fixed palettes (the SVG/X palette, Swing/AWT palettes
* and a history of recently selected colors). Whether the tiled or continuous
* palettes are given precedence depends on the property <code>
* continuousPalettePreferred</code>.
* <p>
* Palettes are pluggable, so it is possible to provide your own
* implementation(s) of Palette to be displayed when the component is clicked.
* <p>
* Typical usage: Attach an ActionListener; it will be notified when the user
* selects a color.
* <p>
* To catch colors as the user selects, listen for PROP_TRANSIENT_COLOR. The
* component will fire changes in PROP_COLOR along with actin events, when the
* user selects a color. PROP_COLOR changes are fired both in response to use
* actions and programmatic changes to the color property.
* <P>
*
* @author Tim Boudreau
*/
public class ColorChooser extends JComponent {
/**
*
*/
private static final long serialVersionUID=1L;
/**
* UI Class ID under which the UI delegate class is stored in UIManager (see
* UIManager.getUI()). The string value is
* <code>&quot;nbColorChooserUI&quot;</code>
*/
public static final String UI_CLASS_ID="nbColorChooserUI"; // NOI18N
private transient Palette[] palettes=null;
private Color color=Color.BLUE;
private transient Color transientColor=null;
private transient ArrayList<ActionListener> actionListenerList;
/**
* Property name for property fired when the color property changes.
*/
public static final String PROP_COLOR="color"; // NOI18N
/**
* Property name for property fired when the transient color property (the
* color while the user is selecting) changes.
*/
public static final String PROP_TRANSIENT_COLOR="transientColor"; // NOI18N
/**
* Fired when the value of the continuous palette changes.
*/
public static final String PROP_CONTINUOUS_PALETTE="continuousPalette"; // NOI18N
/**
* Property indicating the visibility of the popup palette. Code that tracks
* PROP_TRANSIENT_COLOR can listen for this property with a value of false
* to do a final update using the value from getColor() to ensure the set
* color is in sync with the actual value of the color picker - in the case
* that the mouse was released off the palette, the color may be restored to
* its previous value.
*/
public static final String PROP_PICKER_VISIBLE="pickerVisible";
private boolean continuousPalette=true;
/** Create a color chooser */
public ColorChooser() {
this((Color) null);
}
/**
* Create a color chooser initialized to the passed color, defaulted to show
* a continuous palette on initial click.
*
* @param initialColor
*/
public ColorChooser(final Color initialColor) {
this(null, initialColor);
}
/**
* Create a color chooser with the passed array of 8 palettes and
* initialized with the passed color.
*
* @param palettes
* @param initialColor
*/
public ColorChooser(final Palette[] palettes, final Color initialColor) {
setPalettes(palettes);
if (initialColor!=null) {
color=initialColor;
}
updateUI();
}
/**
* Create a color chooser with the passed array of 8 or fewer palettes.
*
* @param palettes
*/
public ColorChooser(final Palette[] palettes) {
this(palettes, null);
}
/**
* Overridden to return <code>UI_CLASS_ID</code>
*
* @return
*/
public String getUIClassId() {
return UI_CLASS_ID;
}
/**
*
*/
@Override
public void updateUI() {
if (UIManager.get(UI_CLASS_ID)!=null) {
setUI((ColorChooserUI) UIManager.getUI(this));
} else {
setUI(DefaultColorChooserUI.createUI(this));
}
}
/**
* Get the color currently represented by this component. If the user is in
* the process of selecting (the palette or color chooser is open), this
* will be the last known value, until such time as the user selects a color
* and an action event is fired.
*
* @return
*/
public Color getColor() {
return color;
}
/**
* Set the color this color chooser currently represents. Note this will
* fire a change in <code>PROP_COLOR</code> but will not trigger an action
* event to be fired.
*
* @param c
*/
public void setColor(Color c) {
if (c.getClass()!=Color.class) {
c=new Color(c.getRed(), c.getGreen(), c.getBlue());
}
if ((color!=null&&!color.equals(c))||(color==null&&c!=null)) {
final Color old=color;
color=c;
repaint();
firePropertyChange(PROP_COLOR, old, c); // NOI18N
}
}
void setTransientColor(final Color c) {
final Color old=transientColor;
transientColor=c;
if ((c!=null&&!color.equals(old))||(old==null&&c!=null)) {
firePropertyChange(PROP_TRANSIENT_COLOR, old, getTransientColor());
repaint();
} else if (c==null) {
firePropertyChange(PROP_TRANSIENT_COLOR, old, getColor());
repaint();
}
}
/**
* Returns the currently displayed color which may not be the same as the
* value of <code>getColor()</code> but is the color currently displayed as
* the user moves the mouse to select the color.
*
* @see #PROP_TRANSIENT_COLOR
* @see #setTransientColor
* @return the color currently being displayed (not necessarily the one
* returned by <code>getColor()</code>).
*/
public Color getTransientColor() {
return transientColor==null?null:new Color(transientColor.getRed(), transientColor.getGreen(), transientColor.getBlue());
}
/**
* Get a string representation of a color, if possible returning a named,
* localized constant if the passed color matches one of the SVG constants;
* else returning a String representing RGB values.
*
* @param c
* @return
*/
public static String colorToString(final Color c) {
RecentColors.getDefault();
final NamedColor named=RecentColors.findNamedColor(c);
if (named==null) {
final StringBuffer sb=new StringBuffer();
sb.append(c.getRed());
sb.append(',');
sb.append(c.getGreen());
sb.append(',');
sb.append(c.getBlue());
return sb.toString();
} else {
return named.getDisplayName();
}
}
Color transientColor() {
return transientColor;
}
/**
* Returns the SVG or Swing constant name for the passed color, if the color
* exactly matches a color in the Swing UIManager constants or the
* SVG/X-Windows constants.
*
* @param color
* @return
*/
public static String getColorName(final Color color) {
return PredefinedPalette.getColorName(color);
}
/**
* Set whether the initial palette shown when clicked with no keys pressed
* is one showing a continuous (rainbow) palette or a set of tiles with
* different colors.
*
* @param val
* The value, true to show a continuous palette by default
*/
public void setContinuousPalettePreferred(final boolean val) {
if (val!=continuousPalette) {
continuousPalette=val;
setPalettes(null);
firePropertyChange(PROP_CONTINUOUS_PALETTE, !val, val);
}
}
/**
* Determine whether the initial palette shown when clicked with no keys
* pressed is one showing a continuous (rainbow) palette or a set of tiles
* with different colors. The default is <code>TRUE</code>.
*
* @return whether or not to default to a continuous palette
*/
public boolean isContinuousPalettePreferred() {
return continuousPalette;
}
/**
* Set the Palette objects this color chooser will display. Can be null to
* reset to defaults. The passed array length must less than or equal to 8.
* <p>
* Which palette is shown to the user depends on what if any control keys
* are being held when the user initially clicks or presses while dragging
* the mouse to select. The mapping between key combinations and palette
* entries is:
* <ul>
* <li>No keys held: 0</li>
* <li>Shift: 1</li>
* <li>Ctrl (Command on macintosh): 2</li>
* <li>Shift-Ctrl(Command): 3</li>
* <li>Alt: 4</li>
* <li>Alt-Shift: 5</li>
* <li>Alt-Ctrl(Command): 6</li>
* <li>Alt-Ctrl(Command)-Shift: 7</li>
* </ul>
*
* @param palettes
*/
public void setPalettes(Palette[] palettes) {
if (palettes!=null&&palettes.length>8) {
throw new IllegalArgumentException("Must be <= 8 palettes"); // NOI18N
}
final Palette[] old=this.palettes;
if (palettes==null) {
palettes=Palette.getDefaultPalettes(continuousPalette);
}
this.palettes=palettes;
firePropertyChange("palettes", old, palettes.clone()); // NOI18N
}
/**
* Get the array of palettes that will be displayed when the user clicks
* this color chooser component and holds down various keys.
*
* @return
*/
public Palette[] getPalettes() {
final Palette[] result=new Palette[palettes.length];
System.arraycopy(palettes, 0, result, 0, palettes.length);
return result;
}
static String getString(final String key) {
if (key==null) {
return null;
}
final String BUNDLE="net.java.dev.colorchooser.Bundle"; // NOI18N
try {
return ResourceBundle.getBundle(BUNDLE).getString(key);
} catch (final MissingResourceException mre) {
// mre.printStackTrace();
return key;
}
}
// ****************** Action listener support **************************
/**
* Registers ActionListener to receive events. Action events are fired when
* the user selects a color, either by click-drag-releasing the mouse over
* the popup palette, or by pressing space or enter and selecting a color
* from the popup <code>JColorChooser</code>.
*
* @param listener
* The listener to register.
*/
public synchronized void addActionListener(
final java.awt.event.ActionListener listener) {
if (actionListenerList==null) {
actionListenerList=new ArrayList<ActionListener>();
}
actionListenerList.add(listener);
}
/**
* Removes ActionListener from the list of listeners. Action events are
* fired when the user selects a color, either by click-drag-releasing the
* mouse over the popup palette, or by pressing space or enter and selecting
* a color from the popup <code>JColorChooser</code> (note they are
* <i>not</i> fired if you call <code>setColor()</code>).
*
* @param listener
* The listener to remove.
*/
public synchronized void removeActionListener(
final java.awt.event.ActionListener listener) {
if (actionListenerList!=null) {
actionListenerList.remove(listener);
}
}
/**
* Notifies all registered listeners about the event.
*
* @param event
* The event to be fired
*/
void fireActionPerformed(final ActionEvent event) {
List<?> list;
synchronized (this) {
if (actionListenerList==null) {
return;
}
list=(List<?>) ((ArrayList<ActionListener>) actionListenerList).clone();
}
for (int i=0; i<list.size(); i++) {
((java.awt.event.ActionListener) list.get(i)).actionPerformed(event);
}
}
void firePickerVisible(final boolean val) {
firePropertyChange(PROP_PICKER_VISIBLE, !val, val);
}
}

View file

@ -0,0 +1,382 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
public class ColorChooserBeanInfo extends SimpleBeanInfo {
// Bean descriptor//GEN-FIRST:BeanDescriptor
/* lazy BeanDescriptor */
private static BeanDescriptor getBdescriptor() {
final BeanDescriptor beanDescriptor = new BeanDescriptor(
net.java.dev.colorchooser.ColorChooser.class, null); // NOI18N//GEN-HEADEREND:BeanDescriptor
// Here you can add code for customizing the BeanDescriptor.
return beanDescriptor;
}// GEN-LAST:BeanDescriptor
// Property identifiers//GEN-FIRST:Properties
private static final int PROPERTY_color = 0;
private static final int PROPERTY_continuousPalettePreferred = 1;
private static final int PROPERTY_cursor = 2;
private static final int PROPERTY_enabled = 3;
private static final int PROPERTY_height = 4;
private static final int PROPERTY_maximumSize = 5;
private static final int PROPERTY_minimumSize = 6;
private static final int PROPERTY_name = 7;
private static final int PROPERTY_preferredSize = 8;
private static final int PROPERTY_toolTipText = 9;
private static final int PROPERTY_transientColor = 10;
private static final int PROPERTY_visible = 11;
private static final int PROPERTY_width = 12;
private static final int PROPERTY_x = 13;
private static final int PROPERTY_y = 14;
// Property array
/* lazy PropertyDescriptor */
private static PropertyDescriptor[] getPdescriptor() {
final PropertyDescriptor[] properties = new PropertyDescriptor[15];
try {
properties[PROPERTY_color] = new PropertyDescriptor("color",
net.java.dev.colorchooser.ColorChooser.class, "getColor",
"setColor"); // NOI18N
properties[PROPERTY_color].setPreferred(true);
properties[PROPERTY_continuousPalettePreferred] = new PropertyDescriptor(
"continuousPalettePreferred",
net.java.dev.colorchooser.ColorChooser.class,
"isContinuousPalettePreferred",
"setContinuousPalettePreferred"); // NOI18N
properties[PROPERTY_continuousPalettePreferred].setPreferred(true);
properties[PROPERTY_cursor] = new PropertyDescriptor("cursor",
net.java.dev.colorchooser.ColorChooser.class, "getCursor",
"setCursor"); // NOI18N
properties[PROPERTY_enabled] = new PropertyDescriptor("enabled",
net.java.dev.colorchooser.ColorChooser.class, "isEnabled",
"setEnabled"); // NOI18N
properties[PROPERTY_height] = new PropertyDescriptor("height",
net.java.dev.colorchooser.ColorChooser.class, "getHeight",
null); // NOI18N
properties[PROPERTY_maximumSize] = new PropertyDescriptor(
"maximumSize",
net.java.dev.colorchooser.ColorChooser.class,
"getMaximumSize", "setMaximumSize"); // NOI18N
properties[PROPERTY_minimumSize] = new PropertyDescriptor(
"minimumSize",
net.java.dev.colorchooser.ColorChooser.class,
"getMinimumSize", "setMinimumSize"); // NOI18N
properties[PROPERTY_name] = new PropertyDescriptor("name",
net.java.dev.colorchooser.ColorChooser.class, "getName",
"setName"); // NOI18N
properties[PROPERTY_preferredSize] = new PropertyDescriptor(
"preferredSize",
net.java.dev.colorchooser.ColorChooser.class,
"getPreferredSize", "setPreferredSize"); // NOI18N
properties[PROPERTY_toolTipText] = new PropertyDescriptor(
"toolTipText",
net.java.dev.colorchooser.ColorChooser.class,
"getToolTipText", "setToolTipText"); // NOI18N
properties[PROPERTY_transientColor] = new PropertyDescriptor(
"transientColor",
net.java.dev.colorchooser.ColorChooser.class,
"getTransientColor", null); // NOI18N
properties[PROPERTY_transientColor].setExpert(true);
properties[PROPERTY_visible] = new PropertyDescriptor("visible",
net.java.dev.colorchooser.ColorChooser.class, "isVisible",
"setVisible"); // NOI18N
properties[PROPERTY_width] = new PropertyDescriptor("width",
net.java.dev.colorchooser.ColorChooser.class, "getWidth",
null); // NOI18N
properties[PROPERTY_x] = new PropertyDescriptor("x",
net.java.dev.colorchooser.ColorChooser.class, "getX", null); // NOI18N
properties[PROPERTY_y] = new PropertyDescriptor("y",
net.java.dev.colorchooser.ColorChooser.class, "getY", null); // NOI18N
} catch (final IntrospectionException e) {
e.printStackTrace();
}// GEN-HEADEREND:Properties
// Here you can add code for customizing the properties array.
return properties;
}// GEN-LAST:Properties
// EventSet identifiers//GEN-FIRST:Events
private static final int EVENT_actionListener = 0;
private static final int EVENT_componentListener = 1;
private static final int EVENT_focusListener = 2;
private static final int EVENT_hierarchyBoundsListener = 3;
private static final int EVENT_inputMethodListener = 4;
private static final int EVENT_keyListener = 5;
private static final int EVENT_mouseListener = 6;
private static final int EVENT_mouseMotionListener = 7;
private static final int EVENT_propertyChangeListener = 8;
// EventSet array
/* lazy EventSetDescriptor */
private static EventSetDescriptor[] getEdescriptor() {
final EventSetDescriptor[] eventSets = new EventSetDescriptor[9];
try {
eventSets[EVENT_actionListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"actionListener", java.awt.event.ActionListener.class,
new String[] { "actionPerformed" }, "addActionListener",
"removeActionListener"); // NOI18N
eventSets[EVENT_actionListener].setPreferred(true);
eventSets[EVENT_componentListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"componentListener",
java.awt.event.ComponentListener.class, new String[] {
"componentHidden", "componentMoved",
"componentResized", "componentShown" },
"addComponentListener", "removeComponentListener"); // NOI18N
eventSets[EVENT_focusListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"focusListener", java.awt.event.FocusListener.class,
new String[] { "focusGained", "focusLost" },
"addFocusListener", "removeFocusListener"); // NOI18N
eventSets[EVENT_hierarchyBoundsListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"hierarchyBoundsListener",
java.awt.event.HierarchyBoundsListener.class, new String[] {
"ancestorMoved", "ancestorResized" },
"addHierarchyBoundsListener",
"removeHierarchyBoundsListener"); // NOI18N
eventSets[EVENT_inputMethodListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"inputMethodListener",
java.awt.event.InputMethodListener.class, new String[] {
"caretPositionChanged", "inputMethodTextChanged" },
"addInputMethodListener", "removeInputMethodListener"); // NOI18N
eventSets[EVENT_keyListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"keyListener", java.awt.event.KeyListener.class,
new String[] { "keyPressed", "keyReleased", "keyTyped" },
"addKeyListener", "removeKeyListener"); // NOI18N
eventSets[EVENT_mouseListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"mouseListener", java.awt.event.MouseListener.class,
new String[] { "mouseClicked", "mouseEntered",
"mouseExited", "mousePressed", "mouseReleased" },
"addMouseListener", "removeMouseListener"); // NOI18N
eventSets[EVENT_mouseMotionListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"mouseMotionListener",
java.awt.event.MouseMotionListener.class, new String[] {
"mouseDragged", "mouseMoved" },
"addMouseMotionListener", "removeMouseMotionListener"); // NOI18N
eventSets[EVENT_propertyChangeListener] = new EventSetDescriptor(
net.java.dev.colorchooser.ColorChooser.class,
"propertyChangeListener",
java.beans.PropertyChangeListener.class,
new String[] { "propertyChange" },
"addPropertyChangeListener", "removePropertyChangeListener"); // NOI18N
} catch (final IntrospectionException e) {
e.printStackTrace();
}// GEN-HEADEREND:Events
// Here you can add code for customizing the event sets array.
return eventSets;
}// GEN-LAST:Events
// Method identifiers//GEN-FIRST:Methods
// Method array
/* lazy MethodDescriptor */
private static MethodDescriptor[] getMdescriptor() {
final MethodDescriptor[] methods = new MethodDescriptor[0];// GEN-HEADEREND:Methods
// Here you can add code for customizing the methods array.
return methods;
}// GEN-LAST:Methods
private static java.awt.Image iconColor16 = null;// GEN-BEGIN:IconsDef
private static java.awt.Image iconColor32 = null;
private static java.awt.Image iconMono16 = null;
private static java.awt.Image iconMono32 = null;// GEN-END:IconsDef
private static String iconNameC16 = "/org/netbeans/swing/colorchooser/chooserIcon.gif";// GEN-BEGIN:Icons
private static String iconNameC32 = "/org/netbeans/swing/colorchooser/chooserIcon32.gif";
private static String iconNameM16 = null;
private static String iconNameM32 = null;// GEN-END:Icons
private static final int defaultPropertyIndex = -1;// GEN-BEGIN:Idx
private static final int defaultEventIndex = -1;// GEN-END:Idx
// GEN-FIRST:Superclass
// Here you can add code for customizing the Superclass BeanInfo.
// GEN-LAST:Superclass
/**
* Gets the bean's <code>BeanDescriptor</code>s.
*
* @return BeanDescriptor describing the editable properties of this bean.
* May return null if the information should be obtained by
* automatic analysis.
*/
@Override
public BeanDescriptor getBeanDescriptor() {
return getBdescriptor();
}
/**
* Gets the bean's <code>PropertyDescriptor</code>s.
*
* @return An array of PropertyDescriptors describing the editable
* properties supported by this bean. May return null if the
* information should be obtained by automatic analysis.
* <p>
* If a property is indexed, then its entry in the result array will
* belong to the IndexedPropertyDescriptor subclass of
* PropertyDescriptor. A client of getPropertyDescriptors can use
* "instanceof" to check if a given PropertyDescriptor is an
* IndexedPropertyDescriptor.
*/
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
return getPdescriptor();
}
/**
* Gets the bean's <code>EventSetDescriptor</code>s.
*
* @return An array of EventSetDescriptors describing the kinds of events
* fired by this bean. May return null if the information should be
* obtained by automatic analysis.
*/
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
return getEdescriptor();
}
/**
* Gets the bean's <code>MethodDescriptor</code>s.
*
* @return An array of MethodDescriptors describing the methods implemented
* by this bean. May return null if the information should be
* obtained by automatic analysis.
*/
@Override
public MethodDescriptor[] getMethodDescriptors() {
return getMdescriptor();
}
/**
* A bean may have a "default" property that is the property that will
* mostly commonly be initially chosen for update by human's who are
* customizing the bean.
*
* @return Index of default property in the PropertyDescriptor array
* returned by getPropertyDescriptors.
* <P>
* Returns -1 if there is no default property.
*/
@Override
public int getDefaultPropertyIndex() {
return defaultPropertyIndex;
}
/**
* A bean may have a "default" event that is the event that will mostly
* commonly be used by human's when using the bean.
*
* @return Index of default event in the EventSetDescriptor array returned
* by getEventSetDescriptors.
* <P>
* Returns -1 if there is no default event.
*/
@Override
public int getDefaultEventIndex() {
return defaultEventIndex;
}
/**
* This method returns an image object that can be used to represent the
* bean in toolboxes, toolbars, etc. Icon images will typically be GIFs, but
* may in future include other formats.
* <p>
* Beans aren't required to provide icons and may return null from this
* method.
* <p>
* There are four possible flavors of icons (16x16 color, 32x32 color, 16x16
* mono, 32x32 mono). If a bean choses to only support a single icon we
* recommend supporting 16x16 color.
* <p>
* We recommend that icons have a "transparent" background so they can be
* rendered onto an existing background.
*
* @param iconKind
* The kind of icon requested. This should be one of the constant
* values ICON_COLOR_16x16, ICON_COLOR_32x32, ICON_MONO_16x16, or
* ICON_MONO_32x32.
* @return An image object representing the requested icon. May return null
* if no suitable icon is available.
*/
@Override
public java.awt.Image getIcon(final int iconKind) {
switch (iconKind) {
case ICON_COLOR_16x16:
if (iconNameC16 == null)
return null;
else {
if (iconColor16 == null)
iconColor16 = loadImage(iconNameC16);
return iconColor16;
}
case ICON_COLOR_32x32:
if (iconNameC32 == null)
return null;
else {
if (iconColor32 == null)
iconColor32 = loadImage(iconNameC32);
return iconColor32;
}
case ICON_MONO_16x16:
if (iconNameM16 == null)
return null;
else {
if (iconMono16 == null)
iconMono16 = loadImage(iconNameM16);
return iconMono16;
}
case ICON_MONO_32x32:
if (iconNameM32 == null)
return null;
else {
if (iconMono32 == null)
iconMono32 = loadImage(iconNameM32);
return iconMono32;
}
default:
return null;
}
}
}

View file

@ -0,0 +1,366 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
/**
* Parent class of UI delegates for color choosers. This class handles popping
* up palettes and selection/setting transient color and firing events.
* Generally, subclasses will simply want to override the painting logic.
* <p>
* To completely override all behavior, override <code>installListeners()</code>
* and <code>uninstallListeners()</code> and do not have them call super.
*
* @author Tim Boudreau
*/
public abstract class ColorChooserUI extends ComponentUI {
/** Creates a new instance of ColorChooserUI */
protected ColorChooserUI() {
}
@Override
public final void installUI(final JComponent jc) {
installListeners((ColorChooser) jc);
init((ColorChooser) jc);
}
@Override
public final void uninstallUI(final JComponent jc) {
uninstallListeners((ColorChooser) jc);
uninit((ColorChooser) jc);
}
/** Optional initialization method called from <code>installUI()</code> */
protected void init(final ColorChooser c) {
}
/** Optional initialization method called from <code>uninstallUI()</code> */
protected void uninit(final ColorChooser c) {
}
/** Begin listening for mouse events on the passed component */
protected void installListeners(final ColorChooser c) {
final L l = new L();
c.addMouseListener(l);
c.addFocusListener(l);
c.addKeyListener(l);
c.putClientProperty("uiListener", l); // NOI18N
}
/** Stop listening for mouse events on the passed component */
protected void uninstallListeners(final ColorChooser c) {
final Object o = c.getClientProperty("uiListener"); // NOI18N
if (o instanceof L) {
final L l = (L) o;
c.removeMouseListener(l);
c.removeFocusListener(l);
c.removeKeyListener(l);
}
}
/** Running on macintosh? */
static final boolean MAC = System.getProperty("mrj.version") // NOI18N
!= null;
/**
*
* Map a key event to an integer used to index into the array of available
* palettes, used to change which palette is displayed on the fly. Note this
* method reads the key code, not the modifiers, of the key event.
* <p>
* If you override this method, also override
* <code>paletteIndexFromModifiers</code>.
* <p>
* The palette actually used is as follows:
* <ul>
* <li>No keys held: 0</li>
* <li>Shift: 1</li>
* <li>Ctrl (Command on macintosh): 2</li>
* <li>Shift-Ctrl(Command): 3</li>
* <li>Alt: 4</li>
* <li>Alt-Shift: 5</li>
* <li>Alt-Ctrl(Command): 6</li>
* <li>Alt-Ctrl(Command)-Shift: 7</li>
* </ul>
*/
protected int paletteIndexFromKeyCode(final KeyEvent ke) {
final int keyCode = ke.getKeyCode();
int result = (keyCode == KeyEvent.VK_SHIFT) ? 1 : 0;
if (MAC) {
result += (keyCode == KeyEvent.VK_META) ? 2 : 0;
} else {
result += (keyCode == KeyEvent.VK_CONTROL) ? 2 : 0;
}
result += (keyCode == KeyEvent.VK_ALT) ? 4 : 0;
return result;
}
/**
*
* Map the modifiers on an input event to an integer used to index into the
* array of available palettes, used to change which palette is displayed on
* the fly. Note this method uses the value of from the event's
* <code>getModifiersEx()</code> method.
* <p>
* If you override this method, also override
* <code>paletteIndexFromKeyCode</code>.
* <p>
* The palette actually used is as follows:
* <ul>
* <li>No keys held: 0</li>
* <li>Shift: 1</li>
* <li>Ctrl (Command on macintosh): 2</li>
* <li>Shift-Ctrl(Command): 3</li>
* <li>Alt: 4</li>
* <li>Alt-Shift: 5</li>
* <li>Alt-Ctrl(Command): 6</li>
* <li>Alt-Ctrl(Command)-Shift: 7</li>
* </ul>
*/
protected int paletteIndexFromModifiers(final InputEvent me) {
final int mods = me.getModifiersEx();
int result = ((mods & InputEvent.SHIFT_DOWN_MASK) != 0) ? 1 : 0;
result += ((mods & InputEvent.CTRL_DOWN_MASK) != 0) ? 2 : 0;
result += ((mods & InputEvent.ALT_DOWN_MASK) != 0) ? 4 : 0;
return result;
}
private JColorChooser jchooser = null;
/**
* Called when the color chooser is invoked from the keyboard (user pressed
* space or enter).
*/
protected void keyboardInvoke(final ColorChooser colorChooser) {
if (!colorChooser.isEnabled()) {
Toolkit.getDefaultToolkit().beep();
return;
}
if (jchooser == null) {
jchooser = new JColorChooser();
} else {
return;
}
jchooser.setColor(colorChooser.getColor());
final Color nue = JColorChooser.showDialog(colorChooser, ColorChooser
.getString("chooseColor"), // NOI18N
colorChooser.getColor());
if (nue != null) {
colorChooser.setColor(nue);
fireColorChanged(colorChooser);
}
jchooser = null;
}
/**
* Cause the passed color chooser to fire an action event to its listeners
* notifying them that the color has changed.
*/
protected void fireColorChanged(final ColorChooser chooser) {
chooser.fireActionPerformed(new ActionEvent(chooser,
ActionEvent.ACTION_PERFORMED, "color")); // NOI18N
}
@Override
public Dimension getMaximumSize(final JComponent c) {
if (!c.isMaximumSizeSet()) {
return getPreferredSize(c);
} else {
return super.getMaximumSize(c);
}
}
@Override
public Dimension getMinimumSize(final JComponent c) {
if (!c.isMinimumSizeSet()) {
return getPreferredSize(c);
} else {
return super.getMinimumSize(c);
}
}
@Override
public Dimension getPreferredSize(final JComponent c) {
if (!c.isPreferredSizeSet()) {
return new Dimension(24, 24);
} else {
return super.getPreferredSize(c);
}
}
private class L extends MouseAdapter implements FocusListener, KeyListener {
private int paletteIndex = 0;
private transient Point nextFocusPopupLocation = null;
int getPaletteIndex() {
return paletteIndex;
}
void initPaletteIndex(final ColorChooser c, final MouseEvent me) {
paletteIndex = paletteIndexFromModifiers(me);
checkRange(c);
}
private void checkRange(final ColorChooser chooser) {
final Palette[] p = chooser.getPalettes();
if (paletteIndex >= p.length) {
paletteIndex = p.length - 1;
}
}
private void updatePaletteIndex(final ColorChooser chooser,
final int value, final boolean pressed) {
final int oldIndex = paletteIndex;
int result = paletteIndex;
if (pressed) {
result |= value;
} else {
result ^= value;
}
if (oldIndex != result
&& PalettePopup.getDefault().isPopupVisible(chooser)) {
paletteIndex = result;
checkRange(chooser);
PalettePopup.getDefault().setPalette(
chooser.getPalettes()[paletteIndex]);
}
}
@Override
public void mousePressed(final MouseEvent me) {
// boolean rightclic=me.isPopupTrigger();
final boolean rightclic = (me.getModifiers() == Event.META_MASK);
final ColorChooser chooser = (ColorChooser) me.getSource();
if (!chooser.isEnabled()) {
Toolkit.getDefaultToolkit().beep();
return;
}
// Point p = me.getPoint();
final Point p = chooser.getLocationOnScreen();
p.translate(chooser.getWidth(), chooser.getHeight());
// SwingUtilities.convertPointToScreen(p, chooser);
initPaletteIndex(chooser, me);
if (rightclic) {
PalettePopup.getDefault().setPalette(chooser.getPalettes()[7]);
} else {
PalettePopup.getDefault().setPalette(
chooser.getPalettes()[getPaletteIndex()]);
}
if (chooser.hasFocus()) {
PalettePopup.getDefault().showPopup(chooser, p);
} else {
nextFocusPopupLocation = p;
chooser.requestFocus();
return;
}
me.consume();
nextFocusPopupLocation = null;
}
@Override
public void mouseReleased(final MouseEvent me) {
// if (me.isPopupTrigger()) return;
final ColorChooser chooser = (ColorChooser) me.getSource();
if (!chooser.isEnabled()) {
Toolkit.getDefaultToolkit().beep();
return;
}
nextFocusPopupLocation = null;
if (PalettePopup.getDefault().isPopupVisible(chooser)) {
PalettePopup.getDefault().hidePopup(chooser);
final Color transientColor = chooser.transientColor();
if (transientColor != null) {
RecentColors.getDefault().add(transientColor);
final Color old = new Color(transientColor.getRed(),
transientColor.getGreen(), transientColor.getBlue());
chooser.setTransientColor(null);
chooser.setColor(old);
fireColorChanged(chooser);
me.consume();
}
}
}
public void focusGained(final FocusEvent e) {
final ColorChooser chooser = (ColorChooser) e.getSource();
if (nextFocusPopupLocation != null && chooser.isEnabled()) {
PalettePopup.getDefault().showPopup(chooser,
nextFocusPopupLocation);
}
nextFocusPopupLocation = null;
chooser.repaint();
}
public void focusLost(final FocusEvent e) {
final ColorChooser chooser = (ColorChooser) e.getSource();
chooser.repaint();
}
public void keyTyped(final KeyEvent e) {
}
public void keyPressed(final KeyEvent e) {
processKeyEvent(e, true);
}
public void keyReleased(final KeyEvent e) {
processKeyEvent(e, false);
}
protected void processKeyEvent(final KeyEvent ke, final boolean pressed) {
final ColorChooser chooser = (ColorChooser) ke.getSource();
updatePaletteIndex(chooser, paletteIndexFromKeyCode(ke), pressed);
if (ke.getKeyCode() == KeyEvent.VK_ALT
|| ke.getKeyCode() == KeyEvent.VK_CONTROL
|| ke.getKeyCode() == KeyEvent.VK_SHIFT) {
ke.consume();
} else if ((ke.getKeyCode() == KeyEvent.VK_SPACE || ke.getKeyCode() == KeyEvent.VK_ENTER)
&& ke.getID() == KeyEvent.KEY_RELEASED) {
keyboardInvoke(chooser);
}
}
}
}

View file

@ -0,0 +1,343 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
/*
* SpectrumImageImage.java
*
* Created on January 10, 2000, 4:54 PM
*/
/**
* This class is palette that uses an offscreen bitmap which contains a spectrum
* of color and hue. The direction of gradients and saturation are settable by
* arguments to the constructor.
*
* @author Tim Boudreau
*/
final class ContinuousPalette extends Palette {
public static final int SMALL_SPEC_WIDTH = 128;
public static final int SMALL_SPEC_HEIGHT = 64;
public static final int LARGE_SPEC_WIDTH = 200;
public static final int LARGE_SPEC_HEIGHT = 100;
public static final int SPEC_IMAGE_COUNT = 8;
private BufferedImage img = null;
/**
* Set true when the bitmap has been built. Bitmap is built on the first
* call to paintTo(), or the first call to PaintTo() subsequent to a
* property being changed that affects the contents of the bitmap.
*/
private boolean initialized = false;
/**
* Holds value of property saturation. Determines the maximum saturation
* level present in the bitmap
*/
private float saturation = 1f;
/**
* Holds value of property verticalHue. When set true, hue rotation is
* vertical
*/
private boolean verticalHue = true;
/** Default value for gray strip on horizontal hue gradients */
private float grayStripSize = 0.05f;
private String name;
/**
* Creates a ContinuousPalette object with user specifiable size and
* saturation and the default horizontal hue gradient direction.
*/
ContinuousPalette(final String name, final int width, final int height,
final float saturation) {
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.setSaturation(saturation);
this.name = name;
}
/**
* Creates a ContinuousPalette object with user specifiable size, saturation
* and hue gradient direction.
*
* @param width
* The width of the image to be created
* @param height
* The height of the image to be created
* @param saturation
* The saturation of the image to be created
* @param vHue
* Sets vertical or horizontal hue gradient
*/
private ContinuousPalette(final String name, final int width,
final int height, final float saturation, final boolean vHue) {
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.setSaturation(saturation);
this.verticalHue = vHue;
this.name = name;
}
/**
* Builds the spectrum bitmap in memory by iterating through all of the
* pixels and calling getColorAt for each.
*/
protected void initImage() {
int currColor;
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
currColor = getColorAt(x, y).getRGB();
img.setRGB(x, y, currColor);
}
}
}
/**
* Public implementation of InitImage() - tests whether spectrum image has
* already been built and only builds it if needed.
*/
public final void initializeImage() {
if (!initialized)
initImage();
}
/**
* Paints the image at Coordinates 0,0 on the graphics context passed to it.
*
* @param g
* A graphics context to be painted into
*/
@Override
public void paintTo(final java.awt.Graphics g) {
if (g != null) {
initializeImage();
((Graphics2D) g).drawRenderedImage(img, AffineTransform
.getTranslateInstance(0, 0));
initialized = true;
}
}
/**
* Returns the color a pixel at a given point should be as an RGB int. Color
* is calculated as follows - Saturation is constant up to the halfway point
* in the brightness gradient direction, and brightness rises. At 100%
* brightness, you have a fully saturated color. From this point on,
* Brightness is constant at 1.0 and saturation drops linearly from the
* saturation property value down to 0.
*
* @param x
* The X coordinate for which a color value is desired
* @param y
* The Y coordinate for which a color value is desired
*/
@Override
public java.awt.Color getColorAt(final int x, final int y) {
float hue;
float brightness;
float workingSaturation;
final boolean inGrayStrip = ((float) y) / img.getHeight() > (1 - grayStripSize);
if (verticalHue) {
hue = ((float) y) / img.getHeight(); // Hue value from 0-1 based on
// y position
brightness = ((float) x) / img.getWidth(); // base brightness value
// 0-1 based on x
// location
} else {
if (inGrayStrip)
return grayValueFromX(x);
hue = 1 - (((float) x) / img.getWidth()); // subtract from 1 so
// lightest color are at
// top
brightness = 1 - ((float) y) / img.getHeight();
}
brightness = brightness * 2; // brightness increases to the halfway
// point along the brightening axis.
if (brightness > 1) { // beyond that point, saturation goes down so
// color moves toward white
workingSaturation = saturation - ((brightness - 1) * saturation); // if
// we're
// past
// the
// halfway
// point,
brightness = 1; // we're decrementing saturation
} else {
workingSaturation = saturation;
}
final java.awt.Color newColor = java.awt.Color.getHSBColor(hue,
workingSaturation, brightness);
return newColor;
}
public java.awt.Color colorFromPoint(final Point p) {
final int x = new Double(p.getX()).intValue();
final int y = new Double(p.getY()).intValue();
return getColorAt(x, y);
}
/**
* Called by InitImage() to draw the grayscale strip at the bottom of
* horizontal-hue spectrum images. Returns a grayscale value based on the
* width of the image, when called with a horizontal coordinate.
*
* @param x
* The x coordinate for which a grayscale value is desired
* @return The grayscale value (expressed as an RGB integer value)
*/
protected java.awt.Color grayValueFromX(final int x) {
final java.awt.Color newColor = java.awt.Color.getHSBColor(0, 0,
((float) x) / img.getWidth());
return newColor;
}
/**
* Getter for property saturation. Saturation defines the base saturation
* for all colors in the image. Setting it to less that 1 causes the colors
* to be more desaturated in the resulting bufferedImage.
*
* @return Returns the maximum saturation value for any colors to be
* generated in the bufferedImage.
*/
public float getSaturation() {
return saturation;
}
/**
* Sets the maximum saturation for any colors in the image. Constrained from
* 0-1. Changing this property will cause the image to be regenerated the
* next time it is needed, or the next time initializeImage() is called.
*
* @param saturation
* New value of property saturation.
*/
public void setSaturation(final float saturation) {
if (this.saturation != saturation) {
this.saturation = saturation;
doChange();
}
}
/**
* Getter for property verticalHue.
*
* @return Value of property verticalHue.
*/
public boolean isVerticalHue() {
return verticalHue;
}
/**
* Setter for property verticalHue.
*
* @param verticalHue
* New value of property verticalHue.
*/
public void setVerticalHue(final boolean verticalHue) {
if (this.verticalHue != verticalHue) {
this.verticalHue = verticalHue;
doChange();
}
}
/**
* Called when a parameter is changed that requires that the spectrum image
* be rebuilt, so that the next time the image is asked for, it will be.
*/
protected void doChange() {
initialized = false;
}
/**
* Setter for the grayStripSize property, which determines the percentage
* (expressed as a float between 0 and 1) of the image height taken up by
* the grayscale strip.
*/
public void setGrayStripSize(final float grayStripSize) {
float workingGrayStripSize = grayStripSize;
if (workingGrayStripSize > 1)
workingGrayStripSize = 1; // handle screwy > 1 values just in case
if (workingGrayStripSize != grayStripSize) {
this.grayStripSize = grayStripSize;
doChange();
}
}
/**
* Getter for the GrayStripSize property, which returns the percentage
* (expressed as a float between 0 and 1) of the height of the image taken
* up by the gray scale strip for selecting non-colored pixels.
*/
public float getGrayStripSize() {
return this.grayStripSize;
}
/**
* Returns the size of the image as a java.awt.Dimension object.
*/
@Override
public Dimension getSize() {
return new Dimension(img.getWidth(), img.getHeight());
}
@Override
public String getNameAt(final int x, final int y) {
final Color c = getColorAt(x, y);
final StringBuffer sb = new StringBuffer();
sb.append(c.getRed());
sb.append(','); // NOI18N
sb.append(c.getGreen());
sb.append(','); // NOI18N
sb.append(c.getBlue());
return sb.toString();
}
private static Palette[] defaultPalettes = null;
/** Create a default set of continuous palettes to use */
public static Palette[] createDefaultPalettes() {
if (defaultPalettes == null) {
defaultPalettes = new Palette[] {
new ContinuousPalette("satLarge", LARGE_SPEC_WIDTH,
LARGE_SPEC_HEIGHT, 1f, false), // NOI18N
new ContinuousPalette("unsatLarge", LARGE_SPEC_WIDTH,
LARGE_SPEC_HEIGHT, 0.4f, false), // NOI18N
new ContinuousPalette("satLargeHoriz", LARGE_SPEC_WIDTH,
LARGE_SPEC_HEIGHT, 1f, true), // NOI18N
new ContinuousPalette("unsatLargeHoriz", LARGE_SPEC_WIDTH,
LARGE_SPEC_HEIGHT, 0.4f, true) // NOI18N
};
}
return defaultPalettes;
}
@Override
public String getDisplayName() {
return ColorChooser.getString(name);
}
@Override
public void setSize(final int w, final int h) {
}
}

View file

@ -0,0 +1,106 @@
/*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at http://www.netbeans.org/cddl.html
* or http://www.netbeans.org/cddl.txt.
*
* When distributing Covered Code, include this CDDL Header Notice in each file
* and include the License file at http://www.netbeans.org/cddl.txt.
* If applicable, add the following below the CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
/**
* Default UI delegate for color choosers. CCBorder handles minor per-look and
* feel differences so we can use one delegate. Note this delegate is stateless
* - there is one instance system-wide. State is kept by the listener - see
* inner class L.
*
* @author Tim Boudreau
*/
final class DefaultColorChooserUI extends ColorChooserUI {
DefaultColorChooserUI() {
}
private static DefaultColorChooserUI INSTANCE = null;
public static ComponentUI createUI(final JComponent jc) {
// assert jc instanceof ColorChooser;
return getDefault();
}
static DefaultColorChooserUI getDefault() {
if (INSTANCE == null) {
INSTANCE = new DefaultColorChooserUI();
}
return INSTANCE;
}
@Override
protected void init(final ColorChooser c) {
c.setToolTipText(getDefaultTooltip());
c.setBorder(new CCBorder());
}
@Override
protected void uninit(final ColorChooser c) {
if (c.getBorder() instanceof CCBorder) {
c.setBorder(null);
}
if (getDefaultTooltip().equals(c.getToolTipText())) {
c.setToolTipText(null);
}
}
private static String getDefaultTooltip() {
return MAC ? ColorChooser.getString("tip.mac") : // NOI18N
ColorChooser.getString("tip"); // NOI18N
}
@Override
public void paint(final Graphics g, final JComponent c) {
final ColorChooser chooser = (ColorChooser) c;
final Color col = chooser.transientColor() != null ? chooser
.transientColor() : chooser.getColor();
g.setColor(col);
g.fillRect(0, 0, chooser.getWidth() - 1, chooser.getHeight() - 1);
if (chooser.hasFocus()) {
g.setColor(invertColor(col));
g.drawRect(4, 4, chooser.getWidth() - 8, chooser.getHeight() - 8);
}
}
// *****************Some utility methods for manipulating colors***********
/** Finds a color that will visually contrast with the selected color */
private static final Color invertColor(final Color c) {
final int r = checkRange(255 - c.getRed());
final int g = checkRange(255 - c.getGreen());
final int b = checkRange(255 - c.getBlue());
return new Color(r, g, b);
}
/**
* Checks to make sure the color component passed is not too close to
* middle-of-the-road, and if so, returns its difference with 128. Used by
* invertColor to make sure that it doesn't, for example, return 129,129,129
* as a color to contrast with 127,127,127.
*/
private static final int checkRange(final int i) {
int result = i;
if (Math.abs(128 - i) < 24) {
result = Math.abs(128 - i);
}
return result;
}
}

View file

@ -0,0 +1,126 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
/**
* An abstract class representing a color which has a name and may provide
* custom code for instantiation. Implements comparable in order to appear in an
* ordered way in palettes. Note that this class is internal to the color
* chooser. It is not acceptable for the color chooser to provide instances of
* NamedColor from its getColor method, since they may be serialized and will
* not be deserializable if their implementation is not on the classpath.
*
* @author Tim Boudreau
*/
abstract class NamedColor extends Color implements Comparable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of NamedColor
*
* @param name
* @param r
* red
* @param g
* green
* @param b
* blue
*/
protected NamedColor(final String name, final int r, final int g,
final int b) {
super(r, g, b);
}
/**
* Get a localized display name for this color if possible. For some colors,
* such as named system colors, a localized variant is not a reasonable
* option.
*
* @return the localized (or not) display name
*/
public abstract String getDisplayName();
/**
* Get the programmatic name, if any, for this color, such as a Swing
* UIDefaults key or an SVG constant name.
*/
public abstract String getName();
/**
* Fetch a java code snippet for instantiating this color. For cases such as
* named defaults from the Swing UIManager, this method might return
* something such as <code>UIManager.getColor(&quot;control&quot;)</code>.
* Useful when implementing a property editor.
*
* @return a string that could be pasted into Java code to instantiate a
* color with these rgb values
*/
public String getInstantiationCode() {
return toString();
}
static NamedColor create(final Color c, final String name) {
return new DefaultNamedColor(c, name);
}
private static final class DefaultNamedColor extends NamedColor {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String name;
public DefaultNamedColor(final Color c, final String name) {
super(name, c.getRed(), c.getGreen(), c.getBlue());
this.name = name;
}
@Override
public String getDisplayName() {
return name;
}
@Override
public String getName() {
return name;
}
public int compareTo(final Object o) {
if (o instanceof NamedColor) {
final NamedColor nc = (NamedColor) o;
final String nm = nc.getDisplayName();
if (nm == null && getDisplayName() == null) {
return 0;
} else {
return nm != null && getDisplayName() != null ? getDisplayName()
.compareTo(nm)
: -1;
}
} else {
return -1;
}
}
}
}

View file

@ -0,0 +1,132 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
/**
* Model for a palette that can be painted, and from which colors may be
* selected. An array of palettes to use may be supplied to a ColorChooser via
* the setPalettes method.
*
* @author Tim Boudreau
*/
public abstract class Palette {
/**
* Returns the color at the specified point, or null if the point is beyond
* the bounds of the palette or in an area that does not indicate a color
*
* @param x
* - an horizontal coordinate in the coordinate space of the
* palette
* @param y
* - a vertical coordinate in the coordinate space of the palette
* @return - a color or null
*/
public abstract Color getColorAt(int x, int y);
/**
* Returns a string description of the color at the point. May be a name or
* a set of RGB values, but should not be longer than 30 characters. Returns
* null if the position is outside the bounds of the palette or has no
* description associated with it. Generally getNameAt() should return null
* from the same coordinates that getColorAt() would.
*
* @param x
* an horizontal coordinate in the coordinate space of the
* palette
* @param y
* a vertical coordinate in the coordinate space of the palette
* @return a string describing the color at this coordinate or null
* @see #getColorAt
*/
public abstract String getNameAt(int x, int y);
/**
* Paint this palette to a graphics context.
*
* @param g
* - a graphics context to paint into
*/
public abstract void paintTo(Graphics g);
/**
* Get the on-screen size of this palette
*
* @return the size of this palette - corresponding to the screen space
* required to display it and defining the coordinate space of this
* palette.
*/
public abstract Dimension getSize();
/**
* Get a localized name for this palette or null if a display name is not
* warranted
*
* @return the display name
*/
public abstract void setSize(int w, int h);
public abstract String getDisplayName();
/**
* Get the default set of 8 palettes used by the color chooser. If
* continuousFirst is true, the first four will be continuous palettes and
* the second four swatches with named colors, system colors, etc.
*/
public static final Palette[] getDefaultPalettes(
final boolean continuousFirst) {
Palette[] result = new Palette[8];
final Palette[] first = continuousFirst ? ContinuousPalette
.createDefaultPalettes() : PredefinedPalette
.createDefaultPalettes();
final Palette[] second = !continuousFirst ? ContinuousPalette
.createDefaultPalettes() : PredefinedPalette
.createDefaultPalettes();
result = new Palette[second.length + first.length];
System.arraycopy(first, 0, result, 0, 4);
System.arraycopy(second, 0, result, 4, 4);
return result;
}
public static final Palette createContinuousPalette(final String name,
final Dimension size, final float saturation) {
if (size.width <= 0)
throw new IllegalArgumentException("width less than or equal 0");
if (size.height <= 0)
throw new IllegalArgumentException("height less than or equal 0");
return new ContinuousPalette(name, size.width, size.height, saturation);
}
public static final Palette createPredefinedPalette(final String name,
final Color[] colors, final String[] names) {
final NamedColor[] cc = new NamedColor[colors.length];
for (int i = 0; i < colors.length; i++) {
cc[i] = NamedColor.create(colors[i], names[i]);
}
return new PredefinedPalette(name, cc);
}
}

View file

@ -0,0 +1,376 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import javax.swing.JComponent;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Encapsulates the logic of a popup palette which can callback a color chooser
* to set its transient color or its final color if the mouse is released over
* the palette.
*
* @author Tim Boudreau
*/
class PalettePopup extends MouseAdapter implements MouseMotionListener,
PropertyChangeListener {
private Popup pop = null;
private PalettePanel panel = null;
private Palette pal = null;
private static Reference defaultInstance = null;
/** Creates a new instance of PalettePopup */
private PalettePopup() {
}
public static PalettePopup getDefault() {
PalettePopup result = null;
if (defaultInstance != null) {
result = (PalettePopup) defaultInstance.get();
}
if (result == null) {
result = new PalettePopup();
defaultInstance = new SoftReference(result);
}
return result;
}
private PalettePanel getPalettePanel() {
if (panel == null) {
panel = new PalettePanel();
}
return panel;
}
public void setPalette(final Palette pal) {
if (pal != this.pal) {
if (isPopupVisible()) {
final Dimension newSize = pal.getSize();
final Dimension oldSize = this.pal.getSize();
if (newSize.equals(oldSize)) {
panel.setPalette(pal);
panel.repaint();
} else {
synchronized (lastOwner.getTreeLock()) {
pop.hide();
panel.setPalette(pal);
pop = PopupFactory.getSharedInstance().getPopup(
lastOwner, getPalettePanel(), lastCoords.x,
lastCoords.y);
pop.show();
}
}
}
this.pal = pal;
}
}
private Palette getPalette() {
return pal;
}
private ColorChooser lastOwner;
private Point lastCoords;
public void showPopup(final ColorChooser owner, final Point coords) {
if (pal == null) {
throw new IllegalStateException("No palette specified");
}
setPopupOwner(owner);
lastCoords = coords;
if (pop != null) {
pop.hide();
pop = null;
}
final PalettePanel pp = getPalettePanel();
pp.setPalette(getPalette());
final Dimension sz = pp.getPreferredSize();
final Rectangle r = owner.getGraphicsConfiguration().getDevice()
.getDefaultConfiguration().getBounds();
final Rectangle test = new Rectangle(coords, sz);
if (!r.contains(test)) {
final int offy = Math.max(0, (test.y + test.height)
- (r.y + r.height));
final int offx = Math.max(0, (test.x + test.width)
- (r.x + r.width));
coords.x -= offx;
coords.y -= offy;
}
pop = PopupFactory.getSharedInstance().getPopup(owner, pp, coords.x,
coords.y);
pop.show();
owner.firePickerVisible(true);
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener(this);
}
private void setPopupOwner(final ColorChooser owner) {
if (lastOwner == owner) {
return;
}
if (lastOwner != null) {
detachFromOwner();
lastOwner.firePickerVisible(false);
}
attachToOwner(owner);
}
private void detachFromOwner() {
if (lastOwner != null) {
lastOwner.removeMouseMotionListener(this);
lastOwner.removeMouseListener(this);
}
lastOwner = null;
}
private void attachToOwner(final ColorChooser owner) {
lastOwner = owner;
owner.addMouseListener(this);
owner.addMouseMotionListener(this);
}
public void hidePopup(final ColorChooser owner) {
if (owner != lastOwner) {
return;
}
hidePopup();
}
private void hidePopup() {
if (pop != null) {
pop.hide();
pop = null;
detachFromOwner();
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.removePropertyChangeListener(this);
}
}
private boolean isPopupVisible() {
return pop != null;
}
public boolean isPopupVisible(final ColorChooser chooser) {
return lastOwner == chooser && isPopupVisible();
}
public void mouseDragged(final java.awt.event.MouseEvent e) {
final Point p = e.getPoint();
SwingUtilities.convertPointToScreen(p, lastOwner);
convertPointToPalette(p);
final Dimension d = panel.getOffset();
if (d != null) {
p.x -= d.width;
p.y -= d.height;
}
if (p.x >= 0 && p.y >= 0 && p.x <= pal.getSize().width
&& p.y < pal.getSize().height) {
lastOwner.setTransientColor(pal.getColorAt(p.x, p.y));
panel.setDisplayTitle(pal.getNameAt(p.x, p.y));
} else {
lastOwner.setTransientColor(null);
panel.setDisplayTitle(null);
}
}
public void mouseMoved(final java.awt.event.MouseEvent e) {
}
private void convertPointToPalette(final Point p) {
p.x -= lastCoords.x;
p.y -= lastCoords.y;
}
public void propertyChange(final PropertyChangeEvent evt) {
if ("focusOwner".equals(evt.getPropertyName())) {
final Object o = evt.getNewValue();
if (o != panel && o != lastOwner) {
hidePopup();
}
}
}
private class PalettePanel extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
private Palette pal = null;
private PalettePanel() {
}
private String title = null;
public void setPalette(final Palette pal) {
Dimension oldSize = null;
if (pal != null && isShowing()) {
oldSize = pal.getSize();
}
this.pal = pal;
if (oldSize != null && pal != null
&& !pal.getSize().equals(oldSize)) {
firePropertyChange("preferredSize", oldSize, pal.getSize()); // NOI18N
}
}
public Dimension getOffset() {
if (pal == null || pal.getDisplayName() == null) {
return null;
}
return new Dimension(0,
((getPreferredSize().height - pal.getSize().height) / 2));
}
@Override
public void paintComponent(final Graphics g) {
final Dimension d = pal.getSize();
final int y = getHeight() - d.height;
if (pal.getDisplayName() != null) {
final GradientPaint gp = new GradientPaint(0, 0, UIManager
.getColor("controlHighlight"), 0, y / 2, UIManager
.getColor("controlShadow"));
((Graphics2D) g).setPaint(gp);
g.fillRect(0, 0, getWidth(), y / 2);
final String s = pal.getDisplayName();
g.setFont(getFont().deriveFont(Font.BOLD,
getFont().getSize() - 2));
final int ht = g.getFontMetrics(g.getFont()).getHeight();
final int wid = g.getFontMetrics(g.getFont()).stringWidth(s);
final int xpos = (getWidth() / 2) - (wid / 2);
g.setColor(UIManager.getColor("controlShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, 0, 0, (y / 2) - 1);
g.drawLine(getWidth() - 1, 0, getWidth() - 1, (y / 2) - 1);
g.setColor(UIManager.getColor("textText"));
g.drawString(s, xpos, ht - 3);
g.translate(0, y / 2);
}
pal.paintTo(g);
final int top = pal.getDisplayName() == null ? y : y / 2;
final int bottom = pal.getDisplayName() == null ? getHeight()
: getHeight() - top;
final GradientPaint gp = new GradientPaint(0, getHeight() - y,
UIManager.getColor("controlHighlight"), 0, bottom,
UIManager.getColor("controlShadow")); // NOI18N
((Graphics2D) g).setPaint(gp);
g.fillRect(0, getHeight() - y, getWidth(), top);
if (title != null) {
g.setColor(UIManager.getColor("textText")); // NOI18N
g.setFont(getFont().deriveFont(Font.PLAIN,
getFont().getSize() - 2));
final int xp = (getWidth() - g.getFontMetrics(g.getFont())
.stringWidth(title)) - 3;
g.drawString(title, xp, getHeight()
- (pal.getDisplayName() == null ? 4 : (y / 2) + 4));
}
g.setColor(UIManager.getColor("controlShadow")); // NOI18N
g.drawLine(0, getHeight() - y, 0, getHeight());
g.drawLine(0, getHeight() - (top + 1), getWidth() - 1, getHeight()
- (top + 1));
g.drawLine(getWidth() - 1, getHeight() - (top + 1), getWidth() - 1,
getHeight() - y);
}
public void setDisplayTitle(final String s) {
if (s != title
&& ((s != null) != (title != null) || ((s != null && !s
.equals(title))))) {
title = s;
repaint();
}
if (s == null && title != null) {
title = null;
repaint();
}
}
@Override
public Dimension getPreferredSize() {
if (pal != null) {
final Dimension result = new Dimension(pal.getSize());
int spacing = 14;
if (lastOwner != null) {
Graphics g = lastOwner.getGraphics();
if (g == null) {
try {
g = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration()
.createCompatibleImage(1, 1)
.createGraphics();
} catch (final SecurityException e) {
g = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB)
.createGraphics();
}
}
if (g != null) {
Font f = getFont() == null ? UIManager
.getFont("controlFont") : getFont();
if (f == null) {
f = new Font("Serif", Font.PLAIN, 12);
}
spacing = g.getFontMetrics(
f.deriveFont(Font.PLAIN, f.getSize() - 2))
.getHeight();
}
g.dispose();
}
if (pal.getDisplayName() != null) {
spacing *= 2;
}
result.height += spacing;
return result;
} else {
return new Dimension(10, 10);
}
}
}
}

View file

@ -0,0 +1,680 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.util.Arrays;
import javax.swing.UIManager;
/**
* A palette of swatches with predefined colors
*
* @author Tim Boudreau
*/
class PredefinedPalette extends Palette {
NamedColor[] colors;
private int swatchSize = 11;
private final int gap = 1;
private static final Rectangle scratch = new Rectangle();
private final String name;
/** Creates a new instance of PredefinedPalette */
public PredefinedPalette(final String name, final NamedColor[] colors) {
this.colors = colors;
this.name = name;
Arrays.sort(colors);
if (colors.length < 14) {
swatchSize = 24;
} else if (colors.length < 40) {
swatchSize = 16;
}
}
@Override
public java.awt.Color getColorAt(final int x, final int y) {
Color result = null;
final int idx = indexForPoint(x, y);
if (idx != -1 && idx < colors.length) {
result = colors[idx];
}
return result;
}
@Override
public void paintTo(final java.awt.Graphics g) {
g.setColor(Color.BLACK);
final Dimension size = getSize();
g.fillRect(0, 0, size.width, size.height);
for (int i = 0; i < colors.length; i++) {
final Color c = colors[i];
rectForIndex(i, scratch);
g.setColor(c);
g.fillRect(scratch.x, scratch.y, scratch.width, scratch.height);
if (Color.BLACK.equals(c)) {
g.setColor(Color.GRAY);
} else {
g.setColor(c.brighter());
}
g.drawLine(scratch.x, scratch.y, scratch.x + scratch.width - 1,
scratch.y);
g.drawLine(scratch.x, scratch.y, scratch.x, scratch.y
+ scratch.height - 1);
if (Color.BLACK.equals(c)) {
g.setColor(Color.GRAY.darker());
} else {
g.setColor(c.darker());
}
g.drawLine(scratch.x + scratch.width - 1, scratch.y
+ scratch.height - 1, scratch.width + scratch.x - 1,
scratch.y + 1);
g.drawLine(scratch.x + scratch.width - 1, scratch.y
+ scratch.height - 1, scratch.x, scratch.y + scratch.height
- 1);
}
}
@Override
public String getNameAt(final int x, final int y) {
final NamedColor nc = (NamedColor) getColorAt(x, y);
if (nc != null) {
return nc.getDisplayName();
} else {
return null;
}
}
protected int getCount() {
return colors.length;
}
Dimension calcSize() {
final int count = colors.length;
final int perRow = (int) Math.round(Math.sqrt(count));
final int perCol = (perRow * perRow >= count) ? perRow : perRow + 1;
final int width = perCol * (swatchSize + gap) + gap;
final int height = perRow * (swatchSize + gap) + gap;
final Dimension result = new Dimension(width, height);
return result;
}
private Dimension size = null;
@Override
public Dimension getSize() {
if (size == null) {
size = calcSize();
}
return size;
}
@Override
public void setSize(final int w, final int h) {
size = new Dimension(w, h);
}
private int indexForPoint(final int x, final int y) {
final Dimension d = getSize();
if (y > d.height || x > d.width || y < 0 || x < 0) {
return -1;
}
final int perRow = d.width / (swatchSize + gap);
final int col = x / (swatchSize + gap);
final int row = y / (swatchSize + gap);
return (row * perRow) + col;
}
private void rectForIndex(final int idx, final Rectangle r) {
final Dimension d = getSize();
final int rectsPerRow = d.width / (swatchSize + gap);
r.x = gap + ((swatchSize + gap) * (idx % rectsPerRow));
r.y = gap + ((swatchSize + gap) * (idx / rectsPerRow));
r.width = swatchSize;
r.height = swatchSize;
}
private static Palette[] predefined = null;
public static Palette[] createDefaultPalettes() {
if (predefined == null) {
predefined = makePal();
}
return predefined;
}
private static final Palette[] makePal() {
final Palette[] result = new Palette[] {
new PredefinedPalette("svg", SVGColors),
new PredefinedPalette("system", getSystemColors()),
RecentColors.getDefault(),
new PredefinedPalette("swing", getSwingColors()) };
return result;
}
static class BasicNamedColor extends NamedColor implements Comparable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String name;
public BasicNamedColor(final String name, final int r, final int g,
final int b) {
super(name, r, g, b);
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String getDisplayName() {
return ColorChooser.getString(getName());
}
@Override
public String toString() {
return "new java.awt.Color(" + getRed() + "," + getGreen() + ","
+ getBlue() + ")";
}
public int compareTo(final Object o) {
final Color c = (Color) o;
// maybe average rgb & compare?
final int result = avgColor(c) - avgColor(this);
return result;
}
@Override
public String getInstantiationCode() {
return toString();
}
}
private static int avgColor(final Color c) {
return (c.getRed() + c.getGreen() + c.getBlue()) / 3;
}
@Override
public String getDisplayName() {
return ColorChooser.getString(name);
}
static String getColorName(final Color c) {
for (final SwingColor swingColor : swingColors) {
if (equals(swingColor, c)) {
return swingColor.getDisplayName();
}
}
for (final NamedColor color : SVGColors) {
if (equals(color, c)) {
return color.getDisplayName();
}
}
return null;
}
static boolean equals(final Color a, final Color b) {
return a.getRGB() == b.getRGB();
}
private static final NamedColor[] SVGColors = new BasicNamedColor[] {
new BasicNamedColor("aliceblue", 240, 248, 255),
new BasicNamedColor("antiquewhite", 250, 235, 215),
new BasicNamedColor("aqua", 0, 255, 255),
new BasicNamedColor("aquamarine", 127, 255, 212),
new BasicNamedColor("azure", 240, 255, 255),
new BasicNamedColor("beige", 245, 245, 220),
new BasicNamedColor("bisque", 255, 228, 196),
new BasicNamedColor("black", 0, 0, 0),
new BasicNamedColor("blanchedalmond", 255, 235, 205),
new BasicNamedColor("blue", 0, 0, 255),
new BasicNamedColor("blueviolet", 138, 43, 226),
new BasicNamedColor("brown", 165, 42, 42),
new BasicNamedColor("burlywood", 222, 184, 135),
new BasicNamedColor("cadetblue", 95, 158, 160),
new BasicNamedColor("chartreuse", 127, 255, 0),
new BasicNamedColor("chocolate", 210, 105, 30),
new BasicNamedColor("coral", 255, 127, 80),
new BasicNamedColor("cornflowerblue", 100, 149, 237),
new BasicNamedColor("cornsilk", 255, 248, 220),
new BasicNamedColor("crimson", 220, 20, 60),
new BasicNamedColor("cyan", 0, 255, 255),
new BasicNamedColor("darkblue", 0, 0, 139),
new BasicNamedColor("darkcyan", 0, 139, 139),
new BasicNamedColor("darkgoldenrod", 184, 134, 11),
new BasicNamedColor("darkgray", 169, 169, 169),
new BasicNamedColor("darkgreen", 0, 100, 0),
new BasicNamedColor("darkgrey", 169, 169, 169),
new BasicNamedColor("darkkhaki", 189, 183, 107),
new BasicNamedColor("darkmagenta", 139, 0, 139),
new BasicNamedColor("darkolivegreen", 85, 107, 47),
new BasicNamedColor("darkorange", 255, 140, 0),
new BasicNamedColor("darkorchid", 153, 50, 204),
new BasicNamedColor("darkred", 139, 0, 0),
new BasicNamedColor("darksalmon", 233, 150, 122),
new BasicNamedColor("darkseagreen", 143, 188, 143),
new BasicNamedColor("darkslateblue", 72, 61, 139),
new BasicNamedColor("darkslategray", 47, 79, 79),
new BasicNamedColor("darkslategrey", 47, 79, 79),
new BasicNamedColor("darkturquoise", 0, 206, 209),
new BasicNamedColor("darkviolet", 148, 0, 211),
new BasicNamedColor("deeppink", 255, 20, 147),
new BasicNamedColor("deepskyblue", 0, 191, 255),
new BasicNamedColor("dimgray", 105, 105, 105),
new BasicNamedColor("dimgrey", 105, 105, 105),
new BasicNamedColor("dodgerblue", 30, 144, 255),
new BasicNamedColor("firebrick", 178, 34, 34),
new BasicNamedColor("floralwhite", 255, 250, 240),
new BasicNamedColor("forestgreen", 34, 139, 34),
new BasicNamedColor("fuchsia", 255, 0, 255),
new BasicNamedColor("gainsboro", 220, 220, 220),
new BasicNamedColor("ghostwhite", 248, 248, 255),
new BasicNamedColor("gold", 255, 215, 0),
new BasicNamedColor("goldenrod", 218, 165, 32),
new BasicNamedColor("gray", 128, 128, 128),
new BasicNamedColor("grey", 128, 128, 128),
new BasicNamedColor("green", 0, 128, 0),
new BasicNamedColor("greenyellow", 173, 255, 47),
new BasicNamedColor("honeydew", 240, 255, 240),
new BasicNamedColor("hotpink", 255, 105, 180),
new BasicNamedColor("indianred", 205, 92, 92),
new BasicNamedColor("indigo", 75, 0, 130),
new BasicNamedColor("ivory", 255, 255, 240),
new BasicNamedColor("khaki", 240, 230, 140),
new BasicNamedColor("lavender", 230, 230, 250),
new BasicNamedColor("lavenderblush", 255, 240, 245),
new BasicNamedColor("lawngreen", 124, 252, 0),
new BasicNamedColor("lemonchiffon", 255, 250, 205),
new BasicNamedColor("lightblue", 173, 216, 230),
new BasicNamedColor("lightcoral", 240, 128, 128),
new BasicNamedColor("lightcyan", 224, 255, 255),
new BasicNamedColor("lightgoldenrodyellow", 250, 250, 210),
new BasicNamedColor("lightgray", 211, 211, 211),
new BasicNamedColor("lightgreen", 144, 238, 144),
new BasicNamedColor("lightgrey", 211, 211, 211),
new BasicNamedColor("lightpink", 255, 182, 193),
new BasicNamedColor("lightsalmon", 255, 160, 122),
new BasicNamedColor("lightseagreen", 32, 178, 170),
new BasicNamedColor("lightskyblue", 135, 206, 250),
new BasicNamedColor("lightslategray", 119, 136, 153),
new BasicNamedColor("lightslategrey", 119, 136, 153),
new BasicNamedColor("lightsteelblue", 176, 196, 222),
new BasicNamedColor("lightyellow", 255, 255, 224),
new BasicNamedColor("lime", 0, 255, 0),
new BasicNamedColor("limegreen", 50, 205, 50),
new BasicNamedColor("linen", 250, 240, 230),
new BasicNamedColor("magenta", 255, 0, 255),
new BasicNamedColor("maroon", 128, 0, 0),
new BasicNamedColor("mediumaquamarine", 102, 205, 170),
new BasicNamedColor("mediumblue", 0, 0, 205),
new BasicNamedColor("mediumorchid", 186, 85, 211),
new BasicNamedColor("mediumpurple", 147, 112, 219),
new BasicNamedColor("mediumseagreen", 60, 179, 113),
new BasicNamedColor("mediumslateblue", 123, 104, 238),
new BasicNamedColor("mediumspringgreen", 0, 250, 154),
new BasicNamedColor("mediumturquoise", 72, 209, 204),
new BasicNamedColor("mediumvioletred", 199, 21, 133),
new BasicNamedColor("midnightblue", 25, 25, 112),
new BasicNamedColor("mintcream", 245, 255, 250),
new BasicNamedColor("mistyrose", 255, 228, 225),
new BasicNamedColor("moccasin", 255, 228, 181),
new BasicNamedColor("navajowhite", 255, 222, 173),
new BasicNamedColor("navy", 0, 0, 128),
new BasicNamedColor("oldlace", 253, 245, 230),
new BasicNamedColor("olive", 128, 128, 0),
new BasicNamedColor("olivedrab", 107, 142, 35),
new BasicNamedColor("orange", 255, 165, 0),
new BasicNamedColor("orangered", 255, 69, 0),
new BasicNamedColor("orchid", 218, 112, 214),
new BasicNamedColor("palegoldenrod", 238, 232, 170),
new BasicNamedColor("palegreen", 152, 251, 152),
new BasicNamedColor("paleturquoise", 175, 238, 238),
new BasicNamedColor("palevioletred", 219, 112, 147),
new BasicNamedColor("papayawhip", 255, 239, 213),
new BasicNamedColor("peachpuff", 255, 218, 185),
new BasicNamedColor("peru", 205, 133, 63),
new BasicNamedColor("pink", 255, 192, 203),
new BasicNamedColor("plum", 221, 160, 221),
new BasicNamedColor("powderblue", 176, 224, 230),
new BasicNamedColor("purple", 128, 0, 128),
new BasicNamedColor("red", 255, 0, 0),
new BasicNamedColor("rosybrown", 188, 143, 143),
new BasicNamedColor("royalblue", 65, 105, 225),
new BasicNamedColor("saddlebrown", 139, 69, 19),
new BasicNamedColor("salmon", 250, 128, 114),
new BasicNamedColor("sandybrown", 244, 164, 96),
new BasicNamedColor("seagreen", 46, 139, 87),
new BasicNamedColor("seashell", 255, 245, 238),
new BasicNamedColor("sienna", 160, 82, 45),
new BasicNamedColor("silver", 192, 192, 192),
new BasicNamedColor("skyblue", 135, 206, 235),
new BasicNamedColor("slateblue", 106, 90, 205),
new BasicNamedColor("slategray", 112, 128, 144),
new BasicNamedColor("slategrey", 112, 128, 144),
new BasicNamedColor("snow", 255, 250, 250),
new BasicNamedColor("springgreen", 0, 255, 127),
new BasicNamedColor("steelblue", 70, 130, 180),
new BasicNamedColor("tan", 210, 180, 140),
new BasicNamedColor("teal", 0, 128, 128),
new BasicNamedColor("thistle", 216, 191, 216),
new BasicNamedColor("tomato", 255, 99, 71),
new BasicNamedColor("turquoise", 64, 224, 208),
new BasicNamedColor("violet", 238, 130, 238),
new BasicNamedColor("wheat", 245, 222, 179),
new BasicNamedColor("white", 255, 255, 255),
new BasicNamedColor("whitesmoke", 245, 245, 245),
new BasicNamedColor("yellow", 255, 255, 0),
new BasicNamedColor("yellowgreen", 154, 205, 50) }; // NOI18N
static class SwingColor extends BasicNamedColor {
/**
*
*/
private static final long serialVersionUID = 1L;
public SwingColor(final String name, final int r, final int g,
final int b) {
super(name, r, g, b);
}
@Override
public String toString() {
return "UIManager.getColor(" + getName() + ")";
}
@Override
public String getDisplayName() {
return getName();
}
@Override
public String getInstantiationCode() {
return toString();
}
}
private static SwingColor[] swingColors = null;
private static SwingColor[] getSwingColors() {
if (swingColors != null) {
return swingColors;
}
final java.util.List l = new java.util.ArrayList();
Color c;
c = UIManager.getColor("windowText");
if (c != null) {
l.add(new SwingColor("windowText", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("activeCaptionBorder");
if (c != null) {
l.add(new SwingColor("activeCaptionBorder", c.getRed(), c
.getGreen(), c.getBlue()));
}
c = UIManager.getColor("inactiveCaptionText");
if (c != null) {
l.add(new SwingColor("inactiveCaptionText", c.getRed(), c
.getGreen(), c.getBlue()));
}
c = UIManager.getColor("controlLtHighlight");
if (c != null) {
l.add(new SwingColor("controlLtHighlight", c.getRed(),
c.getGreen(), c.getBlue()));
}
c = UIManager.getColor("inactiveCaptionBorder");
if (c != null) {
l.add(new SwingColor("inactiveCaptionBorder", c.getRed(), c
.getGreen(), c.getBlue()));
}
c = UIManager.getColor("textInactiveText");
if (c != null) {
l.add(new SwingColor("textInactiveText", c.getRed(), c.getGreen(),
c.getBlue()));
}
c = UIManager.getColor("control");
if (c != null) {
l.add(new SwingColor("control", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("textText");
if (c != null) {
l.add(new SwingColor("textText", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("menu");
if (c != null) {
l
.add(new SwingColor("menu", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("windowBorder");
if (c != null) {
l.add(new SwingColor("windowBorder", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("infoText");
if (c != null) {
l.add(new SwingColor("infoText", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("menuText");
if (c != null) {
l.add(new SwingColor("menuText", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("textHighlightText");
if (c != null) {
l.add(new SwingColor("textHighlightText", c.getRed(), c.getGreen(),
c.getBlue()));
}
c = UIManager.getColor("activeCaptionText");
if (c != null) {
l.add(new SwingColor("activeCaptionText", c.getRed(), c.getGreen(),
c.getBlue()));
}
c = UIManager.getColor("textHighlight");
if (c != null) {
l.add(new SwingColor("textHighlight", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("controlShadow");
if (c != null) {
l.add(new SwingColor("controlShadow", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("controlText");
if (c != null) {
l.add(new SwingColor("controlText", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("menuPressedItemF");
if (c != null) {
l.add(new SwingColor("menuPressedItemF", c.getRed(), c.getGreen(),
c.getBlue()));
}
c = UIManager.getColor("menuPressedItemB");
if (c != null) {
l.add(new SwingColor("menuPressedItemB", c.getRed(), c.getGreen(),
c.getBlue()));
}
c = UIManager.getColor("info");
if (c != null) {
l
.add(new SwingColor("info", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("controlHighlight");
if (c != null) {
l.add(new SwingColor("controlHighlight", c.getRed(), c.getGreen(),
c.getBlue()));
}
c = UIManager.getColor("scrollbar");
if (c != null) {
l.add(new SwingColor("scrollbar", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("window");
if (c != null) {
l.add(new SwingColor("window", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("inactiveCaption");
if (c != null) {
l.add(new SwingColor("inactiveCaption", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("controlDkShadow");
if (c != null) {
l.add(new SwingColor("controlDkShadow", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("activeCaption");
if (c != null) {
l.add(new SwingColor("activeCaption", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("text");
if (c != null) {
l
.add(new SwingColor("text", c.getRed(), c.getGreen(), c
.getBlue()));
}
c = UIManager.getColor("desktop");
if (c != null) {
l.add(new SwingColor("desktop", c.getRed(), c.getGreen(), c
.getBlue()));
}
swingColors = (SwingColor[]) l.toArray(new SwingColor[0]);
return swingColors;
}
/**
* Names of system colors. <em>Note:</em> not localizable, those names
* corresponds to programatical names.
*/
private static final String systemGenerate[] = { "activeCaption",
"activeCaptionBorder", // NOI18N
"activeCaptionText", "control", "controlDkShadow", // NOI18N
"controlHighlight", "controlLtHighlight", // NOI18N
"controlShadow", "controlText", "desktop", // NOI18N
"inactiveCaption", "inactiveCaptionBorder", // NOI18N
"inactiveCaptionText", "info", "infoText", "menu", // NOI18N
"menuText", "scrollbar", "text", "textHighlight", // NOI18N
"textHighlightText", "textInactiveText", "textText", // NOI18N
"window", "windowBorder", "windowText" }; // NOI18N
/** System colors used in System Palette. */
private static final Color sColors[] = { SystemColor.activeCaption,
SystemColor.activeCaptionBorder, SystemColor.activeCaptionText,
SystemColor.control, SystemColor.controlDkShadow,
SystemColor.controlHighlight, SystemColor.controlLtHighlight,
SystemColor.controlShadow, SystemColor.controlText,
SystemColor.desktop, SystemColor.inactiveCaption,
SystemColor.inactiveCaptionBorder, SystemColor.inactiveCaptionText,
SystemColor.info, SystemColor.infoText, SystemColor.menu,
SystemColor.menuText, SystemColor.scrollbar, SystemColor.text,
SystemColor.textHighlight, SystemColor.textHighlightText,
SystemColor.textInactiveText, SystemColor.textText,
SystemColor.window, SystemColor.windowBorder,
SystemColor.windowText };
private static class SysColor extends BasicNamedColor {
/**
*
*/
private static final long serialVersionUID = 1L;
public SysColor(final String name, final Color scolor) {
super(name, scolor.getRed(), scolor.getGreen(), scolor.getBlue());
}
@Override
public String toString() {
return "SystemColor." + getName();
}
@Override
public String getDisplayName() {
return getName();
}
}
private static NamedColor[] systemColors = null;
private static NamedColor[] getSystemColors() {
if (systemColors == null) {
systemColors = new BasicNamedColor[sColors.length];
for (int i = 0; i < sColors.length; i++) {
systemColors[i] = new SysColor(systemGenerate[i], sColors[i]);
}
}
return systemColors;
}
/*
* //A cheap and cheesy way to quickly make an English-localized bundle for
* //an array of NamedColor. public static void main(String args[]) { for
* (int i=0; i < SVGColors.length; i++) { System.out.println("# " +
* SVGColors[i].getRed() + "," + SVGColors[i].getGreen() + "," +
* SVGColors[i].getBlue()); String name = SVGColors[i].getName();
* StringBuffer sb = new StringBuffer(name); sb.replace (0, 1, new
* String(new char[]{Character.toUpperCase(name.charAt(0))})); String
* dispName = sb.toString();
*
* for (int k=0; k < tros.length; k++) { String lookFor = tros[k];
* StringBuffer sb2 = new StringBuffer(lookFor); sb.replace (0, 1, new
* String(new char[]{Character.toUpperCase(lookFor.charAt(0))})); String
* replaceWith = " " + sb2.toString(); dispName =
* org.openide.util.Utilities.replaceString( dispName, tros[k],
* replaceWith); }
*
* System.out.println(SVGColors[i].getName() + "=" + dispName); } }
*
* private static String[] tros = new String[] { "brown", "blue", "red",
* "violet", "orchid", "green", "yellow", "orange", "black", "gray", "grey",
* "white", "maroon", "goldenrod", "cream", "spring", "purple", "sea",
* "magenta", "steel", "slate","pink", "cyan", "chiffon", "coral", "wheat",
* "blush", "brick","olive","khaki", "silk","crimson","wood","almond",
* "smoke", "puff", "whip", "peach", "lace",
* "rose","turquoise","aquamarine","salmon", "sky" };
*/
/**
* //some boilerplate to make a list of swing colors public static void main
* (String[] args) { javax.swing.LookAndFeel lf = new
* javax.swing.plaf.metal.MetalLookAndFeel(); javax.swing.UIDefaults def =
* javax.swing.UIManager.getLookAndFeel().getDefaults(); java.util.Iterator
* i = new java.util.ArrayList(def.keySet()).iterator(); while (i.hasNext())
* { Object o = i.next(); // System.err.println(o); Object result =
* def.get(o); if (result instanceof Color) { String s = o.toString(); if
* (s.indexOf(".") == -1) { System.err.println("c = UIManager.getColor(\"" +
* s +"\");\nif (c != null) {\n l.add(new SwingColor(\"" + s +
* "\", c.getRed(), c.getGreen(), c.getBlue()));\n}"); } } }
* System.err.println("Done"); }
*/
}

View file

@ -0,0 +1,331 @@
/*DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2006-2008. Tim Boudreau. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. This particular file is designated
* as subject to the "Classpath" exception as provided
* in the GPL Version 2 section of the License file that
* accompanied this code.
*/
package net.java.dev.colorchooser;
import java.awt.Color;
import java.awt.Dimension;
import java.security.AccessControlException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.prefs.Preferences;
/**
* Palette implementation that can have recent colors added to it.
*
* @author Tim Boudreau
*/
class RecentColors extends Palette {
private Palette palette;
private boolean changed=true;
/** Creates a new instance of RecentColors */
private RecentColors() {
}
private Palette getWrapped() {
if (changed||palette==null) {
palette=createPalette();
changed=false;
}
return palette;
}
@Override
public java.awt.Color getColorAt(final int x, final int y) {
return getWrapped().getColorAt(x, y);
}
@Override
public String getDisplayName() {
try {
return ResourceBundle.getBundle(
"org.netbeans.swing.colorchooser.Bundle").getString(
"recent"); // NOI18N
} catch (final MissingResourceException mre) {
// mre.printStackTrace();
return "Recent colors";
}
}
@Override
public Dimension getSize() {
final Dimension result=((PredefinedPalette) getWrapped()).calcSize();
return result;
}
@Override
public void paintTo(final java.awt.Graphics g) {
getWrapped().paintTo(g);
}
@Override
public String getNameAt(final int x, final int y) {
return getWrapped().getNameAt(x, y);
}
Stack stack=new Stack();
void add(final Color c) {
if (c instanceof RecentColor) {
return;
}
if (stack.indexOf(c)==-1) {
final String name=c instanceof PredefinedPalette.BasicNamedColor?((PredefinedPalette.BasicNamedColor) c).getDisplayName()
:null;
final String toString=c instanceof PredefinedPalette.BasicNamedColor?((PredefinedPalette.BasicNamedColor) c).toString()
:null;
final Color col=new RecentColor(name, c.getRed(), c.getGreen(), c.getBlue(), toString);
stack.push(col);
changed=true;
palette=null;
if (c instanceof NamedColor) {
addToNameCache((NamedColor) c);
}
saveToPrefs();
}
}
public static final String INNER_DELIMITER="^$";
public static final String OUTER_DELIMITER="!*";
public void saveToPrefs() {
final Preferences prefs=getPreferences();
if (prefs==null) {
return;
}
int count=0;
final StringBuffer sb=new StringBuffer();
final Stack stack=new Stack();
stack.addAll(this.stack);
while (!stack.isEmpty()&&count<64) {
count++;
final Color c=(Color) stack.pop();
if (c instanceof DummyColor) {
break;
}
String name="null";
if (c instanceof PredefinedPalette.BasicNamedColor) {
final PredefinedPalette.BasicNamedColor nc=(PredefinedPalette.BasicNamedColor) c;
name=nc.getDisplayName();
}
if (name=="null") { // NOI18N
name=null;
}
sb.append(name);
sb.append(INNER_DELIMITER);
sb.append(c.getRed());
sb.append(INNER_DELIMITER);
sb.append(c.getGreen());
sb.append(INNER_DELIMITER);
sb.append(c.getBlue());
sb.append(INNER_DELIMITER);
if (c instanceof PredefinedPalette.BasicNamedColor) {
sb.append(c.toString());
} else {
sb.append('x');
}
sb.append(OUTER_DELIMITER); // NOI18N
}
prefs.put("recentColors", sb.toString()); // NOI18N
}
static Map namedMap=null;
static NamedColor findNamedColor(final Color color) {
if (namedMap==null) {
return null;
}
final NamedColor result=(NamedColor) namedMap.get(new Integer(color.getRGB()));
return result;
}
static void addToNameCache(final NamedColor color) {
if (namedMap==null) {
namedMap=new HashMap(40);
}
namedMap.put(new Integer(color.getRGB()), color);
}
private Preferences getPreferences() {
try {
final Preferences base=Preferences.userNodeForPackage(getClass());
return base.node("1.5"); // NOI18N
} catch (final Exception ace) {
return null;
}
}
public void loadFromPrefs() {
final Preferences prefs=getPreferences();
if (prefs==null) {
return;
}
final String s=prefs.get("recentColors", null); // NOI18N
stack=new Stack();
final Color[] col=new Color[64];
Arrays.fill(col, new DummyColor());
int count=63;
try {
if (s!=null) {
// a weird but highly unlikely delimiter
final StringTokenizer tok=new StringTokenizer(s,
OUTER_DELIMITER); // NOI18N
while (tok.hasMoreTokens()&&count>=0) {
final String curr=tok.nextToken();
// another weird but highly unlikely delimiter
final StringTokenizer tk2=new StringTokenizer(curr,
INNER_DELIMITER); // NOI18N
while (tk2.hasMoreTokens()) {
String name=tk2.nextToken();
if ("null".equals(name)) {
name=null;
}
final int r=Integer.parseInt(tk2.nextToken());
final int g=Integer.parseInt(tk2.nextToken());
final int b=Integer.parseInt(tk2.nextToken());
final String toString=tk2.nextToken();
if ("x".equals(toString)) { // NOI18N
col[count]=new RecentColor(name, r, g, b);
} else {
col[count]=new RecentColor(name, r, g, b,
toString);
}
addToNameCache((NamedColor) col[count]);
}
count--;
}
}
stack.addAll(Arrays.asList(col));
} catch (final Exception e) {
System.err.println("Error loading color preferences"); // NOI18N
e.printStackTrace();
}
}
private Palette createPalette() {
final PredefinedPalette.BasicNamedColor[] nc=(PredefinedPalette.BasicNamedColor[]) stack.toArray(new PredefinedPalette.BasicNamedColor[0]);
return new PredefinedPalette("", nc); // NOI18N
}
private class RecentColor extends PredefinedPalette.BasicNamedColor {
/**
*
*/
private static final long serialVersionUID=1L;
String displayName;
String toString=null;
public RecentColor(final String name, final int r, final int g,
final int b) {
super(name, r, g, b);
displayName=name;
}
public RecentColor(final String name, final int r, final int g,
final int b, final String toString) {
this(name, r, g, b);
displayName=name;
this.toString=toString;
}
@Override
public int compareTo(final Object o) {
return stack.indexOf(o)-stack.indexOf(this);
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public boolean equals(final Object o) {
if (o instanceof Color) {
final Color c=(Color) o;
return c.getRGB()==getRGB();
}
return false;
}
@Override
public int hashCode() {
return getRGB();
}
@Override
public String toString() {
if (toString!=null) {
return toString;
} else {
return "new java.awt.Color("+getRed()+","+getGreen()
+","+getBlue()+")"; // NOI18N
}
}
}
private static RecentColors defaultInstance=null;
public static final RecentColors getDefault() {
if (defaultInstance==null) {
defaultInstance=new RecentColors();
((RecentColors) defaultInstance).loadFromPrefs();
}
return defaultInstance;
}
/**
* A stand in for colors to fill up the array of recent colors until we
* really have something to put there.
*/
private class DummyColor extends RecentColor {
/**
*
*/
private static final long serialVersionUID=1L;
public DummyColor() {
super(null, 0, 0, 0);
}
@Override
public String getDisplayName() {
return null;
}
// Ensure that no color will match this, so black swing colors can
// be put into the recent colors array
@Override
public boolean equals(final Object o) {
return o==this;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
}
@Override
public void setSize(final int w, final int h) {
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 560 B