Search in sources :

Example 26 with Location

use of com.codename1.location.Location in project CodenameOne by codenameone.

the class CloudObject method bindProperty.

/**
 * Binds a property value within the given component to this cloud object, this means that
 * when the component changes the cloud object changes unless deferred. If the defer flag is
 * false all changes are stored in a temporary location and only "committed" once commitBindings()
 * is invoked.
 * @param cmp the component to bind
 * @param propertyName the name of the property in the bound component
 * @param attributeName the key within the cloud object
 * @param defer bind settings whether to defer the binding which requires developers to explicitly commit
 * the binding to perform the changes
 * @param objectLead if set to true the UI property is initialized from values in the CloudObject, if false
 * the cloud object property is initialized from the UI
 */
public void bindProperty(Component cmp, final String propertyName, final String attributeName, final int defer, boolean objectLead) {
    if (objectLead) {
        Object val = values.get(attributeName);
        Object cmpVal = cmp.getBoundPropertyValue(propertyName);
        if (val == null) {
            if (cmpVal != null) {
                cmp.setBoundPropertyValue(propertyName, null);
            }
        } else {
            if (cmpVal == null || !(val.equals(cmpVal))) {
                cmp.setBoundPropertyValue(propertyName, val);
            }
        }
    } else {
        Object val = values.get(attributeName);
        Object cmpVal = cmp.getBoundPropertyValue(propertyName);
        if (cmpVal == null) {
            if (val != null) {
                values.remove(attributeName);
                status = STATUS_MODIFIED;
            }
        } else {
            if (val == null || !(val.equals(cmpVal))) {
                values.put(attributeName, cmpVal);
                status = STATUS_MODIFIED;
            }
        }
    }
    BindTarget target = new BindTarget() {

        public void propertyChanged(Component source, String propertyName, Object oldValue, Object newValue) {
            switch(defer) {
                case BINDING_DEFERRED:
                    if (deferedValues == null) {
                        deferedValues = new Hashtable();
                    }
                    deferedValues.put(attributeName, newValue);
                    break;
                case BINDING_IMMEDIATE:
                    values.put(attributeName, newValue);
                    status = STATUS_MODIFIED;
                    break;
                case BINDING_AUTO_SAVE:
                    values.put(attributeName, newValue);
                    status = STATUS_MODIFIED;
                    CloudStorage.getInstance().save(CloudObject.this);
                    break;
            }
        }
    };
    cmp.bindProperty(propertyName, target);
    cmp.putClientProperty("CN1Bind" + propertyName, target);
}
Also used : Hashtable(java.util.Hashtable) BindTarget(com.codename1.cloud.BindTarget) Component(com.codename1.ui.Component)

Example 27 with Location

use of com.codename1.location.Location in project CodenameOne by codenameone.

the class JavaSEPort method installMenu.

