Search in sources :

Example 6 with Ui

use of com.codename1.ui.util.xml.Ui 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 7 with Ui

use of com.codename1.ui.util.xml.Ui 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)

Example 8 with Ui

use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.

the class AddUIResource method addResource.

// GEN-LAST:event_templateActionPerformed
public String addResource(EditableResources res, ResourceEditorView view) {
    String newName = name.getText();
    for (String r : res.getResourceNames()) {
        if (r.equalsIgnoreCase(newName)) {
            JOptionPane.showMessageDialog(this, "A resource called: " + newName + " already exists\nYou must delete the resource first.", "Add Resource", JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }
    Object ui = null;
    InputStream is = getClass().getResourceAsStream("/templates/" + template.getSelectedItem().toString() + ".res");
    if (is != null) {
        try {
            EditableResources r = new EditableResources();
            r.openFile(is);
            is.close();
            ui = r.getResourceObject("Main");
            r.remove("Main");
            view.checkDuplicateResourcesLoop(r, res.getImageResourceNames(), r.getImageResourceNames(), "Rename Image", "Image ", true);
            view.checkDuplicateResourcesLoop(r, res.getL10NResourceNames(), r.getL10NResourceNames(), "Rename Localization", "Localization ", true);
            view.checkDuplicateResourcesLoop(r, res.getDataResourceNames(), r.getDataResourceNames(), "Rename Data", "Data ", true);
            view.checkDuplicateResourcesLoop(r, res.getUIResourceNames(), r.getUIResourceNames(), "Rename GUI", "GUI ", true);
            view.checkDuplicateResourcesLoop(r, res.getFontResourceNames(), r.getFontResourceNames(), "Rename Font", "Font ", true);
            for (String s : r.getImageResourceNames()) {
                res.setImage(s, r.getImage(s));
            }
            for (String s : r.getL10NResourceNames()) {
                res.setL10N(s, (Hashtable) r.getResourceObject(s));
            }
            for (String s : r.getDataResourceNames()) {
                res.setData(s, (byte[]) r.getResourceObject(s));
            }
            for (String s : r.getUIResourceNames()) {
                res.setUi(s, (byte[]) r.getResourceObject(s));
            }
            for (String s : r.getFontResourceNames()) {
                res.setFont(s, r.getFont(s));
            }
        } catch (IOException err) {
            err.printStackTrace();
        }
    }
    res.setUi(name.getText(), (byte[]) ui);
    view.setSelectedResource(name.getText());
    return name.getText();
}
Also used : InputStream(java.io.InputStream) IOException(java.io.IOException) EditableResources(com.codename1.ui.util.EditableResources)

Example 9 with Ui

use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.

the class ResetableTextWatcher method edit.

/**
 * Entry point for using this class
 * @param impl The current running activity
 * @param component Any subclass of com.codename1.ui.TextArea
 * @param inputType One of the TextArea's input-type constants
 */
public static void edit(final AndroidImplementation impl, final Component component, final int inputType) {
    if (impl.getActivity() == null) {
        throw new IllegalArgumentException("activity is null");
    }
    if (component == null) {
        throw new IllegalArgumentException("component is null");
    }
    if (!(component instanceof TextArea)) {
        throw new IllegalArgumentException("component must be instance of TextArea");
    }
    final TextArea textArea = (TextArea) component;
    final String initialText = textArea.getText();
    textArea.putClientProperty("InPlaceEditView.initialText", initialText);
    // The very first time we try to edit a string, let's determine if the
    // system default is to do async editing.  If the system default
    // is not yet set, we set it here, and it will be used as the default from now on
    // We do this because the nativeInstance.isAsyncEditMode() value changes
    // to reflect the currently edited field so it isn't a good way to keep a
    // system default.
    String defaultAsyncEditingSetting = Display.getInstance().getProperty("android.VKBAlwaysOpen", null);
    if (defaultAsyncEditingSetting == null) {
        defaultAsyncEditingSetting = impl.isAsyncEditMode() ? "true" : "false";
        Display.getInstance().setProperty("android.VKBAlwaysOpen", defaultAsyncEditingSetting);
    }
    boolean asyncEdit = "true".equals(defaultAsyncEditingSetting) ? true : false;
    // Check if the form has any setting for asyncEditing that should override
    // the application defaults.
    final Form parentForm = component.getComponentForm();
    if (parentForm == null) {
        com.codename1.io.Log.p("Attempt to edit text area that is not on a form.  This is not supported");
        return;
    }
    if (parentForm.getClientProperty("asyncEditing") != null) {
        Object async = parentForm.getClientProperty("asyncEditing");
        if (async instanceof Boolean) {
            asyncEdit = ((Boolean) async).booleanValue();
        // Log.p("Form overriding asyncEdit due to asyncEditing client property: "+asyncEdit);
        }
    }
    if (parentForm.getClientProperty("android.asyncEditing") != null) {
        Object async = parentForm.getClientProperty("android.asyncEditing");
        if (async instanceof Boolean) {
            asyncEdit = ((Boolean) async).booleanValue();
        // Log.p("Form overriding asyncEdit due to ios.asyncEditing client property: "+asyncEdit);
        }
    }
    if (parentForm.isFormBottomPaddingEditingMode()) {
        asyncEdit = true;
    }
    // then this will override all other settings.
    if (component.getClientProperty("asyncEditing") != null) {
        Object async = component.getClientProperty("asyncEditing");
        if (async instanceof Boolean) {
            asyncEdit = ((Boolean) async).booleanValue();
        // Log.p("Overriding asyncEdit due to field asyncEditing client property: "+asyncEdit);
        }
    }
    if (component.getClientProperty("android.asyncEditing") != null) {
        Object async = component.getClientProperty("android.asyncEditing");
        if (async instanceof Boolean) {
            asyncEdit = ((Boolean) async).booleanValue();
        // Log.p("Overriding asyncEdit due to field ios.asyncEditing client property: "+asyncEdit);
        }
    }
    // if true, then in async mode we are currently editing and are switching to another field
    final boolean isEditedFieldSwitch;
    // If we are already editing, we need to finish that up before we proceed to edit the next field.
    synchronized (editingLock) {
        if (mIsEditing) {
            if (impl.isAsyncEditMode()) {
                // Using isEditedFieldSwitch was causing issues with cursors not showing up.
                // https://github.com/codenameone/CodenameOne/issues/2353
                // https://stackoverflow.com/questions/49004370/focus-behaviour-in-textarea-in-cn1
                // Disabling this feature by default now, but can be re-enabled by setting
                // Display.getInstance().setProperty("android.reuseTextEditorOnSwitch", "true");
                // This editedFieldSwitch feature was added a while back to improve experience on older
                // Android devices where the field switching was going too slow.
                // https://github.com/codenameone/CodenameOne/issues/2012
                // This issue was resolved in this commit (https://github.com/jaanushansen/CodenameOne/commit/f3e53a80704149e4d7cde276d01c1368bcdcfe2c)
                // which was submitted as part of a pull request.  This fix has been the source of several
                // regressions, mostly related to properties not being propagated properly when a text field is changed
                // However, this issue (with the cursor not showing up), doesn't appear to have a simple solution
                // so, I'm disabling this feature for now.
                isEditedFieldSwitch = "true".equals(Display.getInstance().getProperty("android.reuseTextEditorOnSwitch", "false"));
                final String[] out = new String[1];
                TextArea prevTextArea = null;
                if (sInstance != null && sInstance.mLastEditText != null) {
                    prevTextArea = sInstance.mLastEditText.getTextArea();
                }
                if (prevTextArea != null) {
                    final TextArea fPrevTextArea = prevTextArea;
                    final String retVal = sInstance.mLastEditText.getText().toString();
                    Display.getInstance().callSerially(new Runnable() {

                        public void run() {
                            Display.getInstance().onEditingComplete(fPrevTextArea, retVal);
                        }
                    });
                }
                InPlaceEditView.setEditedTextField(textArea);
                nextTextArea = null;
            } else {
                isEditedFieldSwitch = false;
                final InPlaceEditView instance = sInstance;
                if (instance != null && instance.mEditText != null && instance.mEditText.mTextArea == textArea) {
                    instance.showTextEditorAgain();
                    return;
                }
                if (!isClosing && sInstance != null && sInstance.mEditText != null) {
                    isClosing = true;
                    impl.getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            instance.endEditing(REASON_UNDEFINED, true, 0);
                        }
                    });
                }
                afterClose = new Runnable() {

                    @Override
                    public void run() {
                        impl.callHideTextEditor();
                        Display.getInstance().editString(component, textArea.getMaxSize(), inputType, textArea.getText());
                    }
                };
                return;
            }
        } else {
            isEditedFieldSwitch = false;
        }
        mIsEditing = true;
        isClosing = false;
        afterClose = null;
    }
    impl.setAsyncEditMode(asyncEdit);
    // textArea.setPreferredSize(prefSize);
    if (!impl.isAsyncEditMode() && textArea instanceof TextField) {
        ((TextField) textArea).setEditable(false);
    }
    final boolean scrollableParent = isScrollableParent(textArea);
    // We wrap the text area so that we can safely pass data across to the
    // android UI thread.
    final TextAreaData textAreaData = new TextAreaData(textArea);
    impl.getActivity().runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (!isEditedFieldSwitch) {
                releaseEdit();
                if (sInstance == null) {
                    sInstance = new InPlaceEditView(impl);
                    impl.relativeLayout.addView(sInstance);
                }
            // Let's try something new here
            // We'll ALWAYS try resize edit mode (since it just works better)
            // But we'll detect whether the field is still covered by the keyboard
            // and switch to pan mode if necessary.
            }
            if (scrollableParent || parentForm.isFormBottomPaddingEditingMode()) {
                setEditMode(true);
            } else {
                trySetEditMode(true);
            }
            sInstance.startEditing(impl.getActivity(), textAreaData, initialText, inputType, isEditedFieldSwitch);
        }
    });
    final String[] out = new String[1];
    // In order to reuse the code the runs after edit completion, we will wrap it in a runnable
    // For sync edit mode, we will just run onComplete.run() at the end of this method.  For
    // Async mode we add the Runnable to the textarea as a client property, then run it
    // when editing eventually completes.
    Runnable onComplete = new Runnable() {

        public void run() {
            if (!impl.isAsyncEditMode() && textArea instanceof TextField) {
                ((TextField) textArea).setEditable(true);
            }
            textArea.setPreferredSize(null);
            if (sInstance != null && sInstance.mLastEditText != null && sInstance.mLastEditText.mTextArea == textArea) {
                String retVal = sInstance.mLastEditText.getText().toString();
                if (!impl.isAsyncEditMode()) {
                    sInstance.mLastEditText = null;
                    impl.getActivity().runOnUiThread(new Runnable() {

                        public void run() {
                            releaseEdit();
                        }
                    });
                }
                out[0] = retVal;
            } else {
                out[0] = initialText;
            }
            Display.getInstance().onEditingComplete(component, out[0]);
            if (impl.isAsyncEditMode()) {
                impl.callHideTextEditor();
            } else {
                // lock.
                if (sInstance != null) {
                    Display.getInstance().invokeAndBlock(new Runnable() {

                        public void run() {
                            while (sInstance != null) {
                                com.codename1.io.Util.sleep(5);
                            }
                        }
                    });
                }
            }
            // Release the editing flag
            synchronized (editingLock) {
                mIsEditing = false;
            }
            // as a runnable ... this should take priority over the "nextTextArea" setting
            if (afterClose != null) {
                Display.getInstance().callSerially(afterClose);
            } else if (nextTextArea != null) {
                final TextArea next = nextTextArea;
                nextTextArea = null;
                next.requestFocus();
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Display.getInstance().editString(next, next.getMaxSize(), next.getConstraint(), next.getText());
                    }
                });
            }
        }
    };
    textArea.requestFocus();
    textArea.repaint();
    if (impl.isAsyncEditMode()) {
        component.putClientProperty("android.onAsyncEditingComplete", onComplete);
        return;
    }
    // Make this call synchronous
    // We set this flag so that waitForEditCompletion can block on it.
    // The flag will be released inside the endEditing method which will
    // allow the method to proceed.
    waitingForSynchronousEditingCompletion = true;
    waitForEditCompletion();
    onComplete.run();
}
Also used : TextArea(com.codename1.ui.TextArea) Form(com.codename1.ui.Form) TextField(com.codename1.ui.TextField)

