Search in sources :

Example 6 with File

use of com.codename1.io.File 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;
}
Also used : HashMap(java.util.HashMap) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) UIBuilder(com.codename1.ui.util.UIBuilder) JTextField(javax.swing.JTextField) FilenameFilter(java.io.FilenameFilter) UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) EditableResources(com.codename1.ui.util.EditableResources) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) AnimationObject(com.codename1.ui.animations.AnimationObject) File(java.io.File) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) FileWriter(java.io.FileWriter)

Example 7 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class PickMIDlet method startMIDlet.

public static void startMIDlet(Hashtable themeHash) {
    Accessor.setTheme(themeHash);
    Preferences pref = Preferences.userNodeForPackage(ResourceEditorView.class);
    String jar = pref.get("jar", null);
    String midlet = pref.get("midlet", null);
    if (jar != null && midlet != null) {
        File jarFile = new File(jar);
        if (jarFile.exists()) {
            try {
                URLClassLoader cl = URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() }, PickMIDlet.class.getClassLoader());
                StringTokenizer tokenizer = new StringTokenizer((String) midlet, " ,");
                String s = tokenizer.nextToken();
                while (tokenizer.hasMoreTokens()) {
                    s = tokenizer.nextToken();
                }
                Class cls = cl.loadClass(s);
                JavaSEPortWithSVGSupport.setClassLoader(cls);
                EditableResources.setResourcesClassLoader(cls);
                Accessor.setTheme(themeHash);
                Object app = cls.newInstance();
                JarFile zip = new JarFile(jarFile);
                Attributes m = zip.getManifest().getMainAttributes();
                cls.getDeclaredMethod("init", new Class[] { Object.class }).invoke(app, new Object[] { null });
                cls.getDeclaredMethod("start", new Class[0]).invoke(app, new Object[0]);
                // there might be an ongoing transition and the form.show() method is serial
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        if (Display.getInstance().getCurrent() != null) {
                            Display.getInstance().getCurrent().refreshTheme();
                            return;
                        } else {
                            new Thread() {

                                public void run() {
                                    try {
                                        sleep(100);
                                    } catch (InterruptedException ex) {
                                        ex.printStackTrace();
                                    }
                                    Display.getInstance().callSerially(this);
                                }
                            }.start();
                        }
                    }
                });
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    JavaSEPortWithSVGSupport.setClassLoader(PickMIDlet.class);
    LiveDemo l = new LiveDemo();
    l.init(null);
    l.start();
    Accessor.setTheme(themeHash);
    Form current = Display.getInstance().getCurrent();
    if (current != null) {
        current.refreshTheme();
    }
}
Also used : Form(com.codename1.ui.Form) Attributes(java.util.jar.Attributes) JarFile(java.util.jar.JarFile) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) URLClassLoader(java.net.URLClassLoader) Preferences(java.util.prefs.Preferences) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 8 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class PreviewInSimulator method main.

/**
 * Called back from simulateDeviceActionPerformed to show the simulator skin
 */