private void installMenu(final JFrame frm, boolean desktopSkin) throws IOException {
    JMenuBar bar = new JMenuBar();
    frm.setJMenuBar(bar);
    JMenu simulatorMenu = new JMenu("Simulate");
    simulatorMenu.setDoubleBuffered(true);
    simulatorMenu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            menuDisplayed = true;
        }

        @Override
        public void menuCanceled(MenuEvent e) {
            menuDisplayed = false;
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuDisplayed = false;
        }
    });
    JMenuItem rotate = new JMenuItem("Rotate");
    rotate.setEnabled(!desktopSkin);
    simulatorMenu.add(rotate);
    final JCheckBoxMenuItem zoomMenu = new JCheckBoxMenuItem("Zoom", scrollableSkin);
    simulatorMenu.add(zoomMenu);
    JMenu debugEdtMenu = new JMenu("Debug EDT");
    simulatorMenu.add(debugEdtMenu);
    zoomMenu.setEnabled(!desktopSkin);
    JRadioButtonMenuItem debugEdtNone = new JRadioButtonMenuItem("None");
    JRadioButtonMenuItem debugEdtLight = new JRadioButtonMenuItem("Light");
    JRadioButtonMenuItem debugEdtFull = new JRadioButtonMenuItem("Full");
    debugEdtMenu.add(debugEdtNone);
    debugEdtMenu.add(debugEdtLight);
    debugEdtMenu.add(debugEdtFull);
    ButtonGroup bg = new ButtonGroup();
    bg.add(debugEdtNone);
    bg.add(debugEdtLight);
    bg.add(debugEdtFull);
    final Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
    int debugEdtSelection = pref.getInt("debugEDTMode", 0);
    switch(debugEdtSelection) {
        case 0:
            debugEdtNone.setSelected(true);
            setShowEDTWarnings(false);
            setShowEDTViolationStacks(false);
            break;
        case 2:
            debugEdtFull.setSelected(true);
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(true);
            break;
        default:
            debugEdtLight.setSelected(true);
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(false);
            break;
    }
    debugEdtNone.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            setShowEDTWarnings(false);
            setShowEDTViolationStacks(false);
            pref.putInt("debugEDTMode", 0);
        }
    });
    debugEdtFull.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(true);
            pref.putInt("debugEDTMode", 2);
        }
    });
    debugEdtLight.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            setShowEDTWarnings(true);
            setShowEDTViolationStacks(false);
            pref.putInt("debugEDTMode", 1);
        }
    });
    JMenuItem screenshot = new JMenuItem("Screenshot");
    simulatorMenu.add(screenshot);
    KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
    screenshot.setAccelerator(f2);
    screenshot.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            final float zoom = zoomLevel;
            zoomLevel = 1;
            final Form frm = Display.getInstance().getCurrent();
            BufferedImage headerImageTmp;
            if (isPortrait()) {
                headerImageTmp = header;
            } else {
                headerImageTmp = headerLandscape;
            }
            if (!includeHeaderInScreenshot) {
                headerImageTmp = null;
            }
            int headerHeightTmp = 0;
            if (headerImageTmp != null) {
                headerHeightTmp = headerImageTmp.getHeight();
            }
            final int headerHeight = headerHeightTmp;
            final BufferedImage headerImage = headerImageTmp;
            // gr.translate(0, statusBarHeight);
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    final com.codename1.ui.Image img = com.codename1.ui.Image.createImage(frm.getWidth(), frm.getHeight());
                    com.codename1.ui.Graphics gr = img.getGraphics();
                    takingScreenshot = true;
                    screenshotActualZoomLevel = zoom;
                    try {
                        frm.paint(gr);
                    } finally {
                        takingScreenshot = false;
                    }
                    final int imageWidth = img.getWidth();
                    final int imageHeight = img.getHeight();
                    final int[] imageRGB = img.getRGB();
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            BufferedImage bi = new BufferedImage(frm.getWidth(), frm.getHeight() + headerHeight, BufferedImage.TYPE_INT_ARGB);
                            bi.setRGB(0, headerHeight, imageWidth, imageHeight, imageRGB, 0, imageWidth);
                            if (headerImage != null) {
                                Graphics2D g2d = bi.createGraphics();
                                g2d.drawImage(headerImage, 0, 0, null);
                                g2d.dispose();
                            }
                            OutputStream out = null;
                            try {
                                out = new FileOutputStream(findScreenshotFile());
                                ImageIO.write(bi, "png", out);
                                out.close();
                            } catch (Throwable ex) {
                                ex.printStackTrace();
                                System.exit(1);
                            } finally {
                                zoomLevel = zoom;
                                try {
                                    out.close();
                                } catch (Throwable ex) {
                                }
                                frm.repaint();
                                canvas.repaint();
                            }
                        }
                    });
                }
            });
        }
    });
    JMenuItem screenshotWithSkin = new JMenuItem("Screenshot With Skin");
    simulatorMenu.add(screenshotWithSkin);
    screenshotWithSkin.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final float zoom = zoomLevel;
            zoomLevel = 1;
            final Form frm = Display.getInstance().getCurrent();
            BufferedImage headerImageTmp;
            if (isPortrait()) {
                headerImageTmp = header;
            } else {
                headerImageTmp = headerLandscape;
            }
            if (!includeHeaderInScreenshot) {
                headerImageTmp = null;
            }
            int headerHeightTmp = 0;
            if (headerImageTmp != null) {
                headerHeightTmp = headerImageTmp.getHeight();
            }
            final int headerHeight = headerHeightTmp;
            final BufferedImage headerImage = headerImageTmp;
            // gr.translate(0, statusBarHeight);
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    final com.codename1.ui.Image img = com.codename1.ui.Image.createImage(frm.getWidth(), frm.getHeight());
                    com.codename1.ui.Graphics gr = img.getGraphics();
                    takingScreenshot = true;
                    screenshotActualZoomLevel = zoom;
                    try {
                        frm.paint(gr);
                    } finally {
                        takingScreenshot = false;
                    }
                    final int imageWidth = img.getWidth();
                    final int imageHeight = img.getHeight();
                    final int[] imageRGB = img.getRGB();
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            BufferedImage bi = new BufferedImage(frm.getWidth(), frm.getHeight() + headerHeight, BufferedImage.TYPE_INT_ARGB);
                            bi.setRGB(0, headerHeight, imageWidth, imageHeight, imageRGB, 0, imageWidth);
                            BufferedImage skin = getSkin();
                            BufferedImage newSkin = new BufferedImage(skin.getWidth(), skin.getHeight(), BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2d = newSkin.createGraphics();
                            g2d.drawImage(bi, getScreenCoordinates().x, getScreenCoordinates().y, null);
                            if (headerImage != null) {
                                g2d.drawImage(headerImage, getScreenCoordinates().x, getScreenCoordinates().y, null);
                            }
                            g2d.drawImage(skin, 0, 0, null);
                            g2d.dispose();
                            OutputStream out = null;
                            try {
                                out = new FileOutputStream(findScreenshotFile());
                                ImageIO.write(newSkin, "png", out);
                                out.close();
                            } catch (Throwable ex) {
                                ex.printStackTrace();
                                System.exit(1);
                            } finally {
                                zoomLevel = zoom;
                                try {
                                    out.close();
                                } catch (Throwable ex) {
                                }
                                frm.repaint();
                                canvas.repaint();
                            }
                        }
                    });
                }
            });
        }
    });
    includeHeaderInScreenshot = pref.getBoolean("includeHeaderScreenshot", true);
    final JCheckBoxMenuItem includeHeaderMenu = new JCheckBoxMenuItem("Screenshot StatusBar");
    includeHeaderMenu.setToolTipText("Include status bar area in Screenshots");
    includeHeaderMenu.setSelected(includeHeaderInScreenshot);
    simulatorMenu.add(includeHeaderMenu);
    includeHeaderMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            includeHeaderInScreenshot = includeHeaderMenu.isSelected();
            pref.putBoolean("includeHeaderScreenshot", includeHeaderInScreenshot);
        }
    });
    JMenu networkDebug = new JMenu("Network");
    simulatorMenu.add(networkDebug);
    JMenuItem networkMonitor = new JMenuItem("Network Monitor");
    networkMonitor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (netMonitor == null) {
                showNetworkMonitor();
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.putBoolean("NetworkMonitor", true);
            }
        }
    });
    networkDebug.add(networkMonitor);
    JMenuItem proxy = new JMenuItem("Proxy Settings");
    proxy.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            final JDialog proxy;
            if (window != null) {
                proxy = new JDialog(window);
            } else {
                proxy = new JDialog();
            }
            final Preferences pref = Preferences.userNodeForPackage(Component.class);
            int proxySel = pref.getInt("proxySel", 2);
            String proxySelHttp = pref.get("proxySel-http", "");
            String proxySelPort = pref.get("proxySel-port", "");
            JPanel panel = new JPanel();
            panel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            JPanel proxyUrl = new JPanel();
            proxyUrl.setLayout(new FlowLayout(FlowLayout.LEFT));
            proxyUrl.add(new JLabel("Http Proxy:"));
            final JTextField http = new JTextField(proxySelHttp);
            http.setColumns(20);
            proxyUrl.add(http);
            proxyUrl.add(new JLabel("Port:"));
            final JTextField port = new JTextField(proxySelPort);
            port.setColumns(4);
            proxyUrl.add(port);
            final JRadioButton noproxy = new JRadioButton("No Proxy");
            JPanel rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(noproxy);
            Dimension d = rbPanel.getPreferredSize();
            d.width = proxyUrl.getPreferredSize().width;
            rbPanel.setMinimumSize(d);
            // noproxy.setPreferredSize(d);
            panel.add(rbPanel);
            final JRadioButton systemProxy = new JRadioButton("Use System Proxy");
            rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(systemProxy);
            d = rbPanel.getPreferredSize();
            d.width = proxyUrl.getPreferredSize().width;
            rbPanel.setPreferredSize(d);
            panel.add(rbPanel);
            final JRadioButton manual = new JRadioButton("Manual Proxy Settings:");
            rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(manual);
            d = rbPanel.getPreferredSize();
            d.width = proxyUrl.getPreferredSize().width;
            rbPanel.setPreferredSize(d);
            panel.add(rbPanel);
            rbPanel = new JPanel();
            rbPanel.setLayout(new java.awt.GridLayout(1, 0));
            rbPanel.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT);
            rbPanel.add(proxyUrl);
            panel.add(rbPanel);
            ButtonGroup group = new ButtonGroup();
            group.add(noproxy);
            group.add(systemProxy);
            group.add(manual);
            noproxy.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    http.setEnabled(false);
                    port.setEnabled(false);
                }
            });
            systemProxy.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    http.setEnabled(false);
                    port.setEnabled(false);
                }
            });
            manual.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    http.setEnabled(true);
                    port.setEnabled(true);
                }
            });
            switch(proxySel) {
                case 1:
                    noproxy.setSelected(true);
                    http.setEnabled(false);
                    port.setEnabled(false);
                    break;
                case 2:
                    systemProxy.setSelected(true);
                    http.setEnabled(false);
                    port.setEnabled(false);
                    break;
                case 3:
                    manual.setSelected(true);
                    break;
            }
            JPanel closePanel = new JPanel();
            JButton close = new JButton("Ok");
            close.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    if (noproxy.isSelected()) {
                        pref.putInt("proxySel", 1);
                    } else if (systemProxy.isSelected()) {
                        pref.putInt("proxySel", 2);
                    } else if (manual.isSelected()) {
                        pref.putInt("proxySel", 3);
                        pref.put("proxySel-http", http.getText());
                        pref.put("proxySel-port", port.getText());
                    }
                    proxy.dispose();
                    if (netMonitor != null) {
                        netMonitor.dispose();
                        netMonitor = null;
                    }
                    if (perfMonitor != null) {
                        perfMonitor.dispose();
                        perfMonitor = null;
                    }
                    String mainClass = System.getProperty("MainClass");
                    if (mainClass != null) {
                        Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                        deinitializeSync();
                        frm.dispose();
                        System.setProperty("reload.simulator", "true");
                    } else {
                        refreshSkin(frm);
                    }
                }
            });
            closePanel.add(close);
            panel.add(closePanel);
            proxy.add(panel);
            proxy.pack();
            if (window != null) {
                proxy.setLocationRelativeTo(window);
            }
            proxy.setResizable(false);
            proxy.setVisible(true);
        }
    });
    networkDebug.add(proxy);
    networkDebug.addSeparator();
    JRadioButtonMenuItem regularConnection = new JRadioButtonMenuItem("Regular Connection");
    regularConnection.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            slowConnectionMode = false;
            disconnectedMode = false;
            pref.putInt("connectionStatus", 0);
        }
    });
    networkDebug.add(regularConnection);
    JRadioButtonMenuItem slowConnection = new JRadioButtonMenuItem("Slow Connection");
    slowConnection.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            slowConnectionMode = true;
            disconnectedMode = false;
            pref.putInt("connectionStatus", 1);
        }
    });
    networkDebug.add(slowConnection);
    JRadioButtonMenuItem disconnected = new JRadioButtonMenuItem("Disconnected");
    disconnected.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            slowConnectionMode = false;
            disconnectedMode = true;
            pref.putInt("connectionStatus", 2);
        }
    });
    networkDebug.add(disconnected);
    ButtonGroup connectionGroup = new ButtonGroup();
    connectionGroup.add(regularConnection);
    connectionGroup.add(slowConnection);
    connectionGroup.add(disconnected);
    switch(pref.getInt("connectionStatus", 0)) {
        case 0:
            regularConnection.setSelected(true);
            break;
        case 1:
            slowConnection.setSelected(true);
            slowConnectionMode = true;
            break;
        case 2:
            disconnected.setSelected(true);
            disconnectedMode = true;
            break;
    }
    JMenuItem componentTreeInspector = new JMenuItem("Component Inspector");
    componentTreeInspector.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            new ComponentTreeInspector();
        }
    });
    JMenuItem locactionSim = new JMenuItem("Location Simulation");
    locactionSim.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (!fxExists) {
                System.err.println("This simulation requires jdk 7");
                return;
            }
            if (locSimulation == null) {
                locSimulation = new LocationSimulation();
            } else {
                locSimulation.setVisible(true);
            }
        }
    });
    simulatorMenu.add(locactionSim);
    JMenuItem pushSim = new JMenuItem("Push Simulation");
    pushSim.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (pushSimulation == null) {
                pushSimulation = new PushSimulator();
            }
            pref.putBoolean("PushSimulator", true);
            pushSimulation.setVisible(true);
        }
    });
    simulatorMenu.add(pushSim);
    simulatorMenu.add(componentTreeInspector);
    JMenuItem testRecorderMenu = new JMenuItem("Test Recorder");
    testRecorderMenu.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (testRecorder == null) {
                showTestRecorder();
            }
        }
    });
    simulatorMenu.add(testRecorderMenu);
    manualPurchaseSupported = pref.getBoolean("manualPurchaseSupported", true);
    managedPurchaseSupported = pref.getBoolean("managedPurchaseSupported", true);
    subscriptionSupported = pref.getBoolean("subscriptionSupported", true);
    refundSupported = pref.getBoolean("refundSupported", true);
    JMenu purchaseMenu = new JMenu("In App Purchase");
    simulatorMenu.add(purchaseMenu);
    final JCheckBoxMenuItem manualPurchaseSupportedMenu = new JCheckBoxMenuItem("Manual Purchase");
    manualPurchaseSupportedMenu.setSelected(manualPurchaseSupported);
    final JCheckBoxMenuItem managedPurchaseSupportedMenu = new JCheckBoxMenuItem("Managed Purchase");
    managedPurchaseSupportedMenu.setSelected(managedPurchaseSupported);
    final JCheckBoxMenuItem subscriptionSupportedMenu = new JCheckBoxMenuItem("Subscription");
    subscriptionSupportedMenu.setSelected(subscriptionSupported);
    final JCheckBoxMenuItem refundSupportedMenu = new JCheckBoxMenuItem("Refunds");
    refundSupportedMenu.setSelected(refundSupported);
    manualPurchaseSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            manualPurchaseSupported = manualPurchaseSupportedMenu.isSelected();
            pref.putBoolean("manualPurchaseSupported", manualPurchaseSupported);
        }
    });
    managedPurchaseSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            managedPurchaseSupported = managedPurchaseSupportedMenu.isSelected();
            pref.putBoolean("managedPurchaseSupported", managedPurchaseSupported);
        }
    });
    subscriptionSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            subscriptionSupported = subscriptionSupportedMenu.isSelected();
            pref.putBoolean("subscriptionSupported", subscriptionSupported);
        }
    });
    refundSupportedMenu.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            refundSupported = refundSupportedMenu.isSelected();
            pref.putBoolean("refundSupported", refundSupported);
        }
    });
    purchaseMenu.add(manualPurchaseSupportedMenu);
    purchaseMenu.add(managedPurchaseSupportedMenu);
    purchaseMenu.add(subscriptionSupportedMenu);
    purchaseMenu.add(refundSupportedMenu);
    JMenuItem performanceMonitor = new JMenuItem("Performance Monitor");
    performanceMonitor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (perfMonitor == null) {
                showPerformanceMonitor();
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.putBoolean("PerformanceMonitor", true);
            }
        }
    });
    simulatorMenu.add(performanceMonitor);
    JMenuItem clean = new JMenuItem("Clean Storage");
    clean.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            File home = new File(System.getProperty("user.home") + File.separator + appHomeDir);
            if (!home.exists()) {
                return;
            }
            if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to Clean all Storage under " + home.getAbsolutePath() + " ?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                File[] files = home.listFiles();
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    file.delete();
                }
            }
        }
    });
    simulatorMenu.add(clean);
    JMenu skinMenu = createSkinsMenu(frm, null);
    skinMenu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            menuDisplayed = true;
        }

        @Override
        public void menuCanceled(MenuEvent e) {
            menuDisplayed = false;
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuDisplayed = false;
        }
    });
    final JCheckBoxMenuItem touchFlag = new JCheckBoxMenuItem("Touch", touchDevice);
    simulatorMenu.add(touchFlag);
    final JCheckBoxMenuItem nativeInputFlag = new JCheckBoxMenuItem("Native Input", useNativeInput);
    simulatorMenu.add(nativeInputFlag);
    final JCheckBoxMenuItem simulateAndroidVKBFlag = new JCheckBoxMenuItem("Simulate Android VKB", simulateAndroidKeyboard);
    // simulatorMenu.add(simulateAndroidVKBFlag);
    final JCheckBoxMenuItem scrollFlag = new JCheckBoxMenuItem("Scrollable", scrollableSkin);
    simulatorMenu.add(scrollFlag);
    scrollFlag.setEnabled(!desktopSkin);
    final JCheckBoxMenuItem slowMotionFlag = new JCheckBoxMenuItem("Slow Motion", false);
    simulatorMenu.add(slowMotionFlag);
    slowMotionFlag.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Motion.setSlowMotion(slowMotionFlag.isSelected());
        }
    });
    final JCheckBoxMenuItem permFlag = new JCheckBoxMenuItem("Android 6 Permissions", android6PermissionsFlag);
    simulatorMenu.add(permFlag);
    permFlag.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            android6PermissionsFlag = !android6PermissionsFlag;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("Android6Permissions", android6PermissionsFlag);
        }
    });
    pause = new JMenuItem("Pause App");
    simulatorMenu.add(pause);
    pause.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (pause.getText().startsWith("Pause")) {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Executor.stopApp();
                        minimized = true;
                    }
                });
                canvas.setEnabled(false);
                pause.setText("Resume App");
            } else {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Executor.startApp();
                        minimized = false;
                    }
                });
                canvas.setEnabled(true);
                pause.setText("Pause App");
            }
        }
    });
    final JCheckBoxMenuItem alwaysOnTopFlag = new JCheckBoxMenuItem("Always on Top", alwaysOnTop);
    simulatorMenu.add(alwaysOnTopFlag);
    simulatorMenu.addSeparator();
    JMenuItem exit = new JMenuItem("Exit");
    simulatorMenu.add(exit);
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setDoubleBuffered(true);
    helpMenu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            menuDisplayed = true;
        }

        @Override
        public void menuCanceled(MenuEvent e) {
            menuDisplayed = false;
        }

        @Override
        public void menuDeselected(MenuEvent e) {
            menuDisplayed = false;
        }
    });
    JMenuItem javadocs = new JMenuItem("Javadocs");
    javadocs.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/javadoc/"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.add(javadocs);
    JMenuItem how = new JMenuItem("How Do I?...");
    how.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/how-do-i.html"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.add(how);
    JMenuItem forum = new JMenuItem("Community Forum");
    forum.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/discussion-forum.html"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.add(forum);
    JMenuItem bserver = new JMenuItem("Build Server");
    bserver.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI("https://www.codenameone.com/build-server.html"));
            } catch (Exception ex) {
            }
        }
    });
    helpMenu.addSeparator();
    helpMenu.add(bserver);
    helpMenu.addSeparator();
    JMenuItem about = new JMenuItem("About");
    about.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            final JDialog about;
            if (window != null) {
                about = new JDialog(window);
            } else {
                about = new JDialog();
            }
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            JPanel imagePanel = new JPanel();
            JLabel image = new JLabel(new javax.swing.ImageIcon(getClass().getResource("/CodenameOne_Small.png")));
            image.setHorizontalAlignment(SwingConstants.CENTER);
            imagePanel.add(image);
            panel.add(imagePanel);
            JPanel linkPanel = new JPanel();
            JButton link = new JButton();
            link.setText("<HTML>For more information, please <br>visit <FONT color=\"#000099\"><U>www.codenameone.com</U></FONT></HTML>");
            link.setHorizontalAlignment(SwingConstants.LEFT);
            link.setBorderPainted(false);
            link.setOpaque(false);
            link.setBackground(Color.WHITE);
            link.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    try {
                        Desktop.getDesktop().browse(new URI("https://www.codenameone.com"));
                    } catch (Exception ex) {
                    }
                }
            });
            linkPanel.add(link);
            panel.add(linkPanel);
            JPanel closePanel = new JPanel();
            JButton close = new JButton("close");
            close.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    about.dispose();
                }
            });
            closePanel.add(close);
            panel.add(closePanel);
            about.add(panel);
            about.pack();
            if (window != null) {
                about.setLocationRelativeTo(window);
            }
            about.setVisible(true);
        }
    });
    helpMenu.add(about);
    if (showMenu) {
        bar.add(simulatorMenu);
        bar.add(skinMenu);
        bar.add(helpMenu);
    }
    rotate.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            portrait = !portrait;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("Portrait", portrait);
            float w1 = ((float) canvas.getWidth()) / ((float) getSkin().getWidth() / (float) retinaScale);
            float h1 = ((float) canvas.getHeight()) / ((float) getSkin().getHeight() / (float) retinaScale);
            zoomLevel = Math.min(h1, w1);
            Container parent = canvas.getParent();
            parent.remove(canvas);
            canvas.setForcedSize(new java.awt.Dimension((int) (getSkin().getWidth() / retinaScale), (int) (getSkin().getHeight() / retinaScale)));
            parent.add(BorderLayout.CENTER, canvas);
            frm.pack();
            zoomLevel = 1;
            JavaSEPort.this.sizeChanged(getScreenCoordinates().width, getScreenCoordinates().height);
        }
    });
    alwaysOnTopFlag.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent ie) {
            alwaysOnTop = !alwaysOnTop;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("AlwaysOnTop", alwaysOnTop);
            window.setAlwaysOnTop(alwaysOnTop);
        }
    });
    simulateAndroidVKBFlag.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent ie) {
            simulateAndroidKeyboard = !simulateAndroidKeyboard;
        }
    });
    ItemListener zoomListener = new ItemListener() {

        public void itemStateChanged(ItemEvent ie) {
            scrollableSkin = !scrollableSkin;
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("Scrollable", scrollableSkin);
            if (scrollableSkin) {
                frm.add(java.awt.BorderLayout.SOUTH, hSelector);
                frm.add(java.awt.BorderLayout.EAST, vSelector);
            } else {
                frm.remove(hSelector);
                frm.remove(vSelector);
            }
            Container parent = canvas.getParent();
            parent.remove(canvas);
            canvas.setForcedSize(new java.awt.Dimension((int) (getSkin().getWidth() / retinaScale), (int) (getSkin().getHeight() / retinaScale)));
            parent.add(BorderLayout.CENTER, canvas);
            canvas.x = 0;
            canvas.y = 0;
            zoomLevel = 1;
            frm.invalidate();
            frm.pack();
            Display.getInstance().getCurrent().repaint();
            frm.repaint();
        }
    };
    zoomMenu.addItemListener(zoomListener);
    scrollFlag.addItemListener(zoomListener);
    exit.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            exitApplication();
        }
    });
}
Also used : ActionEvent(java.awt.event.ActionEvent) BufferedOutputStream(com.codename1.io.BufferedOutputStream) Graphics(com.codename1.ui.Graphics) Dimension(java.awt.Dimension) ActionListener(java.awt.event.ActionListener) ItemEvent(java.awt.event.ItemEvent) Form(com.codename1.ui.Form) MenuListener(javax.swing.event.MenuListener) URI(java.net.URI) BufferedImage(java.awt.image.BufferedImage) Preferences(java.util.prefs.Preferences) BrowserComponent(com.codename1.ui.BrowserComponent) Component(com.codename1.ui.Component) JTextComponent(javax.swing.text.JTextComponent) PeerComponent(com.codename1.ui.PeerComponent) MenuEvent(javax.swing.event.MenuEvent) Image(com.codename1.ui.Image) Dimension(java.awt.Dimension) Point(java.awt.Point) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) Graphics2D(java.awt.Graphics2D) ItemListener(java.awt.event.ItemListener) java.awt(java.awt)

