Search in sources :

Example 6 with Actions

use of com.codename1.rad.ui.Actions in project CodenameOne by codenameone.

the class JavaSEPort method editString.

/**
 * @inheritDoc
 */
public void editString(final Component cmp, final int maxSize, final int constraint, String text, final int keyCode) {
    if (scrollWheeling) {
        return;
    }
    if (System.getProperty("TextCompatMode") != null) {
        editStringLegacy(cmp, maxSize, constraint, text, keyCode);
        return;
    }
    if (editingInProgress != null) {
        final String fText = text;
        editingInProgress.invokeAfter(new Runnable() {

            public void run() {
                CN.callSerially(new Runnable() {

                    public void run() {
                        editString(cmp, maxSize, constraint, fText, keyCode);
                    }
                });
            }
        });
        editingInProgress.endEditing();
        return;
    }
    // a workaround to fix an issue where the previous Text Component wasn't removed properly.
    // java.awt.Component [] cmps = canvas.getComponents();
    // for (int i = 0; i < cmps.length; i++) {
    // java.awt.Component cmp1 = cmps[i];
    // if(cmp1 instanceof JScrollPane || cmp1 instanceof javax.swing.text.JTextComponent){
    // canvas.remove(cmp1);
    // }
    // }
    checkEDT();
    class Repainter {

        JComponent jcmp;

        javax.swing.border.Border origBorder;

        Repainter(JComponent jcmp) {
            this.jcmp = jcmp;
        }

        void repaint(long tm, int x, int y, int width, int height) {
            boolean oldShowEdtWarnings = showEDTWarnings;
            showEDTWarnings = false;
            // cmp.getSelectedStyle().getPadding(Component.TOP);
            int marginTop = 0;
            // cmp.getSelectedStyle().getPadding(Component.LEFT);
            int marginLeft = 0;
            // cmp.getSelectedStyle().getPadding(Component.RIGHT);
            int marginRight = 0;
            // cmp.getSelectedStyle().getPadding(Component.BOTTOM);
            int marginBottom = 0;
            int paddingTop = Math.round(cmp.getSelectedStyle().getPadding(Component.TOP) * zoomLevel);
            int paddingLeft = Math.round(cmp.getSelectedStyle().getPadding(Component.LEFT) * zoomLevel);
            int paddingRight = Math.round(cmp.getSelectedStyle().getPadding(Component.RIGHT) * zoomLevel);
            int paddingBottom = Math.round(cmp.getSelectedStyle().getPadding(Component.BOTTOM) * zoomLevel);
            Rectangle bounds;
            if (getSkin() != null) {
                bounds = new Rectangle((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + getScreenCoordinates().x + canvas.x + marginLeft) * zoomLevel), (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + getScreenCoordinates().y + canvas.y + marginTop) * zoomLevel), (int) ((cmp.getWidth() - marginLeft - marginRight) * zoomLevel), (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel));
            } else {
                bounds = new Rectangle(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom);
            }
            if (!jcmp.getBounds().equals(bounds)) {
                jcmp.setBounds(bounds);
                if (origBorder == null) {
                    origBorder = jcmp.getBorder();
                }
                // jcmp.setBorder(BorderFactory.createCompoundBorder(
                // origBorder,
                // BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight))
                // );
                jcmp.setBorder(BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight));
            }
            showEDTWarnings = oldShowEdtWarnings;
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    cmp.repaint();
                }
            });
        }
    }
    javax.swing.text.JTextComponent swingT;
    if (((com.codename1.ui.TextArea) cmp).isSingleLineTextArea()) {
        JTextComponent t;
        if ((constraint & TextArea.PASSWORD) == TextArea.PASSWORD) {
            t = new JPasswordField() {

                Repainter repainter = new Repainter(this);

                @Override
                public void repaint(long tm, int x, int y, int width, int height) {
                    if (repainter != null) {
                        repainter.repaint(tm, x, y, width, height);
                    }
                }
            };
        } else {
            t = new JTextField() {

                Repainter repainter = new Repainter(this);

                @Override
                public void repaint(long tm, int x, int y, int width, int height) {
                    if (repainter != null) {
                        repainter.repaint(tm, x, y, width, height);
                    }
                }
            };
        /*
                ((JTextField)t).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (cmp instanceof com.codename1.ui.TextField) {
                            final com.codename1.ui.TextField tf = (com.codename1.ui.TextField)cmp;
                            if (tf.getDoneListener() != null) {
                                Display.getInstance().callSerially(new Runnable() {
                                    public void run() {
                                        if (tf.getDoneListener() != null) {
                                            tf.fireDoneEvent();
                                        }
                                    }
                                });
                            }
                        }
                    }
                    
                });
                */
        }
        swingT = t;
        textCmp = swingT;
    } else {
        // Forward references so that we can access the scroll pane and its
        // repainter from inside the JTextArea.
        final Repainter[] fRepainter = new Repainter[1];
        final JScrollPane[] fPane = new JScrollPane[1];
        final com.codename1.ui.TextArea ta = (com.codename1.ui.TextArea) cmp;
        JTextArea t = new JTextArea() {

            @Override
            public void repaint(long tm, int x, int y, int width, int height) {
                // enough.
                if (fRepainter[0] != null && fPane[0] != null) {
                    Point p = SwingUtilities.convertPoint(this, x, y, fPane[0]);
                    fRepainter[0].repaint(tm, p.x, p.y, width, height);
                }
            }
        };
        t.setWrapStyleWord(true);
        t.setLineWrap(true);
        swingT = t;
        JScrollPane pane = new JScrollPane(swingT) {

            Repainter repainter = new Repainter(this);

            {
                fRepainter[0] = repainter;
            }

            @Override
            public void repaint(long tm, int x, int y, int width, int height) {
                if (repainter != null) {
                    repainter.repaint(tm, x, y, width, height);
                }
            }
        };
        fPane[0] = pane;
        if (ta.isGrowByContent()) {
            pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        }
        pane.setBorder(null);
        pane.setOpaque(false);
        pane.getViewport().setOpaque(false);
        // Without these scrollbars, it seems terribly difficult
        // to work with TextAreas that contain more text than can fit.
        // Commenting these out for better usability - at least on OS X.
        // pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        // pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textCmp = pane;
    }
    if (cmp.isRTL()) {
        textCmp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }
    DefaultCaret caret = (DefaultCaret) swingT.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    swingT.setFocusTraversalKeysEnabled(false);
    TextEditUtil.setCurrentEditComponent(cmp);
    final javax.swing.text.JTextComponent txt = swingT;
    txt.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_TAB) {
                if (e.isShiftDown()) {
                    TextEditUtil.editPrevTextArea();
                } else {
                    TextEditUtil.editNextTextArea();
                }
            }
        }
    });
    // swingT.setBorder(null);
    swingT.setOpaque(false);
    swingT.setForeground(new Color(cmp.getUnselectedStyle().getFgColor()));
    swingT.setCaretColor(new Color(cmp.getUnselectedStyle().getFgColor()));
    final javax.swing.text.JTextComponent tf = swingT;
    if (keyCode > 0) {
        text += ((char) keyCode);
        setText(tf, text);
        setCaretPosition(tf, text.length());
        if (cmp instanceof com.codename1.ui.TextField) {
            ((com.codename1.ui.TextField) cmp).setText(getText(tf));
        }
    } else {
        setText(tf, text);
    }
    textCmp.setBorder(null);
    textCmp.setOpaque(false);
    canvas.add(textCmp);
    int marginTop = cmp.getSelectedStyle().getPadding(Component.TOP);
    int marginLeft = cmp.getSelectedStyle().getPadding(Component.LEFT);
    int marginRight = cmp.getSelectedStyle().getPadding(Component.RIGHT);
    int marginBottom = cmp.getSelectedStyle().getPadding(Component.BOTTOM);
    if (getSkin() != null) {
        textCmp.setBounds((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + getScreenCoordinates().x + canvas.x + marginLeft) * zoomLevel), (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + getScreenCoordinates().y + canvas.y + marginTop) * zoomLevel), (int) ((cmp.getWidth() - marginLeft - marginRight) * zoomLevel), (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel));
        // System.out.println("Set bounds to "+textCmp.getBounds());
        java.awt.Font f = font(cmp.getStyle().getFont().getNativeFont());
        tf.setFont(f.deriveFont(f.getSize2D() * zoomLevel));
    } else {
        textCmp.setBounds(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom);
        // System.out.println("Set bounds to "+textCmp.getBounds());
        tf.setFont(font(cmp.getStyle().getFont().getNativeFont()));
    }
    if (tf instanceof JPasswordField && tf.getFont() != null && tf.getFont().getFontName().contains("Roboto")) {
        java.awt.Font fallback = new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, tf.getFont().getSize());
        tf.setFont(fallback);
    }
    setCaretPosition(tf, getText(tf).length());
    // Windows Tablet Show Virtual Keyboard
    // REf https://stackoverflow.com/a/25783041/2935174
    final String sysroot = System.getenv("SystemRoot");
    String tabTipExe = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";
    if (exposeFilesystem) {
        final boolean useTabTip = "tabtip".equalsIgnoreCase(Display.getInstance().getProperty("javase.win.vkb", "tabtip"));
        if (new File(tabTipExe).exists()) {
            try {
                if (useTabTip) {
                    // System.out.println("Opening TabTip");
                    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", tabTipExe);
                    tabTipProcess = pb.start();
                } else {
                    // System.out.println("Opening OSK");
                    ProcessBuilder pb = new ProcessBuilder(sysroot + "/system32/osk.exe");
                    tabTipProcess = pb.start();
                }
            } catch (Exception e) {
                System.err.println("Failed to open VKB: " + e.getMessage());
            }
            tf.addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent arg0) {
                    // System.out.println("Lost focus...");
                    try {
                        if (tabTipProcess != null) {
                            tabTipProcess.destroy();
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (useTabTip) {
                            Runtime.getRuntime().exec("cmd /c taskkill /IM TabTip.exe");
                        } else {
                            Runtime.getRuntime().exec("cmd /c taskkill /IM osk.exe");
                        }
                    } catch (IOException e) {
                        System.err.println("Problem closing VKB: " + e.getMessage());
                    }
                }

                @Override
                public void focusGained(FocusEvent arg0) {
                }
            });
        }
    }
    tf.requestFocus();
    tf.setSelectionStart(0);
    tf.setSelectionEnd(0);
    class Listener implements ActionListener, FocusListener, KeyListener, TextListener, Runnable, DocumentListener, EditingInProgress {

        private final JTextComponent textCmp;

        private final JComponent swingComponentToRemove;

        private boolean performed;

        private boolean fireDone;

        Listener(JTextComponent textCmp, JComponent swingComponentToRemove) {
            this.textCmp = textCmp;
            this.swingComponentToRemove = swingComponentToRemove;
            if (textCmp instanceof JTextArea) {
                if (((com.codename1.ui.TextArea) cmp).getDoneListener() != null) {
                    InputMap input = textCmp.getInputMap();
                    KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
                    KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
                    // input.get(enter)) = "insert-break"
                    input.put(shiftEnter, "insert-break");
                    input.put(enter, "text-submit");
                    ActionMap actions = textCmp.getActionMap();
                    actions.put("text-submit", new AbstractAction() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            fireDone = true;
                            Listener.this.actionPerformed(null);
                        }
                    });
                }
            }
        }

        public void run() {
            while (swingComponentToRemove.getParent() != null) {
                synchronized (this) {
                    try {
                        wait(20);
                    } catch (InterruptedException ex) {
                    }
                }
            }
            EventQueue.invokeLater(new Runnable() {

                public void run() {
                    actionPerformed(null);
                }
            });
        }

        public void actionPerformed(ActionEvent e) {
            if (performed) {
                return;
            }
            performed = true;
            String txt = getText(tf);
            if (testRecorder != null) {
                testRecorder.editTextFieldCompleted(cmp, txt);
            }
            Display.getInstance().onEditingComplete(cmp, txt);
            if (e != null && cmp instanceof com.codename1.ui.TextField || fireDone) {
                final com.codename1.ui.TextArea cn1Tf = (com.codename1.ui.TextArea) cmp;
                if (cmp != null && cn1Tf.getDoneListener() != null) {
                    cn1Tf.fireDoneEvent();
                }
            }
            if (tf instanceof JTextField) {
                ((JTextField) tf).removeActionListener(this);
            }
            ((JTextComponent) tf).getDocument().removeDocumentListener(this);
            tf.removeFocusListener(this);
            canvas.remove(swingComponentToRemove);
            editingInProgress = null;
            currentlyEditingField = null;
            synchronized (this) {
                notify();
            }
            canvas.repaint();
            if (invokeAfter != null) {
                for (Runnable r : invokeAfter) {
                    r.run();
                }
                invokeAfter = null;
            }
        }

        public void focusGained(FocusEvent e) {
            setCaretPosition(tf, getText(tf).length());
        }

        public void focusLost(FocusEvent e) {
            actionPerformed(null);
        }

        public void keyTyped(KeyEvent e) {
            String t = getText(tf);
            if (t.length() >= ((TextArea) cmp).getMaxSize()) {
                e.consume();
            }
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                if (tf instanceof JTextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) >= getText(tf).length() - 1) {
                        actionPerformed(null);
                    }
                }
                return;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                if (tf instanceof JTextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) <= 2) {
                        actionPerformed(null);
                    }
                }
                return;
            }
        }

        public void textValueChanged(TextEvent e) {
            // if (cmp instanceof com.codename1.ui.TextField) {
            updateText();
        // }
        }

        private void updateText() {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    // if(cmp instanceof com.codename1.ui.TextField) {
                    ((com.codename1.ui.TextArea) cmp).setText(getText(tf));
                // }
                }
            });
        }

        public void insertUpdate(DocumentEvent e) {
            updateText();
        }

        public void removeUpdate(DocumentEvent e) {
            updateText();
        }

        public void changedUpdate(DocumentEvent e) {
            updateText();
        }

        private ArrayList<Runnable> invokeAfter;

        @Override
        public void invokeAfter(Runnable r) {
            if (invokeAfter == null) {
                invokeAfter = new ArrayList<Runnable>();
            }
            invokeAfter.add(r);
        }

        @Override
        public void endEditing() {
            if (!EventQueue.isDispatchThread()) {
                EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        endEditing();
                    }
                });
                return;
            }
            actionPerformed(null);
        }
    }
    ;
    final Listener l = new Listener(tf, textCmp);
    if (tf instanceof JTextField) {
        ((JTextField) tf).addActionListener(l);
    }
    ((JTextComponent) tf).getDocument().addDocumentListener(l);
    tf.addKeyListener(l);
    tf.addFocusListener(l);
    if (simulateAndroidKeyboard) {
        java.util.Timer t = new java.util.Timer();
        TimerTask tt = new TimerTask() {

            @Override
            public void run() {
                if (!Display.getInstance().isEdt()) {
                    Display.getInstance().callSerially(this);
                    return;
                }
                if (tf.getParent() != null) {
                    final int height = getScreenCoordinates().height;
                    JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height / 2);
                    new UITimer(new Runnable() {

                        public void run() {
                            if (tf.getParent() != null) {
                                new UITimer(this).schedule(100, false, Display.getInstance().getCurrent());
                            } else {
                                JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height);
                            }
                        }
                    }).schedule(100, false, Display.getInstance().getCurrent());
                }
            }
        };
        t.schedule(tt, 300);
    }
    editingInProgress = l;
    currentlyEditingField = cmp;
    new Thread(l).start();
}
Also used : TextArea(com.codename1.ui.TextArea) Rectangle(java.awt.Rectangle) JTextComponent(javax.swing.text.JTextComponent) Timer(java.util.Timer) AttributedString(java.text.AttributedString) DefaultCaret(javax.swing.text.DefaultCaret) FontRenderContext(java.awt.font.FontRenderContext) Color(java.awt.Color) java.util(java.util) EmptyBorder(javax.swing.border.EmptyBorder) TextArea(com.codename1.ui.TextArea) UITimer(com.codename1.ui.util.UITimer) Font(com.codename1.ui.Font) Point(java.awt.Point) JTextComponent(javax.swing.text.JTextComponent) Point(java.awt.Point) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) LineUnavailableException(javax.sound.sampled.LineUnavailableException) javax.swing(javax.swing) UITimer(com.codename1.ui.util.UITimer) Timer(java.util.Timer) java.awt(java.awt)

