use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.
the class UIManager method buildTheme.
private void buildTheme(Hashtable themeProps) {
String con = (String) themeProps.get("@includeNativeBool");
if (con != null && con.equalsIgnoreCase("true") && Display.getInstance().hasNativeTheme()) {
boolean a = accessible;
accessible = true;
Display.getInstance().installNativeTheme();
accessible = a;
}
Enumeration e = themeProps.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
// this is a constant not a theme entry
if (key.startsWith("@")) {
themeConstants.put(key.substring(1, key.length()), themeProps.get(key));
continue;
}
this.themeProps.put(key, themeProps.get(key));
}
// necessary to clear up the style so we don't get resedue from the previous UI
defaultStyle = new Style();
// create's the default style
defaultStyle = createStyle("", "", false);
defaultSelectedStyle = new Style(defaultStyle);
defaultSelectedStyle = createStyle("", "sel#", true);
String overlayThemes = (String) themeProps.get("@OverlayThemes");
if (overlayThemes != null) {
java.util.List<String> overlayThemesArr = StringUtil.tokenize(overlayThemes, ',');
for (String th : overlayThemesArr) {
th = th.trim();
if (th.length() == 0) {
continue;
}
try {
Resources res = Resources.openLayered("/" + th);
boolean a = accessible;
accessible = true;
addThemeProps(res.getTheme(res.getThemeResourceNames()[0]));
accessible = a;
} catch (Exception ex) {
System.err.println("Failed to load overlay theme file specified by @overlayThemes theme constant: " + th);
Log.e(ex);
}
}
}
}
use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.
the class InstantUI method createEditUI.
/**
* Creates editing UI for the given business object
* @param bo the business object
* @param autoCommit true if the bindings used should be auto-committed
* @return a UI container that can be used to edit the business object
*/
public Container createEditUI(PropertyBusinessObject bo, boolean autoCommit) {
Container cnt;
if (Display.getInstance().isTablet()) {
TableLayout tl = new TableLayout(1, 2);
tl.setGrowHorizontally(true);
cnt = new Container(tl);
} else {
cnt = new Container(BoxLayout.y());
}
UiBinding uib = new UiBinding();
ArrayList<UiBinding.Binding> allBindings = new ArrayList<UiBinding.Binding>();
for (PropertyBase b : bo.getPropertyIndex()) {
if (isExcludedProperty(b)) {
continue;
}
Class cls = (Class) b.getClientProperty("cn1$cmpCls");
if (cls != null) {
try {
Component cmp = (Component) cls.newInstance();
cmp.setName(b.getName());
cnt.add(b.getLabel()).add(cmp);
allBindings.add(uib.bind(b, cmp));
} catch (Exception err) {
Log.e(err);
throw new RuntimeException("Custom property instant UI failed for " + b.getName() + " " + err);
}
continue;
}
String[] multiLabels = (String[]) b.getClientProperty("cn1$multiChceLbl");
if (multiLabels != null) {
// multi choice component
final Object[] multiValues = (Object[]) b.getClientProperty("cn1$multiChceVal");
if (multiLabels.length < 5) {
// toggle buttons
ButtonGroup bg = new ButtonGroup();
RadioButton[] rbs = new RadioButton[multiLabels.length];
cnt.add(b.getLabel());
Container radioBox = new Container(new GridLayout(multiLabels.length));
for (int iter = 0; iter < multiLabels.length; iter++) {
rbs[iter] = RadioButton.createToggle(multiLabels[iter], bg);
radioBox.add(rbs[iter]);
}
cnt.add(radioBox);
allBindings.add(uib.bindGroup(b, multiValues, rbs));
} else {
Picker stringPicker = new Picker();
stringPicker.setStrings(multiLabels);
Map<Object, Object> m1 = new HashMap<Object, Object>();
Map<Object, Object> m2 = new HashMap<Object, Object>();
for (int iter = 0; iter < multiLabels.length; iter++) {
m1.put(multiLabels[iter], multiValues[iter]);
m2.put(multiValues[iter], multiLabels[iter]);
}
cnt.add(b.getLabel()).add(stringPicker);
allBindings.add(uib.bind(b, stringPicker, new UiBinding.PickerAdapter<Object>(new UiBinding.MappingConverter(m1), new UiBinding.MappingConverter(m2))));
}
continue;
}
Class t = b.getGenericType();
if (t != null) {
if (t == Boolean.class) {
CheckBox cb = new CheckBox();
uib.bind(b, cb);
cnt.add(b.getLabel()).add(cb);
continue;
}
if (t == Date.class) {
Picker dp = new Picker();
dp.setType(Display.PICKER_TYPE_DATE);
uib.bind(b, dp);
cnt.add(b.getLabel()).add(dp);
continue;
}
}
TextField tf = new TextField();
tf.setConstraint(getTextFieldConstraint(b));
uib.bind(b, tf);
cnt.add(b.getLabel()).add(tf);
}
cnt.putClientProperty("cn1$iui-binding", uib.createGroupBinding(allBindings));
return cnt;
}
use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.
the class EditableResources method saveXMLFile.
private void saveXMLFile(File xml, File resourcesDir) throws IOException {
// disable override for the duration of the save so stuff from the override doesn't
// get into the main resource file
File overrideFileBackup = overrideFile;
EditableResources overrideResourceBackup = overrideResource;
overrideResource = null;
overrideFile = null;
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xml), "UTF-8"));
String[] resourceNames = getResourceNames();
Arrays.sort(resourceNames, String.CASE_INSENSITIVE_ORDER);
bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
bw.write("<resource majorVersion=\"" + MAJOR_VERSION + "\" minorVersion=\"" + MINOR_VERSION + "\" useXmlUI=\"" + xmlUI + "\">\n");
for (int iter = 0; iter < resourceNames.length; iter++) {
String xResourceName = xmlize(resourceNames[iter]);
// write the magic number
byte magic = getResourceType(resourceNames[iter]);
switch(magic) {
case MAGIC_TIMELINE:
case MAGIC_ANIMATION_LEGACY:
case MAGIC_IMAGE_LEGACY:
case MAGIC_INDEXED_IMAGE_LEGACY:
magic = MAGIC_IMAGE;
break;
case MAGIC_THEME_LEGACY:
magic = MAGIC_THEME;
break;
case MAGIC_FONT_LEGACY:
magic = MAGIC_FONT;
break;
}
switch(magic) {
case MAGIC_IMAGE:
Object o = getResourceObject(resourceNames[iter]);
if (!(o instanceof MultiImage)) {
o = null;
}
bw.write(" <image name=\"" + xResourceName + "\" ");
com.codename1.ui.Image image = getImage(resourceNames[iter]);
MultiImage mi = (MultiImage) o;
int rType = getImageType(image, mi);
switch(rType) {
// PNG file
case 0xf1:
// JPEG File
case 0xf2:
if (image instanceof EncodedImage) {
byte[] data = ((EncodedImage) image).getImageData();
writeToFile(data, new File(resourcesDir, normalizeFileName(resourceNames[iter])));
} else {
FileOutputStream fo = new FileOutputStream(new File(resourcesDir, normalizeFileName(resourceNames[iter])));
BufferedImage buffer = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
buffer.setRGB(0, 0, image.getWidth(), image.getHeight(), image.getRGB(), 0, image.getWidth());
ImageIO.write(buffer, "png", fo);
fo.close();
}
break;
// SVG
case 0xf5:
// multiimage with SVG
case 0xf7:
SVG s = (SVG) image.getSVGDocument();
writeToFile(s.getSvgData(), new File(resourcesDir, normalizeFileName(resourceNames[iter])));
if (s.getBaseURL() != null && s.getBaseURL().length() > 0) {
bw.write("baseUrl=\"" + s.getBaseURL() + "\" ");
}
bw.write("type=\"svg\" ");
break;
case 0xF6:
File multiImageDir = new File(resourcesDir, normalizeFileName(resourceNames[iter]));
multiImageDir.mkdirs();
for (int imageIter = 0; imageIter < mi.getDpi().length; imageIter++) {
File f = null;
switch(mi.getDpi()[imageIter]) {
case Display.DENSITY_4K:
f = new File(multiImageDir, "4k.png");
break;
case Display.DENSITY_2HD:
f = new File(multiImageDir, "2hd.png");
break;
case Display.DENSITY_560:
f = new File(multiImageDir, "560.png");
break;
case Display.DENSITY_HD:
f = new File(multiImageDir, "hd.png");
break;
case Display.DENSITY_VERY_HIGH:
f = new File(multiImageDir, "veryhigh.png");
break;
case Display.DENSITY_HIGH:
f = new File(multiImageDir, "high.png");
break;
case Display.DENSITY_MEDIUM:
f = new File(multiImageDir, "medium.png");
break;
case Display.DENSITY_LOW:
f = new File(multiImageDir, "low.png");
break;
case Display.DENSITY_VERY_LOW:
f = new File(multiImageDir, "verylow.png");
break;
}
writeToFile(mi.getInternalImages()[imageIter].getImageData(), f);
}
bw.write("type=\"multi\" ");
break;
// Timeline
case MAGIC_TIMELINE:
File timeline = new File(resourcesDir, normalizeFileName(resourceNames[iter]));
DataOutputStream timelineOut = new DataOutputStream(new FileOutputStream(timeline));
writeTimeline(timelineOut, (Timeline) image);
timelineOut.close();
bw.write("type=\"timeline\" ");
break;
// Fail this is the wrong data type
default:
throw new IOException("Illegal type while creating image: " + Integer.toHexString(rType));
}
bw.write(" />\n");
continue;
case MAGIC_THEME:
Hashtable<String, Object> theme = getTheme(resourceNames[iter]);
theme.remove("name");
bw.write(" <theme name=\"" + xResourceName + "\">\n");
ArrayList<String> setOfKeys = new ArrayList<String>(theme.keySet());
Collections.sort(setOfKeys);
for (String key : setOfKeys) {
if (key.startsWith("@")) {
if (key.endsWith("Image")) {
bw.write(" <val key=\"" + key + "\" value=\"" + findId(theme.get(key), true) + "\" />\n");
} else {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
}
continue;
}
// if this is a simple numeric value
if (key.endsWith("Color")) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
if (key.endsWith("align") || key.endsWith("textDecoration")) {
bw.write(" <val key=\"" + key + "\" value=\"" + ((Number) theme.get(key)).shortValue() + "\" />\n");
continue;
}
// if this is a short numeric value
if (key.endsWith("transparency")) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
if (key.endsWith("opacity")) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
// if this is a padding or margin then we will have the 4 values as bytes
if (key.endsWith("padding") || key.endsWith("margin")) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
// padding and or margin type
if (key.endsWith("Unit")) {
byte[] b = (byte[]) theme.get(key);
bw.write(" <val key=\"" + key + "\" value=\"" + b[0] + "," + b[1] + "," + b[2] + "," + b[3] + "\" />\n");
continue;
}
if (key.endsWith("border")) {
Border border = (Border) theme.get(key);
if (border instanceof RoundBorder) {
RoundBorder rb = (RoundBorder) border;
bw.write(" <border key=\"" + key + "\" type=\"round\" " + "roundBorderColor=\"" + rb.getColor() + "\" " + "opacity=\"" + rb.getOpacity() + "\" " + "strokeColor=\"" + rb.getStrokeColor() + "\" " + "strokeOpacity=\"" + rb.getStrokeOpacity() + "\" " + "strokeThickness=\"" + rb.getStrokeThickness() + "\" " + "strokeMM=\"" + rb.isStrokeMM() + "\" " + "shadowSpread=\"" + rb.getShadowSpread() + "\" " + "shadowOpacity=\"" + rb.getShadowOpacity() + "\" " + "shadowX=\"" + rb.getShadowX() + "\" " + "shadowY=\"" + rb.getShadowY() + "\" " + "shadowBlur=\"" + rb.getShadowBlur() + "\" " + "shadowMM=\"" + rb.isShadowMM() + "\" " + "rectangle=\"" + rb.isRectangle() + "\" />\n");
continue;
}
if (border instanceof RoundRectBorder) {
RoundRectBorder rb = (RoundRectBorder) border;
bw.write(" <border key=\"" + key + "\" type=\"roundRect\" " + "strokeColor=\"" + rb.getStrokeColor() + "\" " + "strokeOpacity=\"" + rb.getStrokeOpacity() + "\" " + "strokeThickness=\"" + rb.getStrokeThickness() + "\" " + "strokeMM=\"" + rb.isStrokeMM() + "\" " + "shadowSpread=\"" + rb.getShadowSpread() + "\" " + "shadowOpacity=\"" + rb.getShadowOpacity() + "\" " + "shadowX=\"" + rb.getShadowX() + "\" " + "shadowY=\"" + rb.getShadowY() + "\" " + "shadowBlur=\"" + rb.getShadowBlur() + "\" " + "topOnlyMode=\"" + rb.isTopOnlyMode() + "\" " + "bottomOnlyMode=\"" + rb.isBottomOnlyMode() + "\" " + "cornerRadius=\"" + rb.getCornerRadius() + "\" " + "bezierCorners=\"" + rb.isBezierCorners() + "\" />\n");
continue;
}
int type = Accessor.getType(border);
switch(type) {
case BORDER_TYPE_EMPTY:
bw.write(" <border key=\"" + key + "\" type=\"empty\" />\n");
continue;
case BORDER_TYPE_LINE:
// use theme colors?
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"line\" millimeters=\"" + Accessor.isMillimeters(border) + "\" thickness=\"" + Accessor.getThickness(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"line\" millimeters=\"" + Accessor.isMillimeters(border) + "\" thickness=\"" + Accessor.getThickness(border) + "\" color=\"" + Accessor.getColorA(border) + "\" />\n");
}
continue;
case BORDER_TYPE_UNDERLINE:
// use theme colors?
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"underline\" millimeters=\"" + Accessor.isMillimeters(border) + "\" thickness=\"" + Accessor.getThickness(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"underline\" millimeters=\"" + Accessor.isMillimeters(border) + "\" thickness=\"" + Accessor.getThickness(border) + "\" color=\"" + Accessor.getColorA(border) + "\" />\n");
}
continue;
case BORDER_TYPE_ROUNDED:
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"rounded\" " + "thickness=\"" + Accessor.getThickness(border) + "\" arcW=\"" + Accessor.getArcWidth(border) + "\" arcH=\"" + Accessor.getArcHeight(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"rounded\" " + "thickness=\"" + Accessor.getThickness(border) + "\" arcW=\"" + Accessor.getArcWidth(border) + "\" arcH=\"" + Accessor.getArcHeight(border) + "\" color=\"" + Accessor.getColorA(border) + "\" />\n");
}
continue;
case BORDER_TYPE_ETCHED_RAISED:
// use theme colors?
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"etchedRaised\" " + "thickness=\"" + Accessor.getThickness(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"etchedRaised\" " + "thickness=\"" + Accessor.getThickness(border) + "\" color=\"" + Accessor.getColorA(border) + "\" colorB=\"" + Accessor.getColorB(border) + "\" />\n");
}
continue;
case BORDER_TYPE_ETCHED_LOWERED:
// use theme colors?
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"etchedLowered\" " + "thickness=\"" + Accessor.getThickness(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"etchedLowered\" " + "thickness=\"" + Accessor.getThickness(border) + "\" color=\"" + Accessor.getColorA(border) + "\" colorB=\"" + Accessor.getColorB(border) + "\" />\n");
}
continue;
case BORDER_TYPE_BEVEL_LOWERED:
// use theme colors?
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"bevelLowered\" " + "thickness=\"" + Accessor.getThickness(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"bevelLowered\" " + "thickness=\"" + Accessor.getThickness(border) + "\" color=\"" + Accessor.getColorA(border) + "\" colorB=\"" + Accessor.getColorB(border) + "\" colorC=\"" + Accessor.getColorC(border) + "\" colorD=\"" + Accessor.getColorD(border) + "\" />\n");
}
continue;
case BORDER_TYPE_BEVEL_RAISED:
if (Accessor.isThemeColors(border)) {
bw.write(" <border key=\"" + key + "\" type=\"bevelRaised\" " + "thickness=\"" + Accessor.getThickness(border) + "\" />\n");
} else {
bw.write(" <border key=\"" + key + "\" type=\"bevelRaised\" " + "thickness=\"" + Accessor.getThickness(border) + "\" color=\"" + Accessor.getColorA(border) + "\" colorB=\"" + Accessor.getColorB(border) + "\" colorC=\"" + Accessor.getColorC(border) + "\" colorD=\"" + Accessor.getColorD(border) + "\" />\n");
}
continue;
// case BORDER_TYPE_IMAGE_SCALED:
case BORDER_TYPE_IMAGE:
{
Image[] images = Accessor.getImages(border);
int resourceCount = 0;
for (int counter = 0; counter < images.length; counter++) {
if (images[counter] != null && findId(images[counter], true) != null) {
resourceCount++;
}
}
if (resourceCount != 2 && resourceCount != 3 && resourceCount != 8 && resourceCount != 9) {
System.out.println("Odd resource count for image border: " + resourceCount);
resourceCount = 2;
}
switch(resourceCount) {
case 2:
bw.write(" <border key=\"" + key + "\" type=\"image\" " + "i1=\"" + findId(images[0], true) + "\" " + "i2=\"" + findId(images[4], true) + "\" />\n");
break;
case 3:
bw.write(" <border key=\"" + key + "\" type=\"image\" " + "i1=\"" + findId(images[0], true) + "\" " + "i2=\"" + findId(images[4], true) + "\" " + "i3=\"" + findId(images[8], true) + "\" />\n");
break;
case 8:
bw.write(" <border key=\"" + key + "\" type=\"image\" " + "i1=\"" + findId(images[0], true) + "\" " + "i2=\"" + findId(images[1], true) + "\" " + "i3=\"" + findId(images[2], true) + "\" " + "i4=\"" + findId(images[3], true) + "\" " + "i5=\"" + findId(images[4], true) + "\" " + "i6=\"" + findId(images[5], true) + "\" " + "i7=\"" + findId(images[6], true) + "\" " + "i8=\"" + findId(images[7], true) + "\" />\n");
break;
case 9:
bw.write(" <border key=\"" + key + "\" type=\"image\" " + "i1=\"" + findId(images[0], true) + "\" " + "i2=\"" + findId(images[1], true) + "\" " + "i3=\"" + findId(images[2], true) + "\" " + "i4=\"" + findId(images[3], true) + "\" " + "i5=\"" + findId(images[4], true) + "\" " + "i6=\"" + findId(images[5], true) + "\" " + "i7=\"" + findId(images[6], true) + "\" " + "i8=\"" + findId(images[7], true) + "\" " + "i9=\"" + findId(images[8], true) + "\" />\n");
break;
}
continue;
}
case BORDER_TYPE_IMAGE_HORIZONTAL:
{
Image[] images = Accessor.getImages(border);
bw.write(" <border key=\"" + key + "\" type=\"imageH\" " + "i1=\"" + findId(images[0], true) + "\" " + "i2=\"" + findId(images[1], true) + "\" " + "i3=\"" + findId(images[2], true) + "\" />\n");
continue;
}
case BORDER_TYPE_IMAGE_VERTICAL:
{
Image[] images = Accessor.getImages(border);
bw.write(" <border key=\"" + key + "\" type=\"imageV\" " + "i1=\"" + findId(images[0], true) + "\" " + "i2=\"" + findId(images[1], true) + "\" " + "i3=\"" + findId(images[2], true) + "\" />\n");
continue;
}
}
continue;
}
// if this is a font
if (key.endsWith("font")) {
com.codename1.ui.Font f = (com.codename1.ui.Font) theme.get(key);
// is this a new font?
boolean newFont = f instanceof EditorFont;
if (newFont) {
bw.write(" <font key=\"" + key + "\" type=\"named\" " + "name=\"" + findId(f) + "\" />\n");
} else {
if (f instanceof EditorTTFFont && (((EditorTTFFont) f).getFontFile() != null || ((EditorTTFFont) f).getNativeFontName() != null)) {
EditorTTFFont ed = (EditorTTFFont) f;
String fname;
String ffName;
if (((EditorTTFFont) f).getNativeFontName() != null) {
fname = ((EditorTTFFont) f).getNativeFontName();
ffName = fname;
} else {
fname = ed.getFontFile().getName();
ffName = ((java.awt.Font) ed.getNativeFont()).getPSName();
}
bw.write(" <font key=\"" + key + "\" type=\"ttf\" " + "face=\"" + f.getFace() + "\" " + "style=\"" + f.getStyle() + "\" " + "size=\"" + f.getSize() + "\" " + "name=\"" + fname + "\" " + "family=\"" + ffName + "\" " + "sizeSettings=\"" + ed.getSizeSetting() + "\" " + "actualSize=\"" + ed.getActualSize() + "\" />\n");
} else {
bw.write(" <font key=\"" + key + "\" type=\"system\" " + "face=\"" + f.getFace() + "\" " + "style=\"" + f.getStyle() + "\" " + "size=\"" + f.getSize() + "\" />\n");
}
}
continue;
}
// if this is a background image
if (key.endsWith("bgImage")) {
bw.write(" <val key=\"" + key + "\" value=\"" + findId(theme.get(key), true) + "\" />\n");
continue;
}
if (key.endsWith("scaledImage")) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
if (key.endsWith("derive")) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
// if this is a background gradient
if (key.endsWith("bgGradient")) {
Object[] gradient = (Object[]) theme.get(key);
bw.write(" <gradient key=\"" + key + "\" color1=\"" + gradient[0] + "\"" + " color2=\"" + gradient[1] + "\"" + " posX=\"" + gradient[2] + "\"" + " posY=\"" + gradient[3] + "\"" + " radius=\"" + gradient[4] + "\" />\n");
continue;
}
if (key.endsWith(Style.BACKGROUND_TYPE) || key.endsWith(Style.BACKGROUND_ALIGNMENT)) {
bw.write(" <val key=\"" + key + "\" value=\"" + theme.get(key) + "\" />\n");
continue;
}
// thow an exception no idea what this is
throw new IOException("Error while trying to read theme property: " + key);
}
bw.write(" </theme>\n");
continue;
case MAGIC_FONT:
File legacyFont = new File(resourcesDir, normalizeFileName(resourceNames[iter]));
DataOutputStream legacyFontOut = new DataOutputStream(new FileOutputStream(legacyFont));
saveFont(legacyFontOut, false, resourceNames[iter]);
legacyFontOut.close();
bw.write(" <legacyFont name=\"" + xResourceName + "\" />\n");
continue;
case MAGIC_DATA:
{
File dataFile = new File(resourcesDir, normalizeFileName(resourceNames[iter]));
DataOutputStream dataFileOut = new DataOutputStream(new FileOutputStream(dataFile));
InputStream i = getData(resourceNames[iter]);
ByteArrayOutputStream outArray = new ByteArrayOutputStream();
int val = i.read();
while (val != -1) {
outArray.write(val);
val = i.read();
}
byte[] data = outArray.toByteArray();
dataFileOut.write(data);
dataFileOut.close();
bw.write(" <data name=\"" + xResourceName + "\" />\n");
continue;
}
case MAGIC_UI:
{
File uiXML = new File(resourcesDir, resourceNames[iter] + ".ui");
UIBuilderOverride u = new UIBuilderOverride();
com.codename1.ui.Container cnt = u.createContainer(this, resourceNames[iter]);
FileOutputStream fos = new FileOutputStream(uiXML);
writeUIXml(cnt, fos);
fos.close();
File ui = new File(resourcesDir, resourceNames[iter]);
DataOutputStream uiOut = new DataOutputStream(new FileOutputStream(ui));
InputStream i = getUi(resourceNames[iter]);
ByteArrayOutputStream outArray = new ByteArrayOutputStream();
int val = i.read();
while (val != -1) {
outArray.write(val);
val = i.read();
}
byte[] data = outArray.toByteArray();
uiOut.write(data);
uiOut.close();
bw.write(" <ui name=\"" + xResourceName + "\" />\n");
continue;
}
case MAGIC_L10N:
// we are getting the theme which allows us to acces the l10n data
bw.write(" <l10n name=\"" + xResourceName + "\">\n");
Hashtable<String, Object> l10n = getTheme(resourceNames[iter]);
for (String locale : l10n.keySet()) {
bw.write(" <lang name=\"" + locale + "\">\n");
Hashtable<String, String> current = (Hashtable<String, String>) l10n.get(locale);
for (String key : current.keySet()) {
String val = current.get(key);
bw.write(" <entry key=\"" + xmlize(key) + "\" value=\"" + xmlize(val) + "\" />\n");
}
bw.write(" </lang>\n");
}
bw.write(" </l10n>\n");
continue;
default:
throw new IOException("Corrupt theme file unrecognized magic number: " + Integer.toHexString(magic & 0xff));
}
}
bw.write("</resource>\n");
bw.close();
} finally {
overrideFile = overrideFileBackup;
overrideResource = overrideResourceBackup;
}
}
use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.
the class ResourceEditorView method generateStateMachineCodeImpl.
private static String generateStateMachineCodeImpl(String uiResourceName, File destFile, boolean promptUserForPackageName, EditableResources loadResources, java.awt.Component errorParent) {
String packageString = "";
File currentFile = destFile;
while (currentFile.getParent() != null) {
String shortName = currentFile.getParentFile().getName();
if (shortName.equalsIgnoreCase("src")) {
break;
}
if (shortName.indexOf(':') > -1 || shortName.length() == 0) {
break;
}
if (shortName.equalsIgnoreCase("org") || shortName.equalsIgnoreCase("com") || shortName.equalsIgnoreCase("net") || shortName.equalsIgnoreCase("gov")) {
if (packageString.length() > 0) {
packageString = shortName + "." + packageString;
} else {
packageString = shortName;
}
break;
}
if (packageString.length() > 0) {
packageString = shortName + "." + packageString;
} else {
packageString = shortName;
}
currentFile = currentFile.getParentFile();
}
final Map<String, String> nameToClassLookup = new HashMap<String, String>();
final Map<String, Integer> commandMap = new HashMap<String, Integer>();
final List<Integer> unhandledCommands = new ArrayList<Integer>();
final List<String[]> actionComponents = new ArrayList<String[]>();
final Map<String, String> allComponents = new HashMap<String, String>();
initCommandMapAndNameToClassLookup(nameToClassLookup, commandMap, unhandledCommands, actionComponents, allComponents);
// list all the .ovr files and add them to the nameToClassLookup
if (loadedFile != null && loadedFile.getParentFile() != null) {
File overrideDir = new File(loadedFile.getParentFile().getParentFile(), "override");
if (overrideDir.exists()) {
File[] ovrFiles = overrideDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String string) {
return string.endsWith(".ovr");
}
});
for (File ovr : ovrFiles) {
try {
EditableResources er = EditableResources.open(new FileInputStream(ovr));
for (String currentResourceName : er.getUIResourceNames()) {
UIBuilder b = new UIBuilder() {
protected com.codename1.ui.Component createComponentInstance(String componentType, Class cls) {
if (cls.getName().startsWith("com.codename1.ui.")) {
// subpackage of CodenameOne should be registered
if (cls.getName().lastIndexOf(".") > 15) {
nameToClassLookup.put(componentType, cls.getName());
}
} else {
nameToClassLookup.put(componentType, cls.getName());
}
return null;
}
};
b.createContainer(er, currentResourceName);
}
} catch (IOException ioErr) {
ioErr.printStackTrace();
}
}
}
}
if (promptUserForPackageName) {
JTextField packageName = new JTextField(packageString);
JOptionPane.showMessageDialog(errorParent, packageName, "Please Pick The Package Name", JOptionPane.PLAIN_MESSAGE);
packageString = packageName.getText();
}
List<String> createdMethodNames = new ArrayList<String>();
try {
Writer w = new FileWriter(destFile);
w.write("/**\n");
w.write(" * This class contains generated code from the Codename One Designer, DO NOT MODIFY!\n");
w.write(" * This class is designed for subclassing that way the code generator can overwrite it\n");
w.write(" * anytime without erasing your changes which should exist in a subclass!\n");
w.write(" * For details about this file and how it works please read this blog post:\n");
w.write(" * http://codenameone.blogspot.com/2010/10/ui-builder-class-how-to-actually-use.html\n");
w.write("*/\n");
if (packageString.length() > 0) {
w.write("package " + packageString + ";\n\n");
}
String className = destFile.getName().substring(0, destFile.getName().indexOf('.'));
boolean hasIo = false;
for (String currentName : nameToClassLookup.keySet()) {
if (nameToClassLookup.get(currentName).indexOf("com.codename1.ui.io") > -1) {
hasIo = true;
break;
}
}
w.write("import com.codename1.ui.*;\n");
w.write("import com.codename1.ui.util.*;\n");
w.write("import com.codename1.ui.plaf.*;\n");
w.write("import java.util.Hashtable;\n");
if (hasIo) {
w.write("import com.codename1.ui.io.*;\n");
w.write("import com.codename1.components*;\n");
}
w.write("import com.codename1.ui.events.*;\n\n");
w.write("public abstract class " + className + " extends UIBuilder {\n");
w.write(" private Container aboutToShowThisContainer;\n");
w.write(" /**\n");
w.write(" * this method should be used to initialize variables instead of\n");
w.write(" * the constructor/class scope to avoid race conditions\n");
w.write(" */\n");
w.write(" /**\n * @deprecated use the version that accepts a resource as an argument instead\n \n**/\n");
w.write(" protected void initVars() {}\n\n");
w.write(" protected void initVars(Resources res) {}\n\n");
w.write(" public " + className + "(Resources res, String resPath, boolean loadTheme) {\n");
w.write(" startApp(res, resPath, loadTheme);\n");
w.write(" }\n\n");
w.write(" public Container startApp(Resources res, String resPath, boolean loadTheme) {\n");
w.write(" initVars();\n");
if (hasIo) {
w.write(" NetworkManager.getInstance().start();\n");
}
for (String currentName : nameToClassLookup.keySet()) {
w.write(" UIBuilder.registerCustomComponent(\"" + currentName + "\", " + nameToClassLookup.get(currentName) + ".class);\n");
}
w.write(" if(loadTheme) {\n");
w.write(" if(res == null) {\n");
w.write(" try {\n");
w.write(" if(resPath.endsWith(\".res\")) {\n");
w.write(" res = Resources.open(resPath);\n");
w.write(" System.out.println(\"Warning: you should construct the state machine without the .res extension to allow theme overlays\");\n");
w.write(" } else {\n");
w.write(" res = Resources.openLayered(resPath);\n");
w.write(" }\n");
w.write(" } catch(java.io.IOException err) { err.printStackTrace(); }\n");
w.write(" }\n");
w.write(" initTheme(res);\n");
w.write(" }\n");
w.write(" if(res != null) {\n");
w.write(" setResourceFilePath(resPath);\n");
w.write(" setResourceFile(res);\n");
w.write(" initVars(res);\n");
w.write(" return showForm(getFirstFormName(), null);\n");
w.write(" } else {\n");
w.write(" Form f = (Form)createContainer(resPath, getFirstFormName());\n");
w.write(" initVars(fetchResourceFile());\n");
w.write(" beforeShow(f);\n");
w.write(" f.show();\n");
w.write(" postShow(f);\n");
w.write(" return f;\n");
w.write(" }\n");
w.write(" }\n\n");
w.write(" protected String getFirstFormName() {\n");
w.write(" return \"" + uiResourceName + "\";\n");
w.write(" }\n\n");
w.write(" public Container createWidget(Resources res, String resPath, boolean loadTheme) {\n");
w.write(" initVars();\n");
if (hasIo) {
w.write(" NetworkManager.getInstance().start();\n");
}
for (String currentName : nameToClassLookup.keySet()) {
w.write(" UIBuilder.registerCustomComponent(\"" + currentName + "\", " + nameToClassLookup.get(currentName) + ".class);\n");
}
w.write(" if(loadTheme) {\n");
w.write(" if(res == null) {\n");
w.write(" try {\n");
w.write(" res = Resources.openLayered(resPath);\n");
w.write(" } catch(java.io.IOException err) { err.printStackTrace(); }\n");
w.write(" }\n");
w.write(" initTheme(res);\n");
w.write(" }\n");
w.write(" return createContainer(resPath, \"" + uiResourceName + "\");\n");
w.write(" }\n\n");
w.write(" protected void initTheme(Resources res) {\n");
w.write(" String[] themes = res.getThemeResourceNames();\n");
w.write(" if(themes != null && themes.length > 0) {\n");
w.write(" UIManager.getInstance().setThemeProps(res.getTheme(themes[0]));\n");
w.write(" }\n");
w.write(" }\n\n");
w.write(" public " + className + "() {\n");
w.write(" }\n\n");
w.write(" public " + className + "(String resPath) {\n");
w.write(" this(null, resPath, true);\n");
w.write(" }\n\n");
w.write(" public " + className + "(Resources res) {\n");
w.write(" this(res, null, true);\n");
w.write(" }\n\n");
w.write(" public " + className + "(String resPath, boolean loadTheme) {\n");
w.write(" this(null, resPath, loadTheme);\n");
w.write(" }\n\n");
w.write(" public " + className + "(Resources res, boolean loadTheme) {\n");
w.write(" this(res, null, loadTheme);\n");
w.write(" }\n\n");
for (String componentName : allComponents.keySet()) {
String componentType = allComponents.get(componentName);
String methodName = " find" + normalizeFormName(componentName);
// exists without a space might trigger this situation and thus code that won't compile
if (!createdMethodNames.contains(methodName)) {
if (componentType.equals("com.codename1.ui.Form") || componentType.equals("com.codename1.ui.Dialog")) {
continue;
}
createdMethodNames.add(methodName);
w.write(" public " + componentType + methodName + "(Component root) {\n");
w.write(" return (" + componentType + ")" + "findByName(\"" + componentName + "\", root);\n");
w.write(" }\n\n");
w.write(" public " + componentType + methodName + "() {\n");
w.write(" " + componentType + " cmp = (" + componentType + ")" + "findByName(\"" + componentName + "\", Display.getInstance().getCurrent());\n");
w.write(" if(cmp == null && aboutToShowThisContainer != null) {\n");
w.write(" cmp = (" + componentType + ")" + "findByName(\"" + componentName + "\", aboutToShowThisContainer);\n");
w.write(" }\n");
w.write(" return cmp;\n");
w.write(" }\n\n");
}
}
if (commandMap.size() > 0) {
for (String key : commandMap.keySet()) {
w.write(" public static final int COMMAND_" + key + " = " + commandMap.get(key) + ";\n");
}
w.write("\n");
StringBuilder methodSwitch = new StringBuilder(" protected void processCommand(ActionEvent ev, Command cmd) {\n switch(cmd.getId()) {\n");
for (String key : commandMap.keySet()) {
String camelCase = "on" + key;
boolean isAbstract = unhandledCommands.contains(commandMap.get(key));
if (isAbstract) {
w.write(" protected abstract void ");
w.write(camelCase);
w.write("();\n\n");
} else {
w.write(" protected boolean ");
w.write(camelCase);
w.write("() {\n return false;\n }\n\n");
}
methodSwitch.append(" case COMMAND_");
methodSwitch.append(key);
methodSwitch.append(":\n");
methodSwitch.append(" ");
if (isAbstract) {
methodSwitch.append(camelCase);
methodSwitch.append("();\n break;\n\n");
} else {
methodSwitch.append("if(");
methodSwitch.append(camelCase);
methodSwitch.append("()) {\n ev.consume();\n return;\n }\n break;\n\n");
}
}
methodSwitch.append(" }\n if(ev.getComponent() != null) {\n handleComponentAction(ev.getComponent(), ev);\n }\n }\n\n");
w.write(methodSwitch.toString());
}
writeFormCallbackCode(w, " protected void exitForm(Form f) {\n", "f.getName()", "exit", "f", "Form f");
writeFormCallbackCode(w, " protected void beforeShow(Form f) {\n aboutToShowThisContainer = f;\n", "f.getName()", "before", "f", "Form f");
writeFormCallbackCode(w, " protected void beforeShowContainer(Container c) {\n aboutToShowThisContainer = c;\n", "c.getName()", "beforeContainer", "c", "Container c");
writeFormCallbackCode(w, " protected void postShow(Form f) {\n", "f.getName()", "post", "f", "Form f");
writeFormCallbackCode(w, " protected void postShowContainer(Container c) {\n", "c.getName()", "postContainer", "c", "Container c");
writeFormCallbackCode(w, " protected void onCreateRoot(String rootName) {\n", "rootName", "onCreate", "", "");
writeFormCallbackCode(w, " protected Hashtable getFormState(Form f) {\n Hashtable h = super.getFormState(f);\n", "f.getName()", "getState", "f, h", "Form f, Hashtable h", "return h;");
writeFormCallbackCode(w, " protected void setFormState(Form f, Hashtable state) {\n super.setFormState(f, state);\n", "f.getName()", "setState", "f, state", "Form f, Hashtable state");
List<String> listComponents = new ArrayList<String>();
for (String currentName : allComponents.keySet()) {
String value = allComponents.get(currentName);
if (value.equals("com.codename1.ui.List") || value.equals("com.codename1.ui.ComboBox") || value.equals("com.codename1.ui.list.MultiList") || value.equals("com.codename1.ui.Calendar")) {
listComponents.add(currentName);
}
}
List<String> containerListComponents = new ArrayList<String>();
for (String currentName : allComponents.keySet()) {
String value = allComponents.get(currentName);
if (value.equals("com.codename1.ui.list.ContainerList")) {
containerListComponents.add(currentName);
}
}
if (listComponents.size() > 0) {
w.write(" protected boolean setListModel(List cmp) {\n");
w.write(" String listName = cmp.getName();\n");
for (String listName : listComponents) {
w.write(" if(\"");
w.write(listName);
w.write("\".equals(listName)) {\n");
w.write(" return initListModel");
w.write(normalizeFormName(listName));
w.write("(cmp);\n }\n");
}
w.write(" return super.setListModel(cmp);\n }\n\n");
for (String listName : listComponents) {
w.write(" protected boolean initListModel");
w.write(normalizeFormName(listName));
w.write("(List cmp) {\n");
w.write(" return false;\n }\n\n");
}
}
if (containerListComponents.size() > 0) {
w.write(" protected boolean setListModel(com.codename1.ui.list.ContainerList cmp) {\n");
w.write(" String listName = cmp.getName();\n");
for (String listName : containerListComponents) {
w.write(" if(\"");
w.write(listName);
w.write("\".equals(listName)) {\n");
w.write(" return initListModel");
w.write(normalizeFormName(listName));
w.write("(cmp);\n }\n");
}
w.write(" return super.setListModel(cmp);\n }\n\n");
for (String listName : containerListComponents) {
w.write(" protected boolean initListModel");
w.write(normalizeFormName(listName));
w.write("(com.codename1.ui.list.ContainerList cmp) {\n");
w.write(" return false;\n }\n\n");
}
}
if (actionComponents.size() > 0) {
Object lastFormName = null;
StringBuilder methods = new StringBuilder();
w.write(" protected void handleComponentAction(Component c, ActionEvent event) {\n");
w.write(" Container rootContainerAncestor = getRootAncestor(c);\n");
w.write(" if(rootContainerAncestor == null) return;\n");
w.write(" String rootContainerName = rootContainerAncestor.getName();\n");
w.write(" Container leadParentContainer = c.getParent().getLeadParent();\n");
w.write(" if(leadParentContainer != null && leadParentContainer.getClass() != Container.class) {\n");
w.write(" c = c.getParent().getLeadParent();\n");
w.write(" }\n");
w.write(" if(rootContainerName == null) return;\n");
for (String[] currentCmp : actionComponents) {
if (lastFormName != currentCmp[1]) {
if (lastFormName != null) {
w.write(" }\n");
}
w.write(" if(rootContainerName.equals(\"");
w.write(currentCmp[1]);
w.write("\")) {\n");
lastFormName = currentCmp[1];
}
w.write(" if(\"");
w.write(currentCmp[0]);
w.write("\".equals(c.getName())) {\n");
String methodName = "on" + normalizeFormName(currentCmp[1]) + "_" + normalizeFormName(currentCmp[0]) + "Action";
w.write(" ");
w.write(methodName);
w.write("(c, event);\n");
w.write(" return;\n");
w.write(" }\n");
methods.append(" protected void ");
methods.append(methodName);
methods.append("(Component c, ActionEvent event) {\n }\n\n");
}
w.write(" }\n }\n\n");
w.write(methods.toString());
}
w.write("}\n");
w.close();
} catch (IOException ioErr) {
ioErr.printStackTrace();
JOptionPane.showMessageDialog(errorParent, "IO Error: " + ioErr, "IO Error", JOptionPane.ERROR_MESSAGE);
}
return packageString;
}
use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.
the class ResourceEditorView method initCommandMapAndNameToClassLookup.
private static void initCommandMapAndNameToClassLookup(final Map<String, String> nameToClassLookup, final Map<String, Integer> commandMap, final List<Integer> unhandledCommands, final List<String[]> actionComponentNames, final Map<String, String> allComponents) {
// register the proper handlers for the component types used
UIBuilderOverride.registerCustom();
PickMIDlet.getCustomComponents();
for (String currentResourceName : loadedResources.getUIResourceNames()) {
final String currentName = currentResourceName;
UIBuilder b = new UIBuilder() {
protected com.codename1.ui.Command createCommand(String commandName, com.codename1.ui.Image icon, int commandId, String action) {
if (unhandledCommands != null) {
if (action == null) {
unhandledCommands.add(commandId);
}
}
// we already have that command id...
if (commandMap.values().contains(commandId)) {
removeCommandDups(commandMap, commandId);
}
if (commandName == null || commandName.length() == 0) {
commandName = "Command" + commandId;
}
commandName = normalizeFormName(currentName) + normalizeFormName(commandName);
commandMap.put(commandName, commandId);
return super.createCommand(commandName, icon, commandId, action);
}
public boolean caseInsensitiveContainsKey(String s) {
return caseInsensitiveKey(s) != null;
}
public String caseInsensitiveKey(String s) {
for (String k : allComponents.keySet()) {
if (k.equalsIgnoreCase(s)) {
return k;
}
}
return null;
}
public void postCreateComponent(com.codename1.ui.Component cmp) {
if (allComponents != null) {
String name = cmp.getName();
String componentClass = cmp.getClass().getName();
if (allComponents.containsKey(name)) {
if (!componentClass.equals(allComponents.get(name))) {
allComponents.put(name, "com.codename1.ui.Component");
} else {
allComponents.put(name, componentClass);
}
} else {
if (!caseInsensitiveContainsKey(name)) {
allComponents.put(name, componentClass);
}
}
}
com.codename1.ui.Component actual = cmp;
if (cmp instanceof com.codename1.ui.Container) {
actual = ((com.codename1.ui.Container) cmp).getLeadComponent();
if (actual == null) {
actual = cmp;
}
}
if (actionComponentNames != null && (actual instanceof com.codename1.ui.Button || actual instanceof com.codename1.ui.List || actual instanceof com.codename1.ui.list.ContainerList || actual instanceof com.codename1.ui.TextArea || actual instanceof com.codename1.ui.Calendar)) {
if (actual instanceof com.codename1.ui.Button) {
if (((com.codename1.ui.Button) actual).getCommand() != null) {
return;
}
}
String componentName = cmp.getName();
for (String[] arr : actionComponentNames) {
if (arr[0].equals(componentName) && arr[1].equals(currentName)) {
return;
}
}
actionComponentNames.add(new String[] { componentName, currentName });
}
}
protected com.codename1.ui.Component createComponentInstance(String componentType, Class cls) {
if (cls.getName().startsWith("com.codename1.ui.")) {
// subpackage of CodenameOne should be registered
if (cls.getName().lastIndexOf(".") > 15) {
nameToClassLookup.put(componentType, cls.getName());
}
} else {
nameToClassLookup.put(componentType, cls.getName());
}
return null;
}
};
b.createContainer(loadedResources, currentResourceName);
}
}
Aggregations