use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class Resources method loadTheme.
Hashtable loadTheme(String id, boolean newerVersion) throws IOException {
Hashtable theme = new Hashtable();
String densityStr = Display.getInstance().getDensityStr();
String platformName = Display.getInstance().getPlatformName();
if ("HTML5".equals(platformName)) {
platformName = Display.getInstance().getProperty("HTML5.platformName", "mac");
}
String deviceType = Display.getInstance().isDesktop() ? "desktop" : Display.getInstance().isTablet() ? "tablet" : "phone";
String platformPrefix = "platform-" + platformName + "-";
String densityPrefix = "density-" + densityStr + "-";
String devicePrefix = "device-" + deviceType + "-";
String platformDensityPrefix = platformPrefix + densityPrefix;
String devicePlatformPrefix = devicePrefix + platformPrefix;
String devicePlatformDensityPrefix = devicePlatformPrefix + densityPrefix;
theme.put("name", id);
// marks the theme as uninitialized so we can finish "wiring" cached resources
theme.put("uninitialized", Boolean.TRUE);
int size = input.readShort();
List<String> fontKeys = new ArrayList<String>();
Map<String, Float> fontScaleRules = null;
class MediaRule {
int matchCount;
int bestMatchScore;
String rawKey;
String translatedKey;
}
Map<String, MediaRule> mediaRules = new HashMap<String, MediaRule>();
int defaultFontSizeSetPriority = 0;
for (int iter = 0; iter < size; iter++) {
String key = input.readUTF();
if (key.startsWith("@")) {
theme.put(key, input.readUTF());
if (enableMediaQueries) {
if (key.endsWith("-font-scale")) {
if (fontScaleRules == null) {
fontScaleRules = new LinkedHashMap<String, Float>();
}
fontScaleRules.put(key, Float.parseFloat((String) theme.get(key)));
}
}
if (key.equals("@defaultFontSizeInt") && defaultFontSizeSetPriority < 1) {
int themeMedianFontSize = Integer.parseInt((String) theme.get(key));
if (themeMedianFontSize > 0) {
double adjustedFontSize = themeMedianFontSize * CN.convertToPixels(1f) * 25.4 / (CN.isDesktop() ? 96f : 160f);
Font.setDefaultFont(Font.createTrueTypeFont(Font.NATIVE_MAIN_REGULAR, (float) adjustedFontSize / CN.convertToPixels(1f)));
defaultFontSizeSetPriority = 1;
}
}
if (CN.isTablet() && key.equals("@defaultTabletFontSizeInt") && defaultFontSizeSetPriority < 2) {
int themeMedianFontSize = Integer.parseInt((String) theme.get(key));
if (themeMedianFontSize > 0) {
double adjustedFontSize = themeMedianFontSize * CN.convertToPixels(1f) * 25.4 / (CN.isDesktop() ? 96f : 160f);
Font.setDefaultFont(Font.createTrueTypeFont(Font.NATIVE_MAIN_REGULAR, (float) adjustedFontSize / CN.convertToPixels(1f)));
defaultFontSizeSetPriority = 2;
}
}
if (CN.isDesktop() && key.equals("@defaultDesktopFontSizeInt") && defaultFontSizeSetPriority < 3) {
int themeMedianFontSize = Integer.parseInt((String) theme.get(key));
if (themeMedianFontSize > 0) {
double adjustedFontSize = themeMedianFontSize * CN.convertToPixels(1f) * 25.4 / (CN.isDesktop() ? 96f : 160f);
Font.setDefaultFont(Font.createTrueTypeFont(Font.NATIVE_MAIN_REGULAR, (float) adjustedFontSize / CN.convertToPixels(1f)));
defaultFontSizeSetPriority = 3;
}
}
continue;
}
if (enableMediaQueries) {
String subkey = key;
boolean mediaMatch = true;
int matchCount = 0;
int bestMatchScore = 0;
if (subkey.startsWith("device-")) {
if (!subkey.startsWith(devicePrefix)) {
mediaMatch = false;
} else {
subkey = subkey.substring(devicePrefix.length());
matchCount++;
bestMatchScore = Math.max(50, bestMatchScore);
}
}
if (mediaMatch && subkey.startsWith("platform-")) {
if (!subkey.startsWith(platformPrefix)) {
mediaMatch = false;
} else {
subkey = subkey.substring(platformPrefix.length());
matchCount++;
bestMatchScore = Math.max(100, bestMatchScore);
}
}
if (mediaMatch && subkey.startsWith("density-")) {
if (!subkey.startsWith(densityPrefix)) {
mediaMatch = false;
} else {
subkey = subkey.substring(densityPrefix.length());
matchCount++;
bestMatchScore = Math.max(10, bestMatchScore);
}
}
if (mediaMatch) {
if (mediaRules == null) {
mediaRules = new HashMap<String, MediaRule>();
}
MediaRule rule = mediaRules.get(subkey);
boolean replace = false;
if (rule == null) {
replace = true;
}
if (!replace && rule.matchCount <= matchCount) {
replace = true;
}
if (!replace && rule.bestMatchScore <= bestMatchScore) {
replace = true;
}
if (replace) {
if (rule == null) {
rule = new MediaRule();
mediaRules.put(subkey, rule);
}
rule.bestMatchScore = bestMatchScore;
rule.matchCount = matchCount;
rule.rawKey = key;
rule.translatedKey = subkey;
}
}
}
// if this is a simple numeric value
if (key.endsWith("Color")) {
theme.put(key, Integer.toHexString(input.readInt()));
continue;
}
if (key.endsWith("align") || key.endsWith("textDecoration")) {
theme.put(key, new Integer(input.readShort()));
continue;
}
// if this is a short numeric value for transparency
if (key.endsWith("ransparency")) {
theme.put(key, "" + (input.readByte() & 0xff));
continue;
}
if (key.endsWith("fgAlpha")) {
theme.put(key, (input.readInt() & 0xff));
continue;
}
if (key.endsWith("opacity")) {
theme.put(key, "" + (input.readInt() & 0xff));
continue;
}
if (key.endsWith("elevation")) {
theme.put(key, (input.readInt() & 0xff));
continue;
}
if (key.endsWith("iconGap")) {
theme.put(key, input.readFloat());
continue;
}
if (key.endsWith("iconGapUnit")) {
theme.put(key, input.readByte());
continue;
}
if (key.endsWith("surface")) {
theme.put(key, (input.readBoolean()));
continue;
}
// if this is a padding or margin then we will have the 4 values as bytes
if (key.endsWith("adding") || key.endsWith("argin")) {
if (minorVersion > 7) {
float p1 = input.readFloat();
float p2 = input.readFloat();
float p3 = input.readFloat();
float p4 = input.readFloat();
theme.put(key, "" + p1 + "," + p2 + "," + p3 + "," + p4);
} else {
int p1 = input.readByte() & 0xff;
int p2 = input.readByte() & 0xff;
int p3 = input.readByte() & 0xff;
int p4 = input.readByte() & 0xff;
theme.put(key, "" + p1 + "," + p2 + "," + p3 + "," + p4);
}
continue;
}
// padding and or margin type
if (key.endsWith("Unit")) {
byte p1 = input.readByte();
byte p2 = input.readByte();
byte p3 = input.readByte();
byte p4 = input.readByte();
theme.put(key, new byte[] { p1, p2, p3, p4 });
continue;
}
// border
if (key.endsWith("order")) {
int borderType = input.readShort() & 0xffff;
Object b = createBorder(input, borderType);
theme.put(key, b);
continue;
}
// if this is a font
if (key.endsWith("ont")) {
Font f;
// is this a new font?
if (input.readBoolean()) {
String fontId = input.readUTF();
f = (Font) resources.get(fontId);
// if the font is not yet loaded
if (f == null) {
theme.put(key, fontId);
continue;
}
} else {
f = Font.createSystemFont(input.readByte(), input.readByte(), input.readByte());
if (minorVersion > 4) {
boolean hasTTF = input.readBoolean();
if (hasTTF) {
String fileName = input.readUTF();
String fontName = input.readUTF();
int sizeSetting = input.readInt();
float fontSize = input.readFloat();
if (Font.isTrueTypeFileSupported()) {
fontKeys.add(key);
f = createTrueTypeFont(f, fontName, fileName, fontSize, sizeSetting);
}
}
}
}
theme.put(key, f);
continue;
}
// the background property
if (key.endsWith("ackground")) {
int type = input.readByte() & 0xff;
int pos = key.indexOf('.');
if (pos > -1) {
key = key.substring(0, pos);
} else {
key = "";
}
theme.put(key + Style.BACKGROUND_TYPE, new Byte((byte) type));
switch(type) {
// Scaled Image
case 0xF1:
// Tiled Both Image
case MAGIC_INDEXED_IMAGE_LEGACY:
// the image name coupled with the type
theme.put(key + Style.BG_IMAGE, input.readUTF());
break;
// Aligned Image
case 0xf5:
// Tiled Vertically Image
case 0xF2:
// Tiled Horizontally Image
case 0xF3:
// the image name coupled with the type and with alignment information
String imageName = input.readUTF();
theme.put(key + Style.BG_IMAGE, imageName);
byte align = input.readByte();
theme.put(key + Style.BACKGROUND_ALIGNMENT, new Byte(align));
break;
// Horizontal Linear Gradient
case 0xF6:
// Vertical Linear Gradient
case 0xF7:
Float c = new Float(0.5f);
theme.put(key + Style.BACKGROUND_GRADIENT, new Object[] { new Integer(input.readInt()), new Integer(input.readInt()), c, c, new Float(1) });
break;
// Radial Gradient
case 0xF8:
int c1 = input.readInt();
int c2 = input.readInt();
float f1 = input.readFloat();
float f2 = input.readFloat();
float radialSize = 1;
if (minorVersion > 1) {
radialSize = input.readFloat();
}
theme.put(key + Style.BACKGROUND_GRADIENT, new Object[] { new Integer(c1), new Integer(c2), new Float(f1), new Float(f2), new Float(radialSize) });
break;
}
continue;
}
// if this is a background image bgImage
if (key.endsWith("derive")) {
theme.put(key, input.readUTF());
continue;
}
// if this is a background image bgImage
if (key.endsWith("bgImage")) {
String imageId = input.readUTF();
Image i = getImage(imageId);
// if the font is not yet loaded
if (i == null) {
theme.put(key, imageId);
continue;
}
theme.put(key, i);
continue;
}
if (key.endsWith("scaledImage")) {
if (input.readBoolean()) {
theme.put(key, "true");
} else {
theme.put(key, "false");
}
continue;
}
if (key.endsWith(Style.BACKGROUND_TYPE) || key.endsWith(Style.BACKGROUND_ALIGNMENT)) {
theme.put(key, new Byte(input.readByte()));
continue;
}
if (key.endsWith(Style.BACKGROUND_GRADIENT)) {
if (minorVersion < 2) {
theme.put(key, new Object[] { new Integer(input.readInt()), new Integer(input.readInt()), new Float(input.readFloat()), new Float(input.readFloat()) });
} else {
theme.put(key, new Object[] { new Integer(input.readInt()), new Integer(input.readInt()), new Float(input.readFloat()), new Float(input.readFloat()), new Float(input.readFloat()) });
}
continue;
}
// thow an exception no idea what this is
throw new IOException("Error while trying to read theme property: " + key);
}
if (enableMediaQueries) {
if (mediaRules != null && !mediaRules.isEmpty()) {
for (MediaRule rule : mediaRules.values()) {
theme.put(rule.translatedKey, theme.get(rule.rawKey));
}
}
if (fontScaleRules != null && !fontKeys.isEmpty()) {
float scale = 1f;
for (Map.Entry<String, Float> rule : fontScaleRules.entrySet()) {
String key = rule.getKey();
String skey = key.substring(1);
if (skey.startsWith("device-")) {
if (skey.startsWith(devicePrefix)) {
skey = skey.substring(devicePrefix.length());
} else {
continue;
}
}
if (skey.startsWith("platform-")) {
if (skey.startsWith(platformPrefix)) {
skey = skey.substring(platformPrefix.length());
} else {
continue;
}
}
if (skey.startsWith("density-")) {
if (skey.startsWith(densityPrefix)) {
skey = skey.substring(densityPrefix.length());
} else {
continue;
}
}
if ("font-scale".equals(skey)) {
scale *= rule.getValue();
}
}
if (Math.abs(scale - 1f) > 0.01) {
for (String fontKey : fontKeys) {
Font f = (Font) theme.get(fontKey);
if (f != null && f.isTTFNativeFont()) {
try {
f = f.derive(f.getPixelSize() * scale, f.getStyle());
theme.put(fontKey, f);
} catch (Exception ex) {
Log.p("Failed to derive font " + f + " while loading font key " + fontKey + " from resource file. " + ex.getMessage());
Log.e(ex);
}
}
}
}
}
}
return theme;
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class Resources method createImage.
Image createImage(DataInputStream input) throws IOException {
if (majorVersion == 0 && minorVersion == 0) {
byte[] data = new byte[input.readInt()];
input.readFully(data, 0, data.length);
return EncodedImage.create(data);
} else {
int type = input.readByte() & 0xff;
switch(type) {
// PNG file
case 0xf1:
// JPEG File
case 0xf2:
byte[] data = new byte[input.readInt()];
input.readFully(data, 0, data.length);
if (minorVersion > 3) {
int width = input.readInt();
int height = input.readInt();
boolean opaque = input.readBoolean();
return EncodedImage.create(data, width, height, opaque);
}
return EncodedImage.create(data);
// Indexed image
case 0xF3:
return createPackedImage8();
// SVG
case 0xF5:
{
int svgSize = input.readInt();
if (Image.isSVGSupported()) {
byte[] s = new byte[svgSize];
input.readFully(s);
String baseURL = input.readUTF();
boolean animated = input.readBoolean();
loadSVGRatios(input);
byte[] fallback = new byte[input.readInt()];
if (fallback.length > 0) {
input.readFully(fallback, 0, fallback.length);
}
return Image.createSVG(baseURL, animated, s);
} else {
svgSize -= input.skip(svgSize);
while (svgSize > 0) {
svgSize -= input.skip(svgSize);
}
// read the base url, the animated property and screen ratios to skip them as well...
input.readUTF();
input.readBoolean();
input.readFloat();
input.readFloat();
byte[] fallback = new byte[input.readInt()];
input.readFully(fallback, 0, fallback.length);
return EncodedImage.create(fallback);
}
}
// SVG with multi-image
case 0xf7:
{
int svgSize = input.readInt();
if (Image.isSVGSupported()) {
byte[] s = new byte[svgSize];
input.readFully(s);
String baseURL = input.readUTF();
boolean animated = input.readBoolean();
Image img = readMultiImage(input, true);
Image svg = createSVG(animated, s);
if (svg.getSVGDocument() == null) {
return img;
}
return svg;
} else {
svgSize -= input.skip(svgSize);
while (svgSize > 0) {
svgSize -= input.skip(svgSize);
}
String baseURL = input.readUTF();
// read the animated property to skip it as well...
input.readBoolean();
return readMultiImage(input);
}
}
// mutli image
case 0xF6:
return readMultiImage(input);
case 0xEF:
Timeline tl = readTimeline(input);
return tl;
// Fail this is the wrong data type
default:
throw new IOException("Illegal type while creating image: " + Integer.toHexString(type));
}
}
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class LazyValueC method createComponent.
private Component createComponent(DataInputStream in, Container parent, Container root, Resources res, Hashtable componentListeners, EmbeddedContainer embedded) throws Exception {
String name = in.readUTF();
int property = in.readInt();
// special case for the base form
if (property == PROPERTY_BASE_FORM) {
String baseFormName = name;
initBaseForm(baseFormName);
if (!ignorBaseForm) {
Form base = (Form) createContainer(res, baseFormName);
Container destination = (Container) findByName("destination", base);
// try finding an appropriate empty container if no "fixed" destination is defined
if (destination == null) {
destination = findEmptyContainer(base.getContentPane());
if (destination == null) {
System.out.println("Couldn't find appropriate 'destination' container in base form: " + baseFormName);
return null;
}
}
root = base;
Component cmp = createComponent(in, destination, root, res, componentListeners, embedded);
if (destination.getLayout() instanceof BorderLayout) {
destination.addComponent(BorderLayout.CENTER, cmp);
} else {
destination.addComponent(cmp);
}
return root;
} else {
name = in.readUTF();
property = in.readInt();
}
}
Component cmp = createComponentType(name);
if (componentListeners != null) {
Object listeners = componentListeners.get(name);
if (listeners != null) {
if (listeners instanceof Vector) {
Vector v = (Vector) listeners;
for (int iter = 0; iter < v.size(); iter++) {
bindListenerToComponent(cmp, v.elementAt(iter));
}
} else {
bindListenerToComponent(cmp, listeners);
}
}
}
Component actualLead = cmp;
if (actualLead instanceof Container) {
Container cnt = (Container) actualLead;
actualLead = cnt.getLeadComponent();
if (actualLead == null) {
actualLead = cmp;
}
}
if (actualLead instanceof Button) {
ActionListener l = getFormListenerInstance(root, embedded);
if (l != null) {
((Button) actualLead).addActionListener(l);
}
} else {
if (actualLead instanceof TextArea) {
ActionListener l = getFormListenerInstance(root, embedded);
if (l != null) {
((TextArea) actualLead).addActionListener(l);
}
} else {
if (actualLead instanceof List) {
ActionListener l = getFormListenerInstance(root, embedded);
if (l != null) {
((List) actualLead).addActionListener(l);
}
} else {
if (actualLead instanceof ContainerList) {
ActionListener l = getFormListenerInstance(root, embedded);
if (l != null) {
((ContainerList) actualLead).addActionListener(l);
}
} else {
if (actualLead instanceof com.codename1.ui.Calendar) {
ActionListener l = getFormListenerInstance(root, embedded);
if (l != null) {
((com.codename1.ui.Calendar) actualLead).addActionListener(l);
}
}
}
}
}
}
cmp.putClientProperty(TYPE_KEY, name);
if (root == null) {
root = (Container) cmp;
}
while (property != -1) {
modifyingProperty(cmp, property);
switch(property) {
case PROPERTY_CUSTOM:
String customPropertyName = in.readUTF();
modifyingCustomProperty(cmp, customPropertyName);
boolean isNull = in.readBoolean();
if (isNull) {
cmp.setPropertyValue(customPropertyName, null);
break;
}
boolean cl = cmp instanceof ContainerList;
String[] propertyNames = cmp.getPropertyNames();
for (int iter = 0; iter < propertyNames.length; iter++) {
if (propertyNames[iter].equals(customPropertyName)) {
Class type = cmp.getPropertyTypes()[iter];
String[] typeNames = cmp.getPropertyTypeNames();
String typeName = null;
if (typeNames != null && typeNames.length > iter) {
typeName = typeNames[iter];
}
Object value = readCustomPropertyValue(in, type, typeName, res, propertyNames[iter]);
if (cl && customPropertyName.equals("ListItems") && setListModel((ContainerList) cmp)) {
break;
}
cmp.setPropertyValue(customPropertyName, value);
break;
}
}
break;
case PROPERTY_EMBED:
root.putClientProperty(EMBEDDED_FORM_FLAG, "");
((EmbeddedContainer) cmp).setEmbed(in.readUTF());
Container embed = createContainer(res, ((EmbeddedContainer) cmp).getEmbed(), (EmbeddedContainer) cmp);
if (embed != null) {
if (embed instanceof Form) {
embed = formToContainer((Form) embed);
}
((EmbeddedContainer) cmp).addComponent(BorderLayout.CENTER, embed);
// this isn't exactly the "right thing" but its the best we can do to make all
// use cases work
beforeShowContainer(embed);
postShowContainer(embed);
}
break;
case PROPERTY_TOGGLE_BUTTON:
((Button) cmp).setToggle(in.readBoolean());
break;
case PROPERTY_RADIO_GROUP:
((RadioButton) cmp).setGroup(in.readUTF());
break;
case PROPERTY_SELECTED:
boolean isSelected = in.readBoolean();
if (cmp instanceof RadioButton) {
((RadioButton) cmp).setSelected(isSelected);
} else {
((CheckBox) cmp).setSelected(isSelected);
}
break;
case PROPERTY_SCROLLABLE_X:
((Container) cmp).setScrollableX(in.readBoolean());
break;
case PROPERTY_SCROLLABLE_Y:
((Container) cmp).setScrollableY(in.readBoolean());
break;
case PROPERTY_TENSILE_DRAG_ENABLED:
cmp.setTensileDragEnabled(in.readBoolean());
break;
case PROPERTY_TACTILE_TOUCH:
cmp.setTactileTouch(in.readBoolean());
break;
case PROPERTY_SNAP_TO_GRID:
cmp.setSnapToGrid(in.readBoolean());
break;
case PROPERTY_FLATTEN:
cmp.setFlatten(in.readBoolean());
break;
case PROPERTY_TEXT:
if (cmp instanceof Label) {
((Label) cmp).setText(in.readUTF());
} else {
((TextArea) cmp).setText(in.readUTF());
}
break;
case PROPERTY_TEXT_MAX_LENGTH:
((TextArea) cmp).setMaxSize(in.readInt());
break;
case PROPERTY_TEXT_CONSTRAINT:
((TextArea) cmp).setConstraint(in.readInt());
if (cmp instanceof TextField) {
int cons = ((TextArea) cmp).getConstraint();
if ((cons & TextArea.NUMERIC) == TextArea.NUMERIC) {
((TextField) cmp).setInputModeOrder(new String[] { "123" });
}
}
break;
case PROPERTY_ALIGNMENT:
if (cmp instanceof Label) {
((Label) cmp).setAlignment(in.readInt());
} else {
((TextArea) cmp).setAlignment(in.readInt());
}
break;
case PROPERTY_TEXT_AREA_GROW:
((TextArea) cmp).setGrowByContent(in.readBoolean());
break;
case PROPERTY_LAYOUT:
Layout layout = null;
switch(in.readShort()) {
case LAYOUT_BORDER_LEGACY:
layout = new BorderLayout();
break;
case LAYOUT_BORDER_ANOTHER_LEGACY:
{
BorderLayout b = new BorderLayout();
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.NORTH, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.EAST, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.WEST, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.SOUTH, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.CENTER, in.readUTF());
}
layout = b;
break;
}
case LAYOUT_BORDER:
{
BorderLayout b = new BorderLayout();
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.NORTH, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.EAST, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.WEST, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.SOUTH, in.readUTF());
}
if (in.readBoolean()) {
b.defineLandscapeSwap(BorderLayout.CENTER, in.readUTF());
}
b.setAbsoluteCenter(in.readBoolean());
layout = b;
break;
}
case LAYOUT_BOX_X:
layout = new BoxLayout(BoxLayout.X_AXIS);
break;
case LAYOUT_BOX_Y:
layout = new BoxLayout(BoxLayout.Y_AXIS);
break;
case LAYOUT_FLOW_LEGACY:
layout = new FlowLayout();
break;
case LAYOUT_FLOW:
FlowLayout f = new FlowLayout();
f.setFillRows(in.readBoolean());
f.setAlign(in.readInt());
f.setValign(in.readInt());
layout = f;
break;
case LAYOUT_LAYERED:
layout = new LayeredLayout();
break;
case LAYOUT_GRID:
layout = new GridLayout(in.readInt(), in.readInt());
break;
case LAYOUT_TABLE:
layout = new TableLayout(in.readInt(), in.readInt());
break;
}
((Container) cmp).setLayout(layout);
break;
case PROPERTY_TAB_PLACEMENT:
((Tabs) cmp).setTabPlacement(in.readInt());
break;
case PROPERTY_TAB_TEXT_POSITION:
((Tabs) cmp).setTabTextPosition(in.readInt());
break;
case PROPERTY_PREFERRED_WIDTH:
cmp.setPreferredW(in.readInt());
break;
case PROPERTY_PREFERRED_HEIGHT:
cmp.setPreferredH(in.readInt());
break;
case PROPERTY_UIID:
cmp.setUIID(in.readUTF());
break;
case PROPERTY_DIALOG_UIID:
((Dialog) cmp).setDialogUIID(in.readUTF());
break;
case PROPERTY_DISPOSE_WHEN_POINTER_OUT:
((Dialog) cmp).setDisposeWhenPointerOutOfBounds(in.readBoolean());
break;
case PROPERTY_CLOUD_BOUND_PROPERTY:
cmp.setCloudBoundProperty(in.readUTF());
break;
case PROPERTY_CLOUD_DESTINATION_PROPERTY:
cmp.setCloudDestinationProperty(in.readUTF());
break;
case PROPERTY_DIALOG_POSITION:
String pos = in.readUTF();
if (pos.length() > 0) {
((Dialog) cmp).setDialogPosition(pos);
}
break;
case PROPERTY_FOCUSABLE:
cmp.setFocusable(in.readBoolean());
break;
case PROPERTY_ENABLED:
cmp.setEnabled(in.readBoolean());
break;
case PROPERTY_SCROLL_VISIBLE:
cmp.setScrollVisible(in.readBoolean());
break;
case PROPERTY_ICON:
((Label) cmp).setIcon(res.getImage(in.readUTF()));
break;
case PROPERTY_ROLLOVER_ICON:
((Button) cmp).setRolloverIcon(res.getImage(in.readUTF()));
break;
case PROPERTY_PRESSED_ICON:
((Button) cmp).setPressedIcon(res.getImage(in.readUTF()));
break;
case PROPERTY_DISABLED_ICON:
((Button) cmp).setDisabledIcon(res.getImage(in.readUTF()));
break;
case PROPERTY_GAP:
((Label) cmp).setGap(in.readInt());
break;
case PROPERTY_VERTICAL_ALIGNMENT:
if (cmp instanceof TextArea) {
((TextArea) cmp).setVerticalAlignment(in.readInt());
} else {
((Label) cmp).setVerticalAlignment(in.readInt());
}
break;
case PROPERTY_TEXT_POSITION:
((Label) cmp).setTextPosition(in.readInt());
break;
case PROPERTY_CLIENT_PROPERTIES:
int count = in.readInt();
StringBuilder sb = new StringBuilder();
for (int iter = 0; iter < count; iter++) {
String k = in.readUTF();
String v = in.readUTF();
cmp.putClientProperty(k, v);
sb.append(k);
if (iter < count - 1) {
sb.append(",");
}
}
cmp.putClientProperty("cn1$Properties", sb.toString());
break;
case PROPERTY_NAME:
String componentName = in.readUTF();
cmp.setName(componentName);
root.putClientProperty("%" + componentName + "%", cmp);
break;
case PROPERTY_LAYOUT_CONSTRAINT:
if (parent.getLayout() instanceof BorderLayout) {
cmp.putClientProperty("layoutConstraint", in.readUTF());
} else {
TableLayout tl = (TableLayout) parent.getLayout();
TableLayout.Constraint con = tl.createConstraint(in.readInt(), in.readInt());
con.setHeightPercentage(in.readInt());
con.setWidthPercentage(in.readInt());
con.setHorizontalAlign(in.readInt());
con.setHorizontalSpan(in.readInt());
con.setVerticalAlign(in.readInt());
con.setVerticalSpan(in.readInt());
cmp.putClientProperty("layoutConstraint", con);
}
break;
case PROPERTY_TITLE:
((Form) cmp).setTitle(in.readUTF());
break;
case PROPERTY_COMPONENTS:
int componentCount = in.readInt();
if (cmp instanceof Tabs) {
for (int iter = 0; iter < componentCount; iter++) {
String tab = in.readUTF();
Component child = createComponent(in, (Container) cmp, root, res, componentListeners, embedded);
((Tabs) cmp).addTab(tab, child);
}
} else {
for (int iter = 0; iter < componentCount; iter++) {
Component child = createComponent(in, (Container) cmp, root, res, componentListeners, embedded);
Object con = child.getClientProperty("layoutConstraint");
if (con != null) {
((Container) cmp).addComponent(con, child);
} else {
((Container) cmp).addComponent(child);
}
}
}
break;
case PROPERTY_COLUMNS:
((TextArea) cmp).setColumns(in.readInt());
break;
case PROPERTY_ROWS:
((TextArea) cmp).setRows(in.readInt());
break;
case PROPERTY_HINT:
if (cmp instanceof List) {
((List) cmp).setHint(in.readUTF());
} else {
((TextArea) cmp).setHint(in.readUTF());
}
break;
case PROPERTY_HINT_ICON:
if (cmp instanceof List) {
((List) cmp).setHintIcon(res.getImage(in.readUTF()));
} else {
((TextArea) cmp).setHintIcon(res.getImage(in.readUTF()));
}
break;
case PROPERTY_ITEM_GAP:
((List) cmp).setItemGap(in.readInt());
break;
case PROPERTY_LIST_FIXED:
((List) cmp).setFixedSelection(in.readInt());
break;
case PROPERTY_LIST_ORIENTATION:
((List) cmp).setOrientation(in.readInt());
break;
case PROPERTY_LIST_ITEMS_LEGACY:
String[] items = new String[in.readInt()];
for (int iter = 0; iter < items.length; iter++) {
items[iter] = in.readUTF();
}
if (!setListModel(((List) cmp))) {
((List) cmp).setModel(new DefaultListModel((Object[]) items));
}
break;
case PROPERTY_LIST_ITEMS:
Object[] elements = readObjectArrayForListModel(in, res);
if (!setListModel(((List) cmp))) {
((List) cmp).setModel(new DefaultListModel(elements));
}
break;
case PROPERTY_LIST_RENDERER:
if (cmp instanceof ContainerList) {
((ContainerList) cmp).setRenderer(readRendererer(res, in));
} else {
((List) cmp).setRenderer(readRendererer(res, in));
}
break;
case PROPERTY_NEXT_FORM:
String nextForm = in.readUTF();
setNextForm(cmp, nextForm, res, root);
break;
case PROPERTY_COMMANDS:
readCommands(in, cmp, res, false);
break;
case PROPERTY_COMMANDS_LEGACY:
readCommands(in, cmp, res, true);
break;
case PROPERTY_CYCLIC_FOCUS:
((Form) cmp).setCyclicFocus(in.readBoolean());
break;
case PROPERTY_RTL:
cmp.setRTL(in.readBoolean());
break;
case PROPERTY_SLIDER_THUMB:
((Slider) cmp).setThumbImage(res.getImage(in.readUTF()));
break;
case PROPERTY_INFINITE:
((Slider) cmp).setInfinite(in.readBoolean());
break;
case PROPERTY_PROGRESS:
((Slider) cmp).setProgress(in.readInt());
break;
case PROPERTY_VERTICAL:
((Slider) cmp).setVertical(in.readBoolean());
break;
case PROPERTY_EDITABLE:
if (cmp instanceof TextArea) {
((TextArea) cmp).setEditable(in.readBoolean());
} else {
((Slider) cmp).setEditable(in.readBoolean());
}
break;
case PROPERTY_INCREMENTS:
((Slider) cmp).setIncrements(in.readInt());
break;
case PROPERTY_RENDER_PERCENTAGE_ON_TOP:
((Slider) cmp).setRenderPercentageOnTop(in.readBoolean());
break;
case PROPERTY_MAX_VALUE:
((Slider) cmp).setMaxValue(in.readInt());
break;
case PROPERTY_MIN_VALUE:
((Slider) cmp).setMinValue(in.readInt());
break;
}
property = in.readInt();
}
postCreateComponent(cmp);
return cmp;
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class JavaSEPort method installMenu.
private void installMenu(final JFrame frm, boolean desktopSkin) throws IOException {
final Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
JMenuBar bar = new JMenuBar();
frm.setJMenuBar(bar);
JMenu simulatorMenu = new JMenu("Simulator");
registerMenuWithBlit(simulatorMenu);
JMenu simulateMenu = new JMenu("Simulate");
registerMenuWithBlit(simulateMenu);
JMenu toolsMenu = new JMenu("Tools");
registerMenuWithBlit(toolsMenu);
JMenuItem buildHintEditor = new JMenuItem("Edit Build Hints...");
ActionListener l = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new BuildHintEditor(JavaSEPort.this).show();
}
};
buildHintEditor.addActionListener(l);
toolsMenu.add(buildHintEditor);
final JCheckBoxMenuItem useAppFrameMenu = new JCheckBoxMenuItem("Single Window Mode", useAppFrame);
useAppFrameMenu.setToolTipText("Check this option to enable Single Window mode, in which the simulator, component inspector, network monitor and other tools are all included in a single, multi-panel window");
useAppFrameMenu.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
try {
pref.putBoolean("cn1.simulator.useAppFrame", useAppFrameMenu.isSelected());
deinitializeSync();
frm.dispose();
System.setProperty("reload.simulator", "true");
} catch (Exception ex) {
Log.e(ex);
}
}
});
simulatorMenu.add(useAppFrameMenu);
final JCheckBoxMenuItem zoomMenu = new JCheckBoxMenuItem("Zoom", scrollableSkin);
if (appFrame == null)
simulatorMenu.add(zoomMenu);
JMenu debugEdtMenu = new JMenu("Debug EDT");
toolsMenu.add(debugEdtMenu);
zoomMenu.setEnabled(!desktopSkin);
JRadioButtonMenuItem debugEdtNone = new JRadioButtonMenuItem("None");
JRadioButtonMenuItem debugEdtLight = new JRadioButtonMenuItem("Light");
JRadioButtonMenuItem debugEdtFull = new JRadioButtonMenuItem("Full");
debugEdtMenu.add(debugEdtNone);
debugEdtMenu.add(debugEdtLight);
debugEdtMenu.add(debugEdtFull);
ButtonGroup bg = new ButtonGroup();
bg.add(debugEdtNone);
bg.add(debugEdtLight);
bg.add(debugEdtFull);
int debugEdtSelection = pref.getInt("debugEDTMode", 0);
switch(debugEdtSelection) {
case 0:
debugEdtNone.setSelected(true);
setShowEDTWarnings(false);
setShowEDTViolationStacks(false);
break;
case 2:
debugEdtFull.setSelected(true);
setShowEDTWarnings(true);
setShowEDTViolationStacks(true);
break;
default:
debugEdtLight.setSelected(true);
setShowEDTWarnings(true);
setShowEDTViolationStacks(false);
break;
}
debugEdtNone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setShowEDTWarnings(false);
setShowEDTViolationStacks(false);
pref.putInt("debugEDTMode", 0);
}
});
debugEdtFull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setShowEDTWarnings(true);
setShowEDTViolationStacks(true);
pref.putInt("debugEDTMode", 2);
}
});
debugEdtLight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setShowEDTWarnings(true);
setShowEDTViolationStacks(false);
pref.putInt("debugEDTMode", 1);
}
});
JMenuItem screenshot = new JMenuItem("Screenshot");
if (appFrame == null)
simulatorMenu.add(screenshot);
KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
screenshot.setAccelerator(f2);
screenshot.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
final float zoom = zoomLevel;
zoomLevel = 1;
final Form frm = Display.getInstance().getCurrent();
BufferedImage headerImageTmp;
if (isPortrait()) {
headerImageTmp = header;
} else {
headerImageTmp = headerLandscape;
}
if (!includeHeaderInScreenshot) {
headerImageTmp = null;
}
int headerHeightTmp = 0;
if (headerImageTmp != null) {
headerHeightTmp = headerImageTmp.getHeight();
}
final int headerHeight = headerHeightTmp;
final BufferedImage headerImage = headerImageTmp;
// gr.translate(0, statusBarHeight);
Display.getInstance().callSerially(new Runnable() {
public void run() {
final com.codename1.ui.Image img = com.codename1.ui.Image.createImage(frm.getWidth(), frm.getHeight());
com.codename1.ui.Graphics gr = img.getGraphics();
takingScreenshot = true;
screenshotActualZoomLevel = zoom;
try {
frm.paint(gr);
} finally {
takingScreenshot = false;
}
final int imageWidth = img.getWidth();
final int imageHeight = img.getHeight();
final int[] imageRGB = img.getRGB();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
BufferedImage bi = new BufferedImage(frm.getWidth(), frm.getHeight() + headerHeight, BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0, headerHeight, imageWidth, imageHeight, imageRGB, 0, imageWidth);
if (headerImage != null) {
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(headerImage, 0, 0, null);
g2d.dispose();
}
OutputStream out = null;
try {
out = new FileOutputStream(findScreenshotFile());
ImageIO.write(bi, "png", out);
out.close();
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(1);
} finally {
zoomLevel = zoom;
try {
out.close();
} catch (Throwable ex) {
}
frm.repaint();
canvas.repaint();
}
}
});
}
});
}
});
JMenuItem screenshotWithSkin = new JMenuItem("Screenshot With Skin");
if (appFrame == null)
simulatorMenu.add(screenshotWithSkin);
screenshotWithSkin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final float zoom = zoomLevel;
zoomLevel = 1;
final Form frm = Display.getInstance().getCurrent();
BufferedImage headerImageTmp;
if (isPortrait()) {
headerImageTmp = header;
} else {
headerImageTmp = headerLandscape;
}
if (!includeHeaderInScreenshot) {
headerImageTmp = null;
}
int headerHeightTmp = 0;
if (headerImageTmp != null) {
headerHeightTmp = headerImageTmp.getHeight();
}
final int headerHeight = headerHeightTmp;
final BufferedImage headerImage = headerImageTmp;
// gr.translate(0, statusBarHeight);
Display.getInstance().callSerially(new Runnable() {
public void run() {
final com.codename1.ui.Image img = com.codename1.ui.Image.createImage(frm.getWidth(), frm.getHeight());
com.codename1.ui.Graphics gr = img.getGraphics();
takingScreenshot = true;
screenshotActualZoomLevel = zoom;
try {
frm.paint(gr);
} finally {
takingScreenshot = false;
}
final int imageWidth = img.getWidth();
final int imageHeight = img.getHeight();
final int[] imageRGB = img.getRGB();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
BufferedImage bi = new BufferedImage(frm.getWidth(), frm.getHeight() + headerHeight, BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0, headerHeight, imageWidth, imageHeight, imageRGB, 0, imageWidth);
BufferedImage skin = getSkin();
BufferedImage newSkin = new BufferedImage(skin.getWidth(), skin.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = newSkin.createGraphics();
g2d.drawImage(bi, getScreenCoordinates().x, getScreenCoordinates().y, null);
if (headerImage != null) {
g2d.drawImage(headerImage, getScreenCoordinates().x, getScreenCoordinates().y, null);
}
g2d.drawImage(skin, 0, 0, null);
g2d.dispose();
OutputStream out = null;
try {
out = new FileOutputStream(findScreenshotFile());
ImageIO.write(newSkin, "png", out);
out.close();
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(1);
} finally {
zoomLevel = zoom;
try {
out.close();
} catch (Throwable ex) {
}
frm.repaint();
canvas.repaint();
}
}
});
}
});
}
});
includeHeaderInScreenshot = pref.getBoolean("includeHeaderScreenshot", true);
final JCheckBoxMenuItem includeHeaderMenu = new JCheckBoxMenuItem("Screenshot StatusBar");
includeHeaderMenu.setToolTipText("Include status bar area in Screenshots");
includeHeaderMenu.setSelected(includeHeaderInScreenshot);
if (appFrame == null)
simulatorMenu.add(includeHeaderMenu);
includeHeaderMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
includeHeaderInScreenshot = includeHeaderMenu.isSelected();
pref.putBoolean("includeHeaderScreenshot", includeHeaderInScreenshot);
}
});
JMenu networkDebug = new JMenu("Network");
toolsMenu.add(networkDebug);
JMenuItem networkMonitor = new JMenuItem("Network Monitor");
networkMonitor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (netMonitor == null) {
showNetworkMonitor();
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.putBoolean("NetworkMonitor", true);
}
}
});
networkDebug.add(networkMonitor);
JMenuItem proxy = new JMenuItem("Proxy Settings");
proxy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JDialog proxy;
if (window != null) {
proxy = new JDialog(window);
} else {
proxy = new JDialog();
}
final Preferences pref = Preferences.userNodeForPackage(Component.class);
int proxySel = pref.getInt("proxySel", 2);
String proxySelHttp = pref.get("proxySel-http", "");
String proxySelPort = pref.get("proxySel-port", "");
JPanel panel = new JPanel();
panel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JPanel proxyUrl = new JPanel();
proxyUrl.setLayout(new FlowLayout(FlowLayout.LEFT));
proxyUrl.add(new JLabel("Http Proxy:"));
final JTextField http = new JTextField(proxySelHttp);
http.setColumns(20);
proxyUrl.add(http);
proxyUrl.add(new JLabel("Port:"));
final JTextField port = new JTextField(proxySelPort);
port.setColumns(4);
proxyUrl.add(port);
final JRadioButton noproxy = new JRadioButton("No Proxy");
JPanel rbPanel = new JPanel();
rbPanel.setLayout(new java.awt.GridLayout(1, 0));
rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
rbPanel.add(noproxy);
Dimension d = rbPanel.getPreferredSize();
d.width = proxyUrl.getPreferredSize().width;
rbPanel.setMinimumSize(d);
// noproxy.setPreferredSize(d);
panel.add(rbPanel);
final JRadioButton systemProxy = new JRadioButton("Use System Proxy");
rbPanel = new JPanel();
rbPanel.setLayout(new java.awt.GridLayout(1, 0));
rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
rbPanel.add(systemProxy);
d = rbPanel.getPreferredSize();
d.width = proxyUrl.getPreferredSize().width;
rbPanel.setPreferredSize(d);
panel.add(rbPanel);
final JRadioButton manual = new JRadioButton("Manual Proxy Settings:");
rbPanel = new JPanel();
rbPanel.setLayout(new java.awt.GridLayout(1, 0));
rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
rbPanel.add(manual);
d = rbPanel.getPreferredSize();
d.width = proxyUrl.getPreferredSize().width;
rbPanel.setPreferredSize(d);
panel.add(rbPanel);
rbPanel = new JPanel();
rbPanel.setLayout(new java.awt.GridLayout(1, 0));
rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
rbPanel.add(proxyUrl);
panel.add(rbPanel);
ButtonGroup group = new ButtonGroup();
group.add(noproxy);
group.add(systemProxy);
group.add(manual);
noproxy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
http.setEnabled(false);
port.setEnabled(false);
}
});
systemProxy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
http.setEnabled(false);
port.setEnabled(false);
}
});
manual.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
http.setEnabled(true);
port.setEnabled(true);
}
});
switch(proxySel) {
case 1:
noproxy.setSelected(true);
http.setEnabled(false);
port.setEnabled(false);
break;
case 2:
systemProxy.setSelected(true);
http.setEnabled(false);
port.setEnabled(false);
break;
case 3:
manual.setSelected(true);
break;
}
JPanel closePanel = new JPanel();
JButton close = new JButton("Ok");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (noproxy.isSelected()) {
pref.putInt("proxySel", 1);
} else if (systemProxy.isSelected()) {
pref.putInt("proxySel", 2);
} else if (manual.isSelected()) {
pref.putInt("proxySel", 3);
pref.put("proxySel-http", http.getText());
pref.put("proxySel-port", port.getText());
}
proxy.dispose();
if (netMonitor != null) {
netMonitor.dispose();
netMonitor = null;
}
if (perfMonitor != null) {
perfMonitor.dispose();
perfMonitor = null;
}
String mainClass = System.getProperty("MainClass");
if (mainClass != null) {
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
deinitializeSync();
frm.dispose();
System.setProperty("reload.simulator", "true");
} else {
refreshSkin(frm);
}
}
});
closePanel.add(close);
panel.add(closePanel);
proxy.add(panel);
proxy.pack();
if (window != null) {
proxy.setLocationRelativeTo(window);
}
proxy.setResizable(false);
proxy.setVisible(true);
}
});
networkDebug.add(proxy);
networkDebug.addSeparator();
JRadioButtonMenuItem regularConnection = new JRadioButtonMenuItem("Regular Connection");
regularConnection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
slowConnectionMode = false;
disconnectedMode = false;
pref.putInt("connectionStatus", 0);
}
});
networkDebug.add(regularConnection);
JRadioButtonMenuItem slowConnection = new JRadioButtonMenuItem("Slow Connection");
slowConnection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
slowConnectionMode = true;
disconnectedMode = false;
pref.putInt("connectionStatus", 1);
}
});
networkDebug.add(slowConnection);
JRadioButtonMenuItem disconnected = new JRadioButtonMenuItem("Disconnected");
disconnected.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
slowConnectionMode = false;
disconnectedMode = true;
pref.putInt("connectionStatus", 2);
}
});
networkDebug.add(disconnected);
ButtonGroup connectionGroup = new ButtonGroup();
connectionGroup.add(regularConnection);
connectionGroup.add(slowConnection);
connectionGroup.add(disconnected);
switch(pref.getInt("connectionStatus", 0)) {
case 0:
regularConnection.setSelected(true);
break;
case 1:
slowConnection.setSelected(true);
slowConnectionMode = true;
break;
case 2:
disconnected.setSelected(true);
disconnectedMode = true;
break;
}
JMenuItem componentTreeInspector = new JMenuItem("Component Inspector");
componentTreeInspector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (appFrame != null)
return;
new ComponentTreeInspector().showInFrame();
}
});
JMenuItem scriptingConsole = new JMenuItem("Groovy Console");
scriptingConsole.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new CN1Console().open((java.awt.Component) e.getSource());
}
});
List<String> inputArgs = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments();
// final boolean isDebug = inputArgs.toString().indexOf("-agentlib:jdwp") > 0;
// final boolean usingHotswapAgent = inputArgs.toString().indexOf("-XX:HotswapAgent") > 0;
ButtonGroup hotReloadGroup = new ButtonGroup();
JRadioButtonMenuItem disableHotReload = new JRadioButtonMenuItem("Disabled");
disableHotReload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pref.putInt("hotReload", 0);
System.setProperty("hotReload", "0");
}
});
JRadioButtonMenuItem reloadSimulator = new JRadioButtonMenuItem("Reload Simulator");
reloadSimulator.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pref.putInt("hotReload", 1);
System.setProperty("hotReload", "1");
}
});
JRadioButtonMenuItem reloadCurrentForm = new JRadioButtonMenuItem("Reload Current Form (Requires CodeRAD)");
reloadCurrentForm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pref.putInt("hotReload", 2);
System.setProperty("hotReload", "2");
}
});
switch(pref.getInt("hotReload", 0)) {
case 0:
disableHotReload.setSelected(true);
System.setProperty("hotReload", "0");
break;
case 1:
reloadSimulator.setSelected(true);
System.setProperty("hotReload", "1");
break;
case 2:
reloadCurrentForm.setSelected(true);
System.setProperty("hotReload", "2");
break;
}
JMenu hotReloadMenu = new JMenu("Hot Reload");
hotReloadMenu.add(disableHotReload);
hotReloadMenu.add(reloadSimulator);
hotReloadMenu.add(reloadCurrentForm);
hotReloadGroup.add(disableHotReload);
hotReloadGroup.add(reloadSimulator);
hotReloadGroup.add(reloadCurrentForm);
if (isRunningInMaven() && MavenUtils.isRunningInJDK()) {
toolsMenu.add(hotReloadMenu);
}
scriptingConsole.setToolTipText("Open interactive console");
JMenuItem appArg = new JMenuItem("Send App Argument");
appArg.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Executor.stopApp();
JPanel pnl = new JPanel();
JTextField tf = new JTextField(20);
pnl.add(new JLabel("Argument to The App"));
pnl.add(tf);
int val = JOptionPane.showConfirmDialog(canvas, pnl, "Please Enter The Argument", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (val != JOptionPane.OK_OPTION) {
Executor.startApp();
return;
}
String arg = tf.getText();
Display.getInstance().setProperty("AppArg", arg);
Executor.startApp();
}
});
simulateMenu.add(appArg);
JMenuItem debugWebViews = new JMenuItem("Debug Web Views");
debugWebViews.setEnabled(false);
debugInChromeMenuItem = debugWebViews;
debugWebViews.setToolTipText("Debug app's BrowserComponents' Javascript and DOM inside Chrome's debugger");
debugWebViews.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CN.callSerially(new Runnable() {
public void run() {
String port = System.getProperty("cef.debugPort", null);
if (port != null) {
final Sheet sheet = new Sheet(null, "Debug Web Views");
SpanLabel info = new SpanLabel("You can debug this app's web views in Chrome's " + "debugger by opening the following URL in Chrome:");
SpanLabel warning = new SpanLabel("Debugging only works in Chrome. If Chrome is not your default browser " + "then you'll need to copy and paste the URL above into Chrome");
ComponentSelector.select("*", warning).add(warning, true).selectAllStyles().setFontSizeMillimeters(2).setFgColor(0x555555);
FontImage.setMaterialIcon(warning, FontImage.MATERIAL_WARNING, 3);
final com.codename1.ui.TextField tf = new com.codename1.ui.TextField("http://localhost:" + port);
tf.addPointerPressedListener(new com.codename1.ui.events.ActionListener() {
@Override
public void actionPerformed(com.codename1.ui.events.ActionEvent evt) {
Display.getInstance().copyToClipboard(tf.getText());
ToastBar.showInfoMessage("URL Copied to Clipboard");
sheet.back();
}
});
tf.setEditable(false);
com.codename1.ui.Button copy = new com.codename1.ui.Button(com.codename1.ui.FontImage.MATERIAL_CONTENT_COPY);
copy.addActionListener(new com.codename1.ui.events.ActionListener() {
@Override
public void actionPerformed(com.codename1.ui.events.ActionEvent evt) {
Display.getInstance().copyToClipboard(tf.getText());
ToastBar.showInfoMessage("URL Copied to Clipboard");
sheet.back();
}
});
com.codename1.ui.Button open = new com.codename1.ui.Button("Open In Default Browser");
open.addActionListener(new com.codename1.ui.events.ActionListener() {
@Override
public void actionPerformed(com.codename1.ui.events.ActionEvent evt) {
CN.execute(tf.getText());
sheet.back();
}
});
sheet.getContentPane().setLayout(com.codename1.ui.layouts.BoxLayout.y());
sheet.getContentPane().add(info);
sheet.getContentPane().add(com.codename1.ui.layouts.BorderLayout.centerEastWest(tf, copy, null));
sheet.getContentPane().add(open);
sheet.getContentPane().add(warning);
sheet.setPosition(com.codename1.ui.layouts.BorderLayout.CENTER);
sheet.show();
} else {
ToastBar.showErrorMessage("Debugger not available. The Chrome debugger is only available in apps that contain a BrowserComponent");
}
}
});
}
});
toolsMenu.add(debugWebViews);
JMenuItem locationSim = new JMenuItem("Location Simulation");
locationSim.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (locSimulation == null) {
locSimulation = new LocationSimulation();
}
locSimulation.setVisible(true);
}
});
simulateMenu.add(locationSim);
JMenuItem pushSim = new JMenuItem("Push Simulation");
pushSim.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (pushSimulation == null) {
pushSimulation = new PushSimulator();
}
pref.putBoolean("PushSimulator", true);
pushSimulation.setVisible(true);
}
});
simulateMenu.add(pushSim);
if (appFrame == null) {
toolsMenu.add(componentTreeInspector);
}
toolsMenu.add(scriptingConsole);
JMenuItem testRecorderMenu = new JMenuItem("Test Recorder");
testRecorderMenu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (testRecorder == null) {
showTestRecorder();
}
}
});
toolsMenu.add(testRecorderMenu);
/*
JMenu darkLightModeMenu = new JMenu("Dark/Light Mode");
simulatorMenu.add(darkLightModeMenu);
final JRadioButtonMenuItem darkMode = new JRadioButtonMenuItem("Dark Mode");
final JRadioButtonMenuItem lightMode = new JRadioButtonMenuItem("Light Mode");
final JRadioButtonMenuItem unsupportedMode = new JRadioButtonMenuItem("Unsupported");
ButtonGroup group = new ButtonGroup();
group.add(darkMode);
group.add(lightMode);
group.add(unsupportedMode);
darkMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JavaSEPort.this.darkMode = true;
}
});
lightMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JavaSEPort.this.darkMode = false;
}
});
unsupportedMode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JavaSEPort.this.darkMode = null;
}
});
*/
manualPurchaseSupported = pref.getBoolean("manualPurchaseSupported", true);
managedPurchaseSupported = pref.getBoolean("managedPurchaseSupported", true);
subscriptionSupported = pref.getBoolean("subscriptionSupported", true);
refundSupported = pref.getBoolean("refundSupported", true);
JMenu purchaseMenu = new JMenu("In App Purchase");
simulateMenu.add(purchaseMenu);
final JCheckBoxMenuItem manualPurchaseSupportedMenu = new JCheckBoxMenuItem("Manual Purchase");
manualPurchaseSupportedMenu.setSelected(manualPurchaseSupported);
final JCheckBoxMenuItem managedPurchaseSupportedMenu = new JCheckBoxMenuItem("Managed Purchase");
managedPurchaseSupportedMenu.setSelected(managedPurchaseSupported);
final JCheckBoxMenuItem subscriptionSupportedMenu = new JCheckBoxMenuItem("Subscription");
subscriptionSupportedMenu.setSelected(subscriptionSupported);
final JCheckBoxMenuItem refundSupportedMenu = new JCheckBoxMenuItem("Refunds");
refundSupportedMenu.setSelected(refundSupported);
manualPurchaseSupportedMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
manualPurchaseSupported = manualPurchaseSupportedMenu.isSelected();
pref.putBoolean("manualPurchaseSupported", manualPurchaseSupported);
}
});
managedPurchaseSupportedMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
managedPurchaseSupported = managedPurchaseSupportedMenu.isSelected();
pref.putBoolean("managedPurchaseSupported", managedPurchaseSupported);
}
});
subscriptionSupportedMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
subscriptionSupported = subscriptionSupportedMenu.isSelected();
pref.putBoolean("subscriptionSupported", subscriptionSupported);
}
});
refundSupportedMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
refundSupported = refundSupportedMenu.isSelected();
pref.putBoolean("refundSupported", refundSupported);
}
});
purchaseMenu.add(manualPurchaseSupportedMenu);
purchaseMenu.add(managedPurchaseSupportedMenu);
purchaseMenu.add(subscriptionSupportedMenu);
purchaseMenu.add(refundSupportedMenu);
JMenuItem performanceMonitor = new JMenuItem("Performance Monitor");
performanceMonitor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (perfMonitor == null) {
showPerformanceMonitor();
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.putBoolean("PerformanceMonitor", true);
}
}
});
toolsMenu.add(performanceMonitor);
JMenuItem clean = new JMenuItem("Clean Storage");
clean.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
File home = new File(System.getProperty("user.home") + File.separator + appHomeDir);
if (!home.exists()) {
return;
}
if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to Clean all Storage under " + home.getAbsolutePath() + " ?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
File[] files = home.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
file.delete();
}
}
}
});
toolsMenu.add(clean);
JMenu skinMenu = createSkinsMenu(frm, null);
skinMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
menuDisplayed = true;
}
@Override
public void menuCanceled(MenuEvent e) {
menuDisplayed = false;
}
@Override
public void menuDeselected(MenuEvent e) {
menuDisplayed = false;
}
});
// final JCheckBoxMenuItem touchFlag = new JCheckBoxMenuItem("Touch", touchDevice);
// simulatorMenu.add(touchFlag);
// final JCheckBoxMenuItem nativeInputFlag = new JCheckBoxMenuItem("Native Input", useNativeInput);
// simulatorMenu.add(nativeInputFlag);
// final JCheckBoxMenuItem simulateAndroidVKBFlag = new JCheckBoxMenuItem("Simulate Android VKB", simulateAndroidKeyboard);
// simulatorMenu.add(simulateAndroidVKBFlag);
/*final JCheckBoxMenuItem slowMotionFlag = new JCheckBoxMenuItem("Slow Motion", false);
toolsMenu.add(slowMotionFlag);
slowMotionFlag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Motion.setSlowMotion(slowMotionFlag.isSelected());
}
});*/
final JCheckBoxMenuItem permFlag = new JCheckBoxMenuItem("Android 6 Permissions", android6PermissionsFlag);
simulateMenu.add(permFlag);
permFlag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
android6PermissionsFlag = !android6PermissionsFlag;
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.putBoolean("Android6Permissions", android6PermissionsFlag);
}
});
pause = new JMenuItem("Pause App");
simulateMenu.addSeparator();
simulateMenu.add(pause);
pause.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (pause.getText().startsWith("Pause")) {
Display.getInstance().callSerially(new Runnable() {
public void run() {
Executor.stopApp();
minimized = true;
}
});
canvas.setEnabled(false);
pause.setText("Resume App");
} else {
Display.getInstance().callSerially(new Runnable() {
public void run() {
Executor.startApp();
minimized = false;
}
});
canvas.setEnabled(true);
pause.setText("Pause App");
}
}
});
final JCheckBoxMenuItem alwaysOnTopFlag = new JCheckBoxMenuItem("Always on Top", alwaysOnTop);
if (appFrame == null)
simulatorMenu.add(alwaysOnTopFlag);
if (appFrame == null)
simulatorMenu.addSeparator();
JMenuItem exit = new JMenuItem("Exit");
simulatorMenu.add(exit);
JMenu helpMenu = new JMenu("Help");
helpMenu.setDoubleBuffered(true);
helpMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
menuDisplayed = true;
}
@Override
public void menuCanceled(MenuEvent e) {
menuDisplayed = false;
}
@Override
public void menuDeselected(MenuEvent e) {
menuDisplayed = false;
}
});
JMenuItem javadocs = new JMenuItem("Javadocs");
javadocs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
launchBrowserThatWorks("https://www.codenameone.com/javadoc/");
}
});
helpMenu.add(javadocs);
JMenuItem how = new JMenuItem("How Do I?...");
how.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
launchBrowserThatWorks("https://www.codenameone.com/how-do-i.html");
}
});
helpMenu.add(how);
JMenuItem forum = new JMenuItem("Community Forum");
forum.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
launchBrowserThatWorks("https://www.codenameone.com/discussion-forum.html");
}
});
helpMenu.add(forum);
JMenuItem bserver = new JMenuItem("Build Server");
bserver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
launchBrowserThatWorks("https://cloud.codenameone.com/secure/index.html");
}
});
helpMenu.addSeparator();
helpMenu.add(bserver);
helpMenu.addSeparator();
JMenuItem about = new JMenuItem("About");
about.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JDialog about;
if (window != null) {
about = new JDialog(window);
} else {
about = new JDialog();
}
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JPanel imagePanel = new JPanel();
JLabel image = new JLabel(new javax.swing.ImageIcon(getClass().getResource("/CodenameOne_Small.png")));
image.setHorizontalAlignment(SwingConstants.CENTER);
imagePanel.add(image);
panel.add(imagePanel);
JPanel linkPanel = new JPanel();
JButton link = new JButton();
link.setText("<HTML>For more information, please <br>visit <FONT color=\"#000099\"><U>www.codenameone.com</U></FONT></HTML>");
link.setHorizontalAlignment(SwingConstants.LEFT);
link.setBorderPainted(false);
link.setOpaque(false);
link.setBackground(Color.WHITE);
link.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
launchBrowserThatWorks("https://www.codenameone.com");
}
});
linkPanel.add(link);
panel.add(linkPanel);
JPanel closePanel = new JPanel();
JButton close = new JButton("close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
about.dispose();
}
});
closePanel.add(close);
panel.add(closePanel);
about.add(panel);
about.pack();
if (window != null) {
about.setLocationRelativeTo(window);
}
about.setVisible(true);
}
});
helpMenu.add(about);
if (showMenu) {
bar.add(simulatorMenu);
bar.add(simulateMenu);
bar.add(toolsMenu);
bar.add(skinMenu);
bar.add(helpMenu);
}
alwaysOnTopFlag.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
alwaysOnTop = !alwaysOnTop;
Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
pref.putBoolean("AlwaysOnTop", alwaysOnTop);
window.setAlwaysOnTop(alwaysOnTop);
}
});
ItemListener zoomListener = new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
setScrollableSkin(!scrollableSkin);
if (scrollableSkin) {
if (appFrame == null) {
frm.add(java.awt.BorderLayout.SOUTH, hSelector);
frm.add(java.awt.BorderLayout.EAST, vSelector);
} else {
canvas.getParent().add(java.awt.BorderLayout.SOUTH, hSelector);
canvas.getParent().add(java.awt.BorderLayout.EAST, vSelector);
}
} else {
frm.remove(hSelector);
frm.remove(vSelector);
}
Container parent = canvas.getParent();
parent.remove(canvas);
if (scrollableSkin) {
canvas.setForcedSize(new java.awt.Dimension((int) (getSkin().getWidth() / retinaScale), (int) (getSkin().getHeight() / retinaScale)));
} else {
int screenH = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getHeight();
int screenW = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getWidth();
float zoomY = getSkin().getHeight() > screenH ? screenH / (float) getSkin().getHeight() : 1f;
float zoomX = getSkin().getWidth() > screenW ? screenW / (float) getSkin().getWidth() : 1f;
float zoom = Math.min(zoomX, zoomY);
canvas.setForcedSize(new java.awt.Dimension((int) (getSkin().getWidth() * zoom), (int) (getSkin().getHeight() * zoom)));
if (window != null) {
if (appFrame == null) {
window.setSize(new java.awt.Dimension((int) (getSkin().getWidth() * zoom), (int) (getSkin().getHeight() * zoom)));
}
}
}
parent.add(BorderLayout.CENTER, canvas);
canvas.x = 0;
canvas.y = 0;
zoomLevel = 1;
frm.invalidate();
frm.pack();
Display.getInstance().getCurrent().repaint();
frm.repaint();
}
};
zoomMenu.addItemListener(zoomListener);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
exitApplication();
}
});
}
use of com.codename1.components.Switch in project CodenameOne by codenameone.
the class JavaSEPort method loadTrueTypeFont.
@Override
public Object loadTrueTypeFont(String fontName, String fileName) {
File fontFile = null;
try {
if (fontName.startsWith("native:")) {
if (IS_MAC && isIOS) {
String nn = nativeFontName(fontName);
java.awt.Font nf = new java.awt.Font(nn, java.awt.Font.PLAIN, medianFontSize);
return nf;
}
String res;
switch(fontName) {
case "native:MainThin":
res = "Thin";
break;
case "native:MainLight":
res = "Light";
break;
case "native:MainRegular":
res = "Medium";
break;
case "native:MainBold":
res = "Bold";
break;
case "native:MainBlack":
res = "Black";
break;
case "native:ItalicThin":
res = "ThinItalic";
break;
case "native:ItalicLight":
res = "LightItalic";
break;
case "native:ItalicRegular":
res = "Italic";
break;
case "native:ItalicBold":
res = "BoldItalic";
break;
case "native:ItalicBlack":
res = "BlackItalic";
break;
default:
throw new IllegalArgumentException("Unsupported native font type: " + fontName);
}
String fontResourcePath = "/com/codename1/impl/javase/Roboto-" + res + ".ttf";
InputStream is = getClass().getResourceAsStream(fontResourcePath);
if (is != null) {
java.awt.Font fnt;
try {
fnt = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, is);
} catch (Exception e) {
System.err.println("Exception while reading font from resource path " + fontResourcePath);
throw e;
}
is.close();
return fnt;
}
}
if (baseResourceDir != null) {
fontFile = new File(baseResourceDir, fileName);
} else {
fontFile = new File(getSourceResourcesDir(), fileName);
}
if (fontFile.exists()) {
try {
FileInputStream fs = new FileInputStream(fontFile);
java.awt.Font fnt = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, fs);
fs.close();
if (fnt != null) {
if (!fontName.startsWith(fnt.getFamily())) {
System.out.println("Warning font name might be wrong for " + fileName + " should be: " + fnt.getName());
}
}
return fnt;
} catch (Exception e) {
System.err.println("Exception thrown while trying to create font from file " + fontFile);
throw e;
}
} else {
InputStream is = getResourceAsStream(getClass(), "/" + fileName);
if (is != null) {
try {
java.awt.Font fnt = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, is);
is.close();
if (fnt != null) {
if (!fontName.startsWith(fnt.getFamily())) {
System.out.println("Warning font name might be wrong for " + fileName + " should be: " + fnt.getName());
}
}
return fnt;
} catch (Exception e) {
System.err.println("Exception thrown while trying to create font file from resource path " + "/" + fileName);
throw e;
}
}
}
} catch (Exception err) {
err.printStackTrace();
throw new RuntimeException(err);
}
if (fontFile != null) {
throw new RuntimeException("The file wasn't found: " + fontFile.getAbsolutePath());
}
throw new RuntimeException("The file wasn't found: " + fontName);
}
Aggregations