Example 7 with Actions

use of com.codename1.rad.ui.Actions in project CodenameOne by codenameone.

the class IOSImplementation method initPushActionCategories.

public static void initPushActionCategories() {
    if (pushCallback instanceof PushActionsProvider) {
        PushActionsProvider actionsProvider = (PushActionsProvider) pushCallback;
        PushActionCategory[] categories = actionsProvider.getPushActionCategories();
        if (categories != null) {
            PushAction[] actions = PushActionCategory.getAllActions(categories);
            for (PushAction action : actions) {
                nativeInstance.registerPushAction(action.getId(), action.getTitle(), action.getTextInputPlaceholder(), action.getTextInputButtonText());
            }
            for (PushActionCategory category : categories) {
                nativeInstance.startPushActionCategory(category.getId());
                for (PushAction action : category.getActions()) {
                    nativeInstance.addPushActionToCategory(action.getId());
                }
                nativeInstance.endPushActionCategory();
            }
            nativeInstance.registerPushCategories();
        }
    }
}
Also used : PushActionsProvider(com.codename1.push.PushActionsProvider) PushActionCategory(com.codename1.push.PushActionCategory) PushAction(com.codename1.push.PushAction)

Example 8 with Actions

use of com.codename1.rad.ui.Actions in project CodenameOne by codenameone.