Example 28 with Location

use of com.codename1.location.Location in project CodenameOne by codenameone.

the class SEBrowserComponent method init.

private static void init(SEBrowserComponent self, BrowserComponent p) {
    final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<>(self);
    final WeakReference<BrowserComponent> weakP = new WeakReference<>(p);
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            SEBrowserComponent self = weakSelf.get();
            if (self == null) {
                return;
            }
            self.cnt = new InternalJPanel(self.instance, self);
            // <--- Important if container is opaque it will cause
            self.cnt.setOpaque(false);
            // all kinds of flicker due to painting conflicts with CN1 pipeline.
            self.cnt.setLayout(new BorderLayout());
            self.cnt.add(BorderLayout.CENTER, self.panel);
        // cnt.setVisible(false);
        }
    });
    self.web.getEngine().getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> ov, String t, String t1) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (t1.startsWith("Loading http:") || t1.startsWith("Loading file:") || t1.startsWith("Loading https:")) {
                String url = t1.substring("Loading ".length());
                if (!url.equals(self.currentURL)) {
                    p.fireWebEvent("onStart", new ActionEvent(url));
                }
                self.currentURL = url;
            } else if ("Loading complete".equals(t1)) {
            }
        }
    });
    self.web.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {

        @Override
        public void handle(WebEvent<String> t) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            String msg = t.getData();
            if (msg.startsWith("!cn1_message:")) {
                System.out.println("Receiving message " + msg);
                p.fireWebEvent("onMessage", new ActionEvent(msg.substring("!cn1_message:".length())));
            }
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            System.out.println("Received exception: " + t1.getMessage());
            if (ov.getValue() != null) {
                ov.getValue().printStackTrace();
            }
            if (t != ov.getValue() && t != null) {
                t.printStackTrace();
            }
            if (t1 != ov.getValue() && t1 != t && t1 != null) {
                t.printStackTrace();
            }
        }
    });
    self.web.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {

        @Override
        public void changed(ObservableValue ov, State oldState, State newState) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            try {
                netscape.javascript.JSObject w = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                if (w == null) {
                    System.err.println("Could not get window");
                } else {
                    Bridge b = new Bridge(p);
                    self.putClientProperty("SEBrowserComponent.Bridge.jconsole", b);
                    w.setMember("jconsole", b);
                }
            } catch (Throwable t) {
                Log.e(t);
            }
            if (self == null || p == null) {
                return;
            }
            String url = self.web.getEngine().getLocation();
            if (newState == State.SCHEDULED) {
                p.fireWebEvent("onStart", new ActionEvent(url));
            } else if (newState == State.RUNNING) {
                p.fireWebEvent("onLoadResource", new ActionEvent(url));
            } else if (newState == State.SUCCEEDED) {
                if (!p.isNativeScrollingEnabled()) {
                    self.web.getEngine().executeScript("document.body.style.overflow='hidden'");
                }
                // let's just add a client property to the BrowserComponent to enable firebug
                if (Boolean.TRUE.equals(p.getClientProperty("BrowserComponent.firebug"))) {
                    self.web.getEngine().executeScript("if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document['createElement' + 'NS'](E, 'script') : document['createElement']('script');E['setAttribute']('id', 'FirebugLite');E['setAttribute']('src', 'https://getfirebug.com/' + 'firebug-lite.js' + '#startOpened');E['setAttribute']('FirebugLite', '4');(document['getElementsByTagName']('head')[0] || document['getElementsByTagName']('body')[0]).appendChild(E);E = new Image;E['setAttribute']('src', 'https://getfirebug.com/' + '#startOpened');}");
                }
                netscape.javascript.JSObject window = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                Bridge b = new Bridge(p);
                self.putClientProperty("SEBrowserComponent.Bridge.cn1application", b);
                window.setMember("cn1application", b);
                self.web.getEngine().executeScript("while (window._cn1ready && window._cn1ready.length > 0) {var f = window._cn1ready.shift(); f();}");
                // System.out.println("cn1application is "+self.web.getEngine().executeScript("window.cn1application && window.cn1application.shouldNavigate"));
                self.web.getEngine().executeScript("window.addEventListener('unload', function(e){console.log('unloading...');return 'foobar';});");
                p.fireWebEvent("onLoad", new ActionEvent(url));
            }
            self.currentURL = url;
            self.repaint();
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            t1.printStackTrace();
            if (t1 == null) {
                if (t == null) {
                    p.fireWebEvent("onError", new ActionEvent("Unknown error", -1));
                } else {
                    p.fireWebEvent("onError", new ActionEvent(t.getMessage(), -1));
                }
            } else {
                p.fireWebEvent("onError", new ActionEvent(t1.getMessage(), -1));
            }
        }
    });
    // Monitor the location property so that we can send the shouldLoadURL event.
    // This allows us to cancel the loading of a URL if we want to handle it ourself.
    self.web.getEngine().locationProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> prop, String before, String after) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (!p.fireBrowserNavigationCallbacks(self.web.getEngine().getLocation())) {
                self.web.getEngine().getLoadWorker().cancel();
            }
        }
    });
    self.adjustmentListener = new AdjustmentListener() {

        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    SEBrowserComponent self = weakSelf.get();
                    if (self == null) {
                        return;
                    }
                    self.onPositionSizeChange();
                }
            });
        }
    };
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) ObservableValue(javafx.beans.value.ObservableValue) BorderLayout(java.awt.BorderLayout) WeakReference(java.lang.ref.WeakReference) WebEvent(javafx.scene.web.WebEvent) AdjustmentEvent(java.awt.event.AdjustmentEvent) State(javafx.concurrent.Worker.State) AdjustmentListener(java.awt.event.AdjustmentListener)