Example 10 with Ui

use of com.codename1.ui.util.xml.Ui in project CodenameOne by codenameone.

the class ResetableTextWatcher method hideTextEditor.

/**
 * Hides the native text editor while keeping the active async edit session going.
 * This will effectively hide the native text editor, and show the light-weight text area
 * with cursor still in the correct position.
 */
private void hideTextEditor() {
    if (!mIsEditing || textEditorHidden || mEditText == null) {
        return;
    }
    textEditorHidden = true;
    final TextArea ta = mEditText.mTextArea;
    // Since this may be called off the UI thread, we need to issue async request on UI thread
    // to hide the text area.
    impl.getActivity().runOnUiThread(new Runnable() {

        public void run() {
            if (mEditText != null && mEditText.mTextArea == ta) {
                // Note:  Setting visibility to GONE doesn't work here because the TextWatcher
                // will stop receiving input from the keyboard, so we don't have a way to
                // reactivate the text editor when the user starts typing again.  Using the margin
                // to move it off screen keeps the text editor active.
                mEditLayoutParams.setMargins(-Display.getInstance().getDisplayWidth(), 0, 0, 0);
                InPlaceEditView.this.requestLayout();
                final int cursorPos = mEditText.getSelectionStart();
                // Since we are going to be displaying the CN1 text area now, we need to update
                // the cursor.  That needs to happen on the EDT.
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        if (mEditText != null && mEditText.mTextArea == ta && mIsEditing && textEditorHidden) {
                            if (ta instanceof TextField) {
                                ((TextField) ta).setCursorPosition(cursorPos);
                            }
                        }
                    }
                });
            }
        }
    });
    // Repaint the CN1 text area on the EDT.  This is necessary because while the native editor
    // was shown, the cn1 text area paints only its background.  Now that the editor is hidden
    // it should paint its foreground also.
    Display.getInstance().callSerially(new Runnable() {

        public void run() {
            if (mEditText != null && mEditText.mTextArea != null) {
                mEditText.mTextArea.repaint();
            }
        }
    });
// repaintTextEditor(true);
}
Also used : TextArea(com.codename1.ui.TextArea) TextField(com.codename1.ui.TextField)

Aggregations

Component (com.codename1.ui.Component)8 ArrayList (java.util.ArrayList)7 Container (com.codename1.ui.Container)6 Label (com.codename1.ui.Label)6 TextArea (com.codename1.ui.TextArea)6 Vector (java.util.Vector)6 IOException (java.io.IOException)5 Hashtable (java.util.Hashtable)5 EncodedImage (com.codename1.ui.EncodedImage)4 Border (com.codename1.ui.plaf.Border)4 UIBuilderOverride (com.codename1.ui.util.UIBuilderOverride)4 EditorTTFFont (com.codename1.ui.EditorTTFFont)3 Form (com.codename1.ui.Form)3 TextField (com.codename1.ui.TextField)3 AnimationObject (com.codename1.ui.animations.AnimationObject)3 EditableResources (com.codename1.ui.util.EditableResources)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3 InputStream (java.io.InputStream)3