public static void main(String[] argv) {
    com.codename1.ui.Display.init(new Runnable() {

        public void run() {
            try {
                Preferences pref = Preferences.userNodeForPackage(PreviewInSimulator.class);
                String theme = pref.get("previewTheme", null);
                File resFile = new File(pref.get("previewResource", null));
                String baseResDir = pref.get("baseResourceDir", null);
                if (baseResDir != null) {
                    JavaSEPort.setBaseResourceDir(new File(baseResDir));
                }
                String selection = pref.get("previewSelection", null);
                Resources res = Resources.open(new FileInputStream(resFile));
                if (theme == null || theme.length() == 0) {
                    if (com.codename1.ui.Display.getInstance().hasNativeTheme()) {
                        com.codename1.ui.Display.getInstance().installNativeTheme();
                    }
                } else {
                    com.codename1.ui.plaf.UIManager.getInstance().setThemeProps(res.getTheme(theme));
                }
                com.codename1.ui.util.UIBuilder.registerCustomComponent("Table", com.codename1.ui.table.Table.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("MediaPlayer", com.codename1.components.MediaPlayer.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("ContainerList", com.codename1.ui.list.ContainerList.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("ComponentGroup", com.codename1.ui.ComponentGroup.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("Tree", com.codename1.ui.tree.Tree.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("HTMLComponent", com.codename1.ui.html.HTMLComponent.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("RSSReader", com.codename1.components.RSSReader.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("FileTree", com.codename1.components.FileTree.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("WebBrowser", com.codename1.components.WebBrowser.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("NumericSpinner", com.codename1.ui.spinner.NumericSpinner.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("DateSpinner", com.codename1.ui.spinner.DateSpinner.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("TimeSpinner", com.codename1.ui.spinner.TimeSpinner.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("DateTimeSpinner", com.codename1.ui.spinner.DateTimeSpinner.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("GenericSpinner", com.codename1.ui.spinner.GenericSpinner.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("LikeButton", com.codename1.facebook.ui.LikeButton.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("InfiniteProgress", com.codename1.components.InfiniteProgress.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("MultiButton", com.codename1.components.MultiButton.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("SpanButton", com.codename1.components.SpanButton.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("SpanLabel", com.codename1.components.SpanLabel.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("Ads", com.codename1.components.Ads.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("MapComponent", com.codename1.maps.MapComponent.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("MultiList", com.codename1.ui.list.MultiList.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("ShareButton", com.codename1.components.ShareButton.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("OnOffSwitch", com.codename1.components.OnOffSwitch.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("ImageViewer", com.codename1.components.ImageViewer.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("AutoCompleteTextField", com.codename1.ui.AutoCompleteTextField.class);
                com.codename1.ui.util.UIBuilder.registerCustomComponent("Picker", com.codename1.ui.spinner.Picker.class);
                com.codename1.ui.util.UIBuilder builder = new com.codename1.ui.util.UIBuilder();
                com.codename1.ui.Container c = builder.createContainer(res, selection);
                if (c instanceof com.codename1.ui.Form) {
                    ((com.codename1.ui.Form) c).refreshTheme();
                    if (c instanceof com.codename1.ui.Dialog) {
                        ((com.codename1.ui.Dialog) c).showModeless();
                    } else {
                        ((com.codename1.ui.Form) c).show();
                    }
                } else {
                    com.codename1.ui.Form f = new com.codename1.ui.Form();
                    f.setLayout(new com.codename1.ui.layouts.BorderLayout());
                    f.addComponent(com.codename1.ui.layouts.BorderLayout.CENTER, c);
                    f.refreshTheme();
                    f.show();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "Error While Running In Simulator: " + ex, "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
}
Also used : Preferences(java.util.prefs.Preferences) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) BackingStoreException(java.util.prefs.BackingStoreException) Resources(com.codename1.ui.util.Resources) File(java.io.File)

Example 9 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class ResourceEditorApp method migrateGuiBuilder.

private static void migrateGuiBuilder(File projectDir, EditableResources res, String destPackageName) throws IOException {
    File propertiesFile = new File(projectDir, "codenameone_settings.properties");
    Properties props = new Properties();
    FileInputStream pIn = new FileInputStream(propertiesFile);
    props.load(pIn);
    pIn.close();
    if (props.getProperty("guiResource") == null) {
        System.out.println("Not a legacy GUI builder project!\nConversion failed!");
        System.exit(1);
        return;
    }
    UserInterfaceEditor.exportToNewGuiBuilderMode = true;
    String mainForm = props.getProperty("mainForm");
    File stateMachineBase = new File(projectDir, "src" + File.separatorChar + "generated" + File.separator + "StateMachineBase.java");
    StringBuilder stateMachineBaseSource = new StringBuilder("/**\n * This class was generated by the migration wizard, ultimately both it and the Statemachine can be removed.\n");
    stateMachineBaseSource.append(" * This class is no longer updated automatically\n");
    stateMachineBaseSource.append("*/\n");
    stateMachineBaseSource.append("package generated;\n");
    stateMachineBaseSource.append("\nimport com.codename1.ui.*;\n");
    stateMachineBaseSource.append("import com.codename1.ui.util.*;\n");
    stateMachineBaseSource.append("import com.codename1.ui.plaf.*;\n");
    stateMachineBaseSource.append("import java.util.Hashtable;\n");
    stateMachineBaseSource.append("import com.codename1.ui.events.*;\n\n");
    stateMachineBaseSource.append("public abstract class StateMachineBase extends UIBuilder {\n");
    stateMachineBaseSource.append("    private static final java.util.HashMap<String, Class> formNameToClassHashMap = new java.util.HashMap<String, Class>();");
    stateMachineBaseSource.append("    public static StateMachineBase instance;");
    stateMachineBaseSource.append("    protected void initVars() {}\n\n");
    stateMachineBaseSource.append("    protected void initVars(Resources res) {}\n\n");
    stateMachineBaseSource.append("    public StateMachineBase(Resources res, String resPath, boolean loadTheme) {\n    instance = this;\n");
    stateMachineBaseSource.append("        startApp(res, resPath, loadTheme);\n");
    stateMachineBaseSource.append("    }\n\n\n");
    stateMachineBaseSource.append("    public Container startApp(Resources res, String resPath, boolean loadTheme) {\n");
    stateMachineBaseSource.append("        initVars();\n");
    stateMachineBaseSource.append("        if(loadTheme) {\n");
    stateMachineBaseSource.append("            if(res == null) {\n");
    stateMachineBaseSource.append("                try {\n");
    stateMachineBaseSource.append("                    if(resPath.endsWith(\".res\")) {\n");
    stateMachineBaseSource.append("                        res = Resources.open(resPath);\n");
    stateMachineBaseSource.append("                        System.out.println(\"Warning: you should construct the state machine without the .res extension to allow theme overlays\");\n");
    stateMachineBaseSource.append("                    } else {\n");
    stateMachineBaseSource.append("                        res = Resources.openLayered(resPath);\n");
    stateMachineBaseSource.append("                    }\n");
    stateMachineBaseSource.append("                } catch(java.io.IOException err) { err.printStackTrace(); }\n");
    stateMachineBaseSource.append("            }\n");
    stateMachineBaseSource.append("            initTheme(res);\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("        if(res != null) {\n");
    stateMachineBaseSource.append("            setResourceFilePath(resPath);\n");
    stateMachineBaseSource.append("            setResourceFile(res);\n");
    stateMachineBaseSource.append("            Resources.setGlobalResources(res);");
    stateMachineBaseSource.append("            initVars(res);\n");
    stateMachineBaseSource.append("            return showForm(getFirstFormName(), null);\n");
    stateMachineBaseSource.append("        } else {\n");
    stateMachineBaseSource.append("            Form f = (Form)createContainer(resPath, getFirstFormName());\n");
    stateMachineBaseSource.append("            Resources.setGlobalResources(fetchResourceFile());");
    stateMachineBaseSource.append("            initVars(fetchResourceFile());\n");
    stateMachineBaseSource.append("            beforeShow(f);\n");
    stateMachineBaseSource.append("            f.show();\n");
    stateMachineBaseSource.append("            postShow(f);\n");
    stateMachineBaseSource.append("            return f;\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("    }\n\n\n");
    stateMachineBaseSource.append("    protected String getFirstFormName() {\n");
    stateMachineBaseSource.append("        return \"");
    stateMachineBaseSource.append(mainForm);
    stateMachineBaseSource.append("\";\n");
    stateMachineBaseSource.append("    }\n\n\n");
    stateMachineBaseSource.append("    protected void initTheme(Resources res) {\n");
    stateMachineBaseSource.append("            String[] themes = res.getThemeResourceNames();\n");
    stateMachineBaseSource.append("            Resources.setGlobalResources(res);\n");
    stateMachineBaseSource.append("            if(themes != null && themes.length > 0) {\n");
    stateMachineBaseSource.append("                UIManager.getInstance().setThemeProps(res.getTheme(themes[0]));\n");
    stateMachineBaseSource.append("            }\n");
    stateMachineBaseSource.append("    }\n\n\n");
    stateMachineBaseSource.append("    public StateMachineBase() {\n    instance = this;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public StateMachineBase(String resPath) {\n");
    stateMachineBaseSource.append("        this(null, resPath, true);\n    instance = this;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public StateMachineBase(Resources res) {\n");
    stateMachineBaseSource.append("        this(res, null, true);\n    instance = this;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public StateMachineBase(String resPath, boolean loadTheme) {\n");
    stateMachineBaseSource.append("        this(null, resPath, loadTheme);\n    instance = this;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public StateMachineBase(Resources res, boolean loadTheme) {\n");
    stateMachineBaseSource.append("        this(res, null, loadTheme);\n    instance = this;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public Form showForm(String resourceName, Command sourceCommand) {\n");
    stateMachineBaseSource.append("        try {\n");
    stateMachineBaseSource.append("            Form f = (Form)formNameToClassHashMap.get(resourceName).newInstance();\n");
    stateMachineBaseSource.append("            Form current = Display.getInstance().getCurrent();\n");
    stateMachineBaseSource.append("            if(current != null && isBackCommandEnabled() && allowBackTo(resourceName)) {\n");
    stateMachineBaseSource.append("                f.putClientProperty(\"previousForm\", current);\n");
    stateMachineBaseSource.append("                setBackCommand(f, new Command(getBackCommandText(current.getTitle())) {\n");
    stateMachineBaseSource.append("                    public void actionPerformed(ActionEvent evt) {\n");
    stateMachineBaseSource.append("                          back(null);\n");
    stateMachineBaseSource.append("                    }\n");
    stateMachineBaseSource.append("                });\n");
    stateMachineBaseSource.append("            }\n");
    stateMachineBaseSource.append("            if(sourceCommand != null && current != null && current.getBackCommand() == sourceCommand) {\n");
    stateMachineBaseSource.append("                f.showBack();\n");
    stateMachineBaseSource.append("            } else {\n");
    stateMachineBaseSource.append("                f.show();\n");
    stateMachineBaseSource.append("            }\n");
    stateMachineBaseSource.append("            return f;\n");
    stateMachineBaseSource.append("        } catch(Exception err) {\n");
    stateMachineBaseSource.append("            err.printStackTrace();\n");
    stateMachineBaseSource.append("            throw new RuntimeException(\"Form not found: \" + resourceName);\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    protected void beforeShow(Form f) {\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public final void beforeShow__(Form f) {\n        beforeShow(f);\n");
    stateMachineBaseSource.append("        if(Display.getInstance().getCurrent() != null) {\n");
    stateMachineBaseSource.append("            exitForm(Display.getInstance().getCurrent());\n");
    stateMachineBaseSource.append("            invokeFormExit__(Display.getInstance().getCurrent());\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    protected void exitForm(Form f) {\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    protected void postShow(Form f) {\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public final void postShow__(Form f) {\n        postShow(f);\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    private Container getRootComponent__(Component rootComponent) {\n");
    stateMachineBaseSource.append("        if(rootComponent.getParent() != null) {\n");
    stateMachineBaseSource.append("            return getRoot__(rootComponent.getParent());\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("        return (Container)rootComponent;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    private Container getRoot__(Container rootComponent) {\n");
    stateMachineBaseSource.append("        Container p = rootComponent.getParent();\n");
    stateMachineBaseSource.append("        while(p != null) {\n");
    stateMachineBaseSource.append("            rootComponent = p;\n");
    stateMachineBaseSource.append("            p = rootComponent.getParent();\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("        return rootComponent;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public Component findByName(String componentName, Container rootComponent) {\n");
    stateMachineBaseSource.append("        Container root = getRoot__(rootComponent);\n");
    stateMachineBaseSource.append("        return findByName__(componentName, root);\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public Component findByName__(String componentName, Container root) {\n");
    stateMachineBaseSource.append("        int count = root.getComponentCount();\n");
    stateMachineBaseSource.append("        for(int iter = 0 ; iter < count ; iter++) {\n");
    stateMachineBaseSource.append("            Component c = root.getComponentAt(iter);\n");
    stateMachineBaseSource.append("            String n = c.getName();\n");
    stateMachineBaseSource.append("            if(n != null && n.equals(componentName)) {\n");
    stateMachineBaseSource.append("                return c;\n");
    stateMachineBaseSource.append("            }\n");
    stateMachineBaseSource.append("            if(c instanceof Container && ((Container)c).getLeadComponent() == null) {\n");
    stateMachineBaseSource.append("                c = findByName__(componentName, (Container)c);\n");
    stateMachineBaseSource.append("                if(c != null) {\n");
    stateMachineBaseSource.append("                    return c;\n");
    stateMachineBaseSource.append("                }\n");
    stateMachineBaseSource.append("            }\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("        return null;\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    protected void handleComponentAction(Component c, ActionEvent event) {\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public void handleComponentAction__(Component c, ActionEvent event) {\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public void processCommand__(ActionEvent ev, Command cmd) {\n");
    stateMachineBaseSource.append("        processCommand(ev, cmd);\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public void back() {\n");
    stateMachineBaseSource.append("        back(null);\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("    public void back(Component sourceComponent) {\n");
    stateMachineBaseSource.append("        Form current = (Form)Display.getInstance().getCurrent().getClientProperty(\"previousForm\");\n");
    stateMachineBaseSource.append("        current.showBack();\n");
    stateMachineBaseSource.append("    }\n\n");
    StringBuilder formNameMapBuilder = new StringBuilder("static {");
    StringBuilder invokeFormExitBuilder = new StringBuilder("    private void invokeFormExit__(Form f) {\n");
    UserInterfaceEditor.componentNames = new HashMap<String, Class>();
    UserInterfaceEditor.commandList = new ArrayList<ActionCommand>();
    for (String uiName : res.getUIResourceNames()) {
        System.out.println("Processing: " + uiName);
        String fileName = convertToVarName(uiName);
        formNameMapBuilder.append("    formNameToClassHashMap.put(\"");
        formNameMapBuilder.append(uiName);
        formNameMapBuilder.append("\", ");
        formNameMapBuilder.append(destPackageName);
        formNameMapBuilder.append(".");
        formNameMapBuilder.append(fileName);
        formNameMapBuilder.append(".class);\n");
        String normalizedUiName = ResourceEditorView.normalizeFormName(uiName);
        if (RESEVERVED_WORDS.contains(fileName)) {
            fileName += "X";
        } else {
            try {
                if (Class.forName("java.lang." + fileName) != null) {
                    fileName += "X";
                }
            } catch (Throwable t) {
            // passed...
            }
        }
        File guiFile = new File(projectDir, "res" + File.separatorChar + "guibuilder" + File.separatorChar + destPackageName.replace('.', File.separatorChar) + File.separatorChar + fileName + ".gui");
        guiFile.getParentFile().mkdirs();
        File sourcePackageDir = new File(projectDir, "src" + File.separatorChar + destPackageName.replace('.', File.separatorChar));
        sourcePackageDir.mkdirs();
        File sourceFile = new File(sourcePackageDir, fileName + ".java");
        UIBuilderOverride u = new UIBuilderOverride();
        com.codename1.ui.Container cnt = u.createContainer(res, uiName);
        FileOutputStream fos = new FileOutputStream(guiFile);
        Writer w = new OutputStreamWriter(fos, "UTF-8");
        w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
        StringBuilder bld = new StringBuilder();
        UserInterfaceEditor.actionEventNames = new ArrayList<String>();
        UserInterfaceEditor.listNames = new ArrayList<String>();
        UserInterfaceEditor.persistToXML(cnt, cnt, bld, res, "");
        w.write(bld.toString());
        w.flush();
        w.close();
        fos = new FileOutputStream(sourceFile);
        w = new OutputStreamWriter(fos, "UTF-8");
        w.write("package ");
        w.write(destPackageName);
        w.write(";\n");
        w.write("\n");
        w.write("/**\n");
        w.write(" * GUI builder created Form\n");
        w.write(" */\n");
        w.write("public class ");
        w.write(fileName);
        String prePostCode;
        w.write(" extends com.codename1.ui.");
        if (cnt instanceof com.codename1.ui.Form) {
            invokeFormExitBuilder.append("        if(f.getName().equals(\"");
            invokeFormExitBuilder.append(uiName);
            invokeFormExitBuilder.append("\")) {\n");
            invokeFormExitBuilder.append("            exit");
            invokeFormExitBuilder.append(normalizedUiName);
            invokeFormExitBuilder.append("(f);\n        }\n");
            stateMachineBaseSource.append("    protected void before");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("(Form f) {\n");
            stateMachineBaseSource.append("    }\n\n");
            stateMachineBaseSource.append("    public final void before");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("__(Form f) {\n        before");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("(f);\n    }\n\n");
            stateMachineBaseSource.append("    protected void post");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("(Form f) {\n");
            stateMachineBaseSource.append("    }\n\n");
            stateMachineBaseSource.append("    public final void post");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("__(Form f) {\n        post");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("(f);\n    }\n\n");
            stateMachineBaseSource.append("    protected void exit");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("(Form f) {\n");
            stateMachineBaseSource.append("    }\n\n");
        }
        if (cnt instanceof com.codename1.ui.Dialog) {
            w.write("Dialog");
            prePostCode = "\n    public void initComponent() {\n        generated.StateMachineBase.instance.beforeShow__(this);\n";
            prePostCode += "        generated.StateMachineBase.instance.before";
            prePostCode += normalizedUiName;
            prePostCode += "__(this);\n    }\n";
            prePostCode = "\n    public void onShow() {\n        generated.StateMachineBase.instance.postShow__(this);\n";
            prePostCode += "        generated.StateMachineBase.instance.post";
            prePostCode += normalizedUiName;
            prePostCode += "__(this);\n    }\n";
            prePostCode += "    protected void actionCommand(com.codename1.ui.Command cmd) {\n";
            prePostCode += "        generated.StateMachineBase.instance.processCommand__(new com.codename1.ui.events.ActionEvent(cmd), cmd);\n";
            prePostCode += "    }\n\n";
        } else {
            if (cnt instanceof com.codename1.ui.Form) {
                w.write("Form");
                prePostCode = "\n    public void show() {\n        generated.StateMachineBase.instance.beforeShow__(this);\n";
                prePostCode += "        generated.StateMachineBase.instance.before";
                prePostCode += normalizedUiName;
                prePostCode += "__(this);\n        super.show();\n        generated.StateMachineBase.instance.post";
                prePostCode += normalizedUiName;
                prePostCode += "__(this);\n    }\n";
                prePostCode += "    protected void actionCommand(com.codename1.ui.Command cmd) {\n";
                prePostCode += "        generated.StateMachineBase.instance.processCommand__(new com.codename1.ui.events.ActionEvent(cmd), cmd);\n";
                prePostCode += "    }\n\n";
            } else {
                w.write("Container");
                prePostCode = "";
            }
        }
        w.write(" {\n    public ");
        w.write(fileName);
        w.write("() {\n");
        w.write("        this(com.codename1.ui.util.Resources.getGlobalResources());\n");
        w.write("    }\n    \n    public ");
        w.write(fileName);
        w.write("(com.codename1.ui.util.Resources resourceObjectInstance) {\n");
        w.write("        initGuiBuilderComponents(resourceObjectInstance);\n");
        w.write("    }\n\n");
        w.write("//-- DON'T EDIT BELOW THIS LINE!!!\n\n    private void initGuiBuilderComponents(com.codename1.ui.util.Resources resourceObjectInstance) {}\n\n");
        w.write("//-- DON'T EDIT ABOVE THIS LINE!!!\n");
        for (String actionListenerNames : UserInterfaceEditor.actionEventNames) {
            w.write("\n    public void on");
            w.write(actionListenerNames);
            w.write("ActionEvent(com.codename1.ui.events.ActionEvent ev) {\n        ");
            w.write("generated.StateMachineBase.instance.handleComponentAction__((com.codename1.ui.Component)ev.getSource(), ev);\n        ");
            w.write("generated.StateMachineBase.instance.on");
            w.write(normalizedUiName);
            w.write("_");
            String normalizedActionListenerName = ResourceEditorView.normalizeFormName(actionListenerNames);
            w.write(normalizedActionListenerName);
            w.write("Action__((com.codename1.ui.Component)ev.getSource(), ev);\n    }\n\n");
            stateMachineBaseSource.append("    protected void on");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("_");
            stateMachineBaseSource.append(normalizedActionListenerName);
            stateMachineBaseSource.append("Action(Component cmp, ActionEvent ev) {\n    }\n\n");
            stateMachineBaseSource.append("    public void on");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("_");
            stateMachineBaseSource.append(normalizedActionListenerName);
            stateMachineBaseSource.append("Action__(Component cmp, ActionEvent ev) {\n        on");
            stateMachineBaseSource.append(normalizedUiName);
            stateMachineBaseSource.append("_");
            stateMachineBaseSource.append(normalizedActionListenerName);
            stateMachineBaseSource.append("Action(cmp, ev);\n    }\n\n");
        }
        w.write(prePostCode);
        w.write("}\n");
        w.flush();
        w.close();
    }
    formNameMapBuilder.append("}\n");
    invokeFormExitBuilder.append("}\n");
    stateMachineBaseSource.append(formNameMapBuilder);
    stateMachineBaseSource.append(invokeFormExitBuilder);
    ArrayList<String> uniqueNames = new ArrayList<String>();
    for (String cmpName : UserInterfaceEditor.componentNames.keySet()) {
        String nomName = ResourceEditorView.normalizeFormName(cmpName);
        if (uniqueNames.contains(nomName)) {
            continue;
        }
        uniqueNames.add(nomName);
        stateMachineBaseSource.append("    public ");
        stateMachineBaseSource.append(UserInterfaceEditor.componentNames.get(cmpName).getName());
        stateMachineBaseSource.append(" find");
        stateMachineBaseSource.append(nomName);
        stateMachineBaseSource.append("(Component root) {\n        return (");
        stateMachineBaseSource.append(UserInterfaceEditor.componentNames.get(cmpName).getName());
        stateMachineBaseSource.append(")findByName(\"");
        stateMachineBaseSource.append(cmpName);
        stateMachineBaseSource.append("\", getRootComponent__(root));\n    }\n\n");
        stateMachineBaseSource.append("    public ");
        stateMachineBaseSource.append(UserInterfaceEditor.componentNames.get(cmpName).getName());
        stateMachineBaseSource.append(" find");
        stateMachineBaseSource.append(nomName);
        stateMachineBaseSource.append("() {\n        return (");
        stateMachineBaseSource.append(UserInterfaceEditor.componentNames.get(cmpName).getName());
        stateMachineBaseSource.append(")findByName(\"");
        stateMachineBaseSource.append(cmpName);
        stateMachineBaseSource.append("\", Display.getInstance().getCurrent());\n    }\n\n");
    }
    ArrayList<Integer> commandIdsAdded = new ArrayList<Integer>();
    ArrayList<String> commandNamesAdded = new ArrayList<String>();
    for (ActionCommand cmd : UserInterfaceEditor.commandList) {
        String formName = (String) cmd.getClientProperty("FORMNAME");
        if (formName == null) {
            continue;
        }
        String normalizedCommandName = ResourceEditorView.normalizeFormName(formName) + ResourceEditorView.normalizeFormName(cmd.getCommandName());
        if (commandNamesAdded.contains(normalizedCommandName)) {
            continue;
        }
        if (commandIdsAdded.contains(cmd.getId())) {
            continue;
        }
        commandIdsAdded.add(cmd.getId());
        commandNamesAdded.add(normalizedCommandName);
        stateMachineBaseSource.append("    public static final int COMMAND_");
        stateMachineBaseSource.append(normalizedCommandName);
        stateMachineBaseSource.append(" = ");
        stateMachineBaseSource.append(cmd.getId());
        stateMachineBaseSource.append(";\n\n    protected boolean on");
        stateMachineBaseSource.append(normalizedCommandName);
        stateMachineBaseSource.append("() {\n        return false;\n    }\n\n");
    }
    stateMachineBaseSource.append("    protected void processCommand(ActionEvent ev, Command cmd) {\n");
    stateMachineBaseSource.append("        switch(cmd.getId()) {\n");
    commandIdsAdded.clear();
    commandNamesAdded.clear();
    for (ActionCommand cmd : UserInterfaceEditor.commandList) {
        String formName = (String) cmd.getClientProperty("FORMNAME");
        if (formName == null) {
            continue;
        }
        String normalizedCommandName = ResourceEditorView.normalizeFormName(formName) + ResourceEditorView.normalizeFormName(cmd.getCommandName());
        if (commandNamesAdded.contains(normalizedCommandName)) {
            continue;
        }
        if (commandIdsAdded.contains(cmd.getId())) {
            continue;
        }
        commandIdsAdded.add(cmd.getId());
        commandNamesAdded.add(normalizedCommandName);
        stateMachineBaseSource.append("\n        case COMMAND_");
        stateMachineBaseSource.append(normalizedCommandName);
        stateMachineBaseSource.append(":\n");
        if (cmd.getAction() != null && cmd.getAction().length() > 0) {
            if (!cmd.getAction().startsWith("$")) {
                stateMachineBaseSource.append("            showForm(\"");
                stateMachineBaseSource.append(cmd.getAction());
                stateMachineBaseSource.append("\", null);\n");
            }
        }
        stateMachineBaseSource.append("            if(on");
        stateMachineBaseSource.append(normalizedCommandName);
        stateMachineBaseSource.append("()) {\n");
        stateMachineBaseSource.append("                ev.consume();\n");
        stateMachineBaseSource.append("                return;\n");
        stateMachineBaseSource.append("            }\n");
        stateMachineBaseSource.append("            break;\n\n");
    }
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("        if(ev.getComponent() != null) {\n");
    stateMachineBaseSource.append("            handleComponentAction(ev.getComponent(), ev);\n");
    stateMachineBaseSource.append("        }\n");
    stateMachineBaseSource.append("    }\n\n");
    stateMachineBaseSource.append("\n}\n");
    FileOutputStream sbout = new FileOutputStream(stateMachineBase);
    sbout.write(stateMachineBaseSource.toString().getBytes("UTF-8"));
    sbout.close();
    props.remove("mainForm");
    props.remove("package");
    props.remove("guiResource");
    props.remove("baseClass");
    props.remove("userClass");
    FileOutputStream pOut = new FileOutputStream(propertiesFile);
    props.store(pOut, "Updated by GUI builder migration wizard");
    pOut.close();
    System.out.println("Conversion completed successfully!");
    System.exit(0);
}
Also used : UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) ArrayList(java.util.ArrayList) Properties(java.util.Properties) Container(com.codename1.ui.Container) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 10 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class ResourceEditorApp method generateResourceFile.

private static void generateResourceFile(File f, String themeName, String ui) throws Exception {
    System.out.println("Generating resource file " + f + " theme " + themeName + " template " + ui);
    EditableResources res = new EditableResources();
    // "native", "leather", "tzone", "tipster", "blank"
    String template = "Native_Theme";
    if (themeName.equalsIgnoreCase("leather")) {
        template = "Leather";
    }
    if (themeName.equalsIgnoreCase("chrome")) {
        template = "Chrome";
    }
    if (themeName.equalsIgnoreCase("tzone")) {
        template = "tzone_theme";
    }
    if (themeName.equalsIgnoreCase("tipster")) {
        template = "tipster_theme";
    }
    if (themeName.equalsIgnoreCase("socialboo")) {
        template = "socialboo";
    }
    if (themeName.equalsIgnoreCase("mapper")) {
        template = "mapper";
    }
    if (themeName.equalsIgnoreCase("flatblue")) {
        template = "FlatBlueTheme";
    }
    if (themeName.equalsIgnoreCase("flatred")) {
        template = "FlatRedTheme";
    }
    if (themeName.equalsIgnoreCase("flatorange")) {
        template = "FlatOrangeTheme";
    }
    if (themeName.equalsIgnoreCase("business")) {
        template = "BusinessTheme";
    }
    res.setTheme("Theme", importRes(res, template));
    if ("HiWorld".equalsIgnoreCase(ui)) {
        importRes(res, "HiWorldTemplate");
        generate(res, f);
    } else {
        if ("Tabs".equalsIgnoreCase(ui)) {
            importRes(res, "Tabs");
            generate(res, f);
        } else {
            if ("List".equalsIgnoreCase(ui)) {
                importRes(res, "ListOfItems");
                generate(res, f);
            } else {
                if ("NewHi".equalsIgnoreCase(ui)) {
                    importImage("android-icon.png", res);
                    importImage("apple-icon.png", res);
                    importImage("windows-icon.png", res);
                    importImage("duke-no-logos.png", res);
                    Map m = res.getTheme("Theme");
                    m.put("GetStarted.fgColor", "ffffff");
                    m.put("GetStarted.sel#fgColor", "ffffff");
                    m.put("GetStarted.press#fgColor", "ffffff");
                    m.put("GetStarted.bgColor", "339900");
                    m.put("GetStarted.sel#bgColor", "339900");
                    m.put("GetStarted.press#bgColor", "339900");
                    m.put("GetStarted.transparency", "255");
                    m.put("GetStarted.sel#transparency", "255");
                    m.put("GetStarted.press#transparency", "255");
                    Integer centerAlign = new Integer(4);
                    m.put("GetStarted.align", centerAlign);
                    m.put("GetStarted.sel#align", centerAlign);
                    m.put("GetStarted.press#align", centerAlign);
                    m.put("GetStarted.padding", "1,1,1,1");
                    m.put("GetStarted.padUnit", new byte[] { Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS });
                    m.put("GetStarted.sel#padding", "1,1,1,1");
                    m.put("GetStarted.sel#padUnit", new byte[] { Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS });
                    m.put("GetStarted.press#padding", "1,1,1,1");
                    m.put("GetStarted.press#padUnit", new byte[] { Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS });
                    m.put("GetStarted.font", new EditorTTFFont("native:MainLight", 3, 2.5f, Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM)));
                }
            }
        }
    }
    FileOutputStream os = new FileOutputStream(f);
    res.save(os);
    os.close();
}
Also used : EditorTTFFont(com.codename1.ui.EditorTTFFont) FileOutputStream(java.io.FileOutputStream) EditableResources(com.codename1.ui.util.EditableResources) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

IOException (java.io.IOException)76 File (java.io.File)61 FileInputStream (java.io.FileInputStream)43 InputStream (java.io.InputStream)33 EncodedImage (com.codename1.ui.EncodedImage)23 FileOutputStream (java.io.FileOutputStream)23 OutputStream (java.io.OutputStream)22 SortedProperties (com.codename1.ant.SortedProperties)18 FileSystemStorage (com.codename1.io.FileSystemStorage)17 BufferedInputStream (com.codename1.io.BufferedInputStream)15 Image (com.codename1.ui.Image)15 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ActionEvent (com.codename1.ui.events.ActionEvent)14 RandomAccessFile (java.io.RandomAccessFile)14 ArrayList (java.util.ArrayList)14 EditableResources (com.codename1.ui.util.EditableResources)13 InvocationTargetException (java.lang.reflect.InvocationTargetException)13 Properties (java.util.Properties)12 File (com.codename1.io.File)11 BufferedImage (java.awt.image.BufferedImage)11