Example 29 with Location

use of com.codename1.location.Location in project CodenameOne by codenameone.

the class StubLocationManager method bindListener.

@Override
protected void bindListener() {
    checkLocationRegistration();
    setStatus(AVAILABLE);
    final LocationListener l = getLocationListener();
    task = new TimerTask() {

        @Override
        public void run() {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    Location loc;
                    try {
                        loc = getCurrentLocation();
                        if (JavaSEPort.locSimulation == null) {
                            loc.setLongitude(loc.getLongitude() + 0.001);
                            loc.setLatitude(loc.getLatitude() + +0.001);
                        } else {
                            int s = JavaSEPort.locSimulation.getState();
                            if (s != StubLocationManager.super.getStatus()) {
                                l.providerStateChanged(s);
                                setStatus(s);
                            }
                        }
                        l.locationUpdated(loc);
                    } catch (IOException ex) {
                        Logger.getLogger(StubLocationManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
    };
    timer = new Timer();
    timer.schedule(task, 3000, 3000);
}
Also used : TimerTask(java.util.TimerTask) Timer(java.util.Timer) LocationListener(com.codename1.location.LocationListener) IOException(java.io.IOException) Location(com.codename1.location.Location)

Example 30 with Location

use of com.codename1.location.Location in project CodenameOne by codenameone.

the class URLImage method createCachedImage.

/**
 * Creates an image that will be downloaded on the fly as necessary.  On platforms that support a native
 * image cache (e.g. Javascript), the image will be loaded directly from the native cache (i.e. it defers to the
 * platform to handle all caching considerations.  On platforms that don't have a native image cache but
 * do have a caches directory {@link FileSystemStorage#hasCachesDir()}, this will call {@link #createToFileSystem(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String, com.codename1.ui.URLImage.ImageAdapter) }
 * with a file location in the caches directory.  In all other cases, this will call {@link #createToStorage(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String) }.
 *
 * @param imageName The name of the image.
 * @param url the URL from which the image is fetched
 * @param placeholder the image placeholder is shown as the image is loading/downloading
 * and serves as the guideline to the size of the downloaded image.
 * @param resizeRule One of {@link #FLAG_RESIZE_FAIL}, {@link #FLAG_RESIZE_SCALE}, or {@link #FLAG_RESIZE_SCALE_TO_FILL}.
 * @return a Image that will initially just delegate to the placeholder
 */
public static Image createCachedImage(String imageName, String url, Image placeholder, int resizeRule) {
    if (Display.getInstance().supportsNativeImageCache()) {
        CachedImage im = new CachedImage(placeholder, url, resizeRule);
        im.setImageName(imageName);
        return im;
    } else {
        ImageAdapter adapter = null;
        switch(resizeRule) {
            case FLAG_RESIZE_FAIL:
                adapter = RESIZE_FAIL;
                break;
            case FLAG_RESIZE_SCALE:
                adapter = RESIZE_SCALE;
                break;
            case FLAG_RESIZE_SCALE_TO_FILL:
                adapter = RESIZE_SCALE_TO_FILL;
                break;
            default:
                adapter = RESIZE_SCALE_TO_FILL;
                break;
        }
        FileSystemStorage fs = FileSystemStorage.getInstance();
        if (fs.hasCachesDir()) {
            String name = "cn1_image_cache[" + url + "]";
            name = StringUtil.replaceAll(name, "/", "_");
            name = StringUtil.replaceAll(name, "\\", "_");
            name = StringUtil.replaceAll(name, "%", "_");
            name = StringUtil.replaceAll(name, "?", "_");
            name = StringUtil.replaceAll(name, "*", "_");
            name = StringUtil.replaceAll(name, ":", "_");
            name = StringUtil.replaceAll(name, "=", "_");
            String filePath = fs.getCachesDir() + fs.getFileSystemSeparator() + name;
            // System.out.println("Creating to file system "+filePath);
            URLImage im = createToFileSystem(EncodedImage.createFromImage(placeholder, false), filePath, url, adapter);
            im.setImageName(imageName);
            return im;
        } else {
            // System.out.println("Creating to storage ");
            URLImage im = createToStorage(EncodedImage.createFromImage(placeholder, false), "cn1_image_cache[" + url + "@" + placeholder.getWidth() + "x" + placeholder.getHeight(), url, adapter);
            im.setImageName(imageName);
            return im;
        }
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Aggregations

ArrayList (java.util.ArrayList)18 Location (location.Location)17 Location (com.codename1.location.Location)5 IOException (java.io.IOException)5 Point (com.codename1.ui.geom.Point)4 Component (com.codename1.ui.Component)3 ActionEvent (com.codename1.ui.events.ActionEvent)3 ConnectionRequest (com.codename1.io.ConnectionRequest)2 BrowserComponent (com.codename1.ui.BrowserComponent)2 ActionListener (com.codename1.ui.events.ActionListener)2 QualifiedCoordinates (javax.microedition.location.QualifiedCoordinates)2 Paint (com.codename1.charts.compat.Paint)1 Point (com.codename1.charts.models.Point)1 XYSeries (com.codename1.charts.models.XYSeries)1 Orientation (com.codename1.charts.renderers.XYMultipleSeriesRenderer.Orientation)1 XYSeriesRenderer (com.codename1.charts.renderers.XYSeriesRenderer)1 BindTarget (com.codename1.cloud.BindTarget)1 CodenameOneImplementation (com.codename1.impl.CodenameOneImplementation)1 BufferedOutputStream (com.codename1.io.BufferedOutputStream)1 FileSystemStorage (com.codename1.io.FileSystemStorage)1