the class AndroidImplementation method installNotificationActionCategories.

/**
 * Action categories are defined on the Main class by implementing the PushActionsProvider, however
 * the main class may not be available to the push receiver, so we need to save these categories
 * to the file system when the app is installed, then the push receiver can load these actions
 * when it sends a push while the app isn't running.
 * @param provider A reference to the App's main class
 * @throws IOException
 */
public static void installNotificationActionCategories(PushActionsProvider provider) throws IOException {
    // Assume that CN1 is running... this will run when the app starts
    // up
    Context context = getContext();
    boolean requiresUpdate = false;
    File categoriesFile = new File(activity.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
    if (!categoriesFile.exists()) {
        requiresUpdate = true;
    }
    if (!requiresUpdate) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
            if (packageInfo.lastUpdateTime > categoriesFile.lastModified()) {
                requiresUpdate = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    if (!requiresUpdate) {
        return;
    }
    OutputStream os = getContext().openFileOutput(FILE_NAME_NOTIFICATION_CATEGORIES, 0);
    PushActionCategory[] categories = provider.getPushActionCategories();
    javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException("Faield to create document builder for creating notification categories XML document", ex);
    }
    // root elements
    org.w3c.dom.Document doc = docBuilder.newDocument();
    org.w3c.dom.Element root = (org.w3c.dom.Element) doc.createElement("categories");
    doc.appendChild(root);
    for (PushActionCategory category : categories) {
        org.w3c.dom.Element categoryEl = (org.w3c.dom.Element) doc.createElement("category");
        org.w3c.dom.Attr idAttr = doc.createAttribute("id");
        idAttr.setValue(category.getId());
        categoryEl.setAttributeNode(idAttr);
        for (PushAction action : category.getActions()) {
            org.w3c.dom.Element actionEl = (org.w3c.dom.Element) doc.createElement("action");
            org.w3c.dom.Attr actionIdAttr = doc.createAttribute("id");
            actionIdAttr.setValue(action.getId());
            actionEl.setAttributeNode(actionIdAttr);
            org.w3c.dom.Attr actionTitleAttr = doc.createAttribute("title");
            if (action.getTitle() != null) {
                actionTitleAttr.setValue(action.getTitle());
            } else {
                actionTitleAttr.setValue(action.getId());
            }
            actionEl.setAttributeNode(actionTitleAttr);
            if (action.getIcon() != null) {
                org.w3c.dom.Attr actionIconAttr = doc.createAttribute("icon");
                String iconVal = action.getIcon();
                try {
                    // We'll store the resource IDs for the icon
                    // rather than the icon name because that is what
                    // the push notifications require.
                    iconVal = "" + context.getResources().getIdentifier(iconVal, "drawable", context.getPackageName());
                    actionIconAttr.setValue(iconVal);
                    actionEl.setAttributeNode(actionIconAttr);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (action.getTextInputPlaceholder() != null) {
                org.w3c.dom.Attr textInputPlaceholderAttr = doc.createAttribute("textInputPlaceholder");
                textInputPlaceholderAttr.setValue(action.getTextInputPlaceholder());
                actionEl.setAttributeNode(textInputPlaceholderAttr);
            }
            if (action.getTextInputButtonText() != null) {
                org.w3c.dom.Attr textInputButtonTextAttr = doc.createAttribute("textInputButtonText");
                textInputButtonTextAttr.setValue(action.getTextInputButtonText());
                actionEl.setAttributeNode(textInputButtonTextAttr);
            }
            categoryEl.appendChild(actionEl);
        }
        root.appendChild(categoryEl);
    }
    try {
        javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
        javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
        javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
        javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
        transformer.transform(source, result);
    } catch (Exception ex) {
        throw new IOException("Failed to save notification categories as XML.", ex);
    }
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) Element(android.renderscript.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) PushActionCategory(com.codename1.push.PushActionCategory) IOException(java.io.IOException) PushAction(com.codename1.push.PushAction) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 9 with Actions

use of com.codename1.rad.ui.Actions in project CodenameOne by codenameone.

the class AndroidImplementation method addActionsToNotification.

/**
 * Adds actions to a push notification.  This is called by the Push broadcast receiver probably before
 * Codename One is initialized
 * @param provider Reference to the app's main class which implements PushActionsProvider
 * @param categoryId The category ID of the push notification.
 * @param builder The builder for the push notification.
 * @param targetIntent The target intent... this should go to the app's main Activity.
 * @param context The current context (inside the Broadcast receiver).
 * @throws IOException
 */
public static void addActionsToNotification(PushActionsProvider provider, String categoryId, NotificationCompat.Builder builder, Intent targetIntent, Context context) throws IOException {
    // NOTE:  THis will likely run when the main activity isn't running so we won't have
    // access to any display properties... just native Android APIs will be accessible.
    PushActionCategory category = null;
    PushActionCategory[] categories;
    if (provider != null) {
        categories = provider.getPushActionCategories();
    } else {
        categories = getInstalledPushActionCategories(context);
    }
    for (PushActionCategory candidateCategory : categories) {
        if (categoryId.equals(candidateCategory.getId())) {
            category = candidateCategory;
            break;
        }
    }
    if (category == null) {
        return;
    }
    int requestCode = 1;
    for (PushAction action : category.getActions()) {
        Intent newIntent = (Intent) targetIntent.clone();
        newIntent.putExtra("pushActionId", action.getId());
        PendingIntent contentIntent = createPendingIntent(context, requestCode++, newIntent);
        try {
            int iconId = 0;
            try {
                iconId = Integer.parseInt(action.getIcon());
            } catch (Exception ex) {
            }
            // android.app.Notification.Action.Builder actionBuilder = new android.app.Notification.Action.Builder(iconId, action.getTitle(), contentIntent);
            System.out.println("Adding action " + action.getId() + ", " + action.getTitle() + ", icon=" + iconId);
            if (ActionWrapper.BuilderWrapper.isSupported()) {
                // We need to take this abstracted "wrapper" approach because the Action.Builder class, and RemoteInput class
                // aren't available until API 22.
                // These classes use reflection to provide support for these classes safely.
                ActionWrapper.BuilderWrapper actionBuilder = new ActionWrapper.BuilderWrapper(iconId, action.getTitle(), contentIntent);
                if (action.getTextInputPlaceholder() != null && RemoteInputWrapper.isSupported()) {
                    RemoteInputWrapper.BuilderWrapper remoteInputBuilder = new RemoteInputWrapper.BuilderWrapper(action.getId() + "$Result");
                    remoteInputBuilder.setLabel(action.getTextInputPlaceholder());
                    RemoteInputWrapper remoteInput = remoteInputBuilder.build();
                    actionBuilder.addRemoteInput(remoteInput);
                }
                ActionWrapper actionWrapper = actionBuilder.build();
                new NotificationCompatWrapper.BuilderWrapper(builder).addAction(actionWrapper);
            } else {
                builder.addAction(iconId, action.getTitle(), contentIntent);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Also used : PushActionCategory(com.codename1.push.PushActionCategory) ActionWrapper(com.codename1.impl.android.compat.app.NotificationCompatWrapper.ActionWrapper) NotificationCompatWrapper(com.codename1.impl.android.compat.app.NotificationCompatWrapper) PushAction(com.codename1.push.PushAction) Paint(android.graphics.Paint) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RemoteInputWrapper(com.codename1.impl.android.compat.app.RemoteInputWrapper)

Example 10 with Actions

use of com.codename1.rad.ui.Actions in project CodenameOne by codenameone.

the class RADActionBoundUIIDSample method start.

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("Toggled Actions Sample", new BorderLayout());
    // Create a tag fo the online status property.
    Tag TAG_ONLINE = new Tag("online");
    // Create an action that will indicte the online/offline status
    ActionNode status = UI.action(// on state of TAG_ONLINE property.
    UI.label(person -> {
        if (person.isFalsey(TAG_ONLINE)) {
            return "Offline";
        } else {
            return "Online";
        }
    }), // Depending on state of TAG_ONLINE property
    UI.uiid(person -> {
        if (person.isFalsey(TAG_ONLINE)) {
            return "LoggedOutStatusButton";
        } else {
            return "LoggedInStatusButton";
        }
    }), // Icon for the action
    UI.icon(FontImage.MATERIAL_PERSON), // define it to always return true so action is always visible.
    UI.condition(person -> {
        return true;
    }));
    // A User entity we use for the models.
    class User extends Entity {
    }
    entityTypeBuilder(User.class).Boolean(TAG_ONLINE).string(Thing.name).factory(cls -> {
        return new User();
    }).build();
    // Create an entity list that will hold several users.
    EntityList el = new EntityList();
    for (int i = 0; i < 200; i++) {
        User u = new User();
        u.set(Thing.name, "User " + i);
        u.set(TAG_ONLINE, i % 2 == 0);
        el.add(u);
    }
    // The ListNode is a wrapper that will be passed to our View so that
    // they can access our action.
    ListNode node = new ListNode(// for each row.
    UI.actions(ProfileListView.ACCOUNT_LIST_ROW_ACTIONS, status));
    // Use a ProfileListView to display all of the users
    // https://shannah.github.io/CodeRAD/javadoc/com/codename1/rad/ui/entityviews/ProfileListView.html
    ProfileListView plv = new ProfileListView(el, node, 8);
    plv.setScrollableY(true);
    // In order to respond to events raised by the action, our view needs to be wrapped
    // in a controller.  Normally our form would have a FormViewController so we could
    // just use FormController, but this sample is compressed to be inside
    // a single method here so we'll create a dedicated ViewController for the list
    ViewController ctrl = new ViewController(null);
    ctrl.setView(plv);
    ctrl.addActionListener(status, evt -> {
        // The action was pressed by the user
        // Update the model's online status
        User u = (User) evt.getEntity();
        u.set(TAG_ONLINE, u.isFalsey(TAG_ONLINE));
    // This will trigger a property change in the model which will update the view.
    });
    hi.add(CENTER, plv);
    hi.show();
}
Also used : ViewNode(com.codename1.rad.nodes.ViewNode) Toolbar(com.codename1.ui.Toolbar) BoxLayout(com.codename1.ui.layouts.BoxLayout) EntityTypeBuilder.entityTypeBuilder(com.codename1.rad.models.EntityTypeBuilder.entityTypeBuilder) Form(com.codename1.ui.Form) NetworkEvent(com.codename1.io.NetworkEvent) ListNode(com.codename1.rad.nodes.ListNode) Display(com.codename1.ui.Display) FontImage(com.codename1.ui.FontImage) Label(com.codename1.ui.Label) CN(com.codename1.ui.CN) ViewController(com.codename1.rad.controllers.ViewController) UI(com.codename1.rad.ui.UI) Entity(com.codename1.rad.models.Entity) Tag(com.codename1.rad.models.Tag) Resources(com.codename1.ui.util.Resources) EntityList(com.codename1.rad.models.EntityList) IOException(java.io.IOException) ActionNode(com.codename1.rad.nodes.ActionNode) Log(com.codename1.io.Log) BorderLayout(com.codename1.ui.layouts.BorderLayout) ProfileListView(com.codename1.rad.ui.entityviews.ProfileListView) UIManager(com.codename1.ui.plaf.UIManager) Dialog(com.codename1.ui.Dialog) Thing(com.codename1.rad.schemas.Thing) EntityListView(com.codename1.rad.ui.entityviews.EntityListView) Entity(com.codename1.rad.models.Entity) BorderLayout(com.codename1.ui.layouts.BorderLayout) Form(com.codename1.ui.Form) ViewController(com.codename1.rad.controllers.ViewController) ActionNode(com.codename1.rad.nodes.ActionNode) EntityList(com.codename1.rad.models.EntityList) ProfileListView(com.codename1.rad.ui.entityviews.ProfileListView) Tag(com.codename1.rad.models.Tag) ListNode(com.codename1.rad.nodes.ListNode)

Aggregations

ActionNode (com.codename1.rad.nodes.ActionNode)6 IOException (java.io.IOException)5 PushAction (com.codename1.push.PushAction)4 PushActionCategory (com.codename1.push.PushActionCategory)4 ViewNode (com.codename1.rad.nodes.ViewNode)4 Container (com.codename1.ui.Container)3 BorderLayout (com.codename1.ui.layouts.BorderLayout)3 GridLayout (com.codename1.ui.layouts.GridLayout)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ParseException (java.text.ParseException)3 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)2 Paint (android.graphics.Paint)2 RemoteException (android.os.RemoteException)2 Element (android.renderscript.Element)2 Log (com.codename1.io.Log)2 NetworkEvent (com.codename1.io.NetworkEvent)2 MediaException (com.codename1.media.AsyncMedia.MediaException)2 ViewController (com.codename1.rad.controllers.ViewController)2 Entity (com.codename1.rad.models.Entity)2 EntityList (com.codename1.rad.models.EntityList)2