Search in sources :

Example 51 with Switch

use of com.codename1.components.Switch in project CodenameOne by codenameone.

the class ResetableTextWatcher method edit.

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

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

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

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

        @Override
        public void run() {
            if (!isEditedFieldSwitch) {
                releaseEdit();
                if (sInstance == null) {
                    sInstance = new InPlaceEditView(impl);
                    impl.relativeLayout.addView(sInstance);
                }
            // Let's try something new here
            // We'll ALWAYS try resize edit mode (since it just works better)
            // But we'll detect whether the field is still covered by the keyboard
            // and switch to pan mode if necessary.
            }
            if (panEditMode) {
                setEditMode(false);
            } else if (resizeEditMode) {
                setEditMode(true);
            } else if (parentForm.isFormBottomPaddingEditingMode()) {
                setEditMode(true);
            } else if (scrollableParent) {
                setEditMode(false);
            } else {
                trySetEditMode(true);
            }
            sInstance.startEditing(impl.getActivity(), textAreaData, initialText, inputType, isEditedFieldSwitch);
        }
    });
    final String[] out = new String[1];
    // In case the contents of the text area are changed while editing is in progress
    // we should propagate the changes to the native text field.
    final DataChangedListener textAreaDataChanged = new DataChangedListener() {

        @Override
        public void dataChanged(int type, int index) {
            if (suppressDataChangedEvent) {
                // https://github.com/codenameone/CodenameOne/issues/3343
                return;
            }
            TextArea currTextArea = getCurrentTextArea();
            if (currTextArea != textArea) {
                // This is not the active text area anymore
                textArea.removeDataChangedListener(this);
                return;
            }
            final String newText = textArea.getText();
            EditView currEditView = getCurrentEditView();
            if (currEditView == null || currEditView.mTextArea != textArea) {
                textArea.removeDataChangedListener(this);
                return;
            }
            String existingText = currEditView.getText().toString();
            // because Objects.equals was not available until API 19
            if (!com.codename1.compat.java.util.Objects.equals(newText, existingText)) {
                impl.getActivity().runOnUiThread(new Runnable() {

                    public void run() {
                        TextArea currTextArea = getCurrentTextArea();
                        EditView currEditView = getCurrentEditView();
                        if (currTextArea != textArea || currEditView == null || currEditView.mTextArea != textArea) {
                            return;
                        }
                        String existingText = currEditView.getText().toString();
                        // because Objects.equals was not available until API 19
                        if (!com.codename1.compat.java.util.Objects.equals(newText, existingText)) {
                            // We need to suppress the Android text change events
                            // to prevent weird things from happening.  E.g. https://github.com/codenameone/CodenameOne/issues/3349
                            suppressTextChangeEvent = true;
                            currEditView.setText(newText);
                            suppressTextChangeEvent = false;
                        }
                    }
                });
            }
        }
    };
    textArea.addDataChangedListener(textAreaDataChanged);
    // In order to reuse the code the runs after edit completion, we will wrap it in a runnable
    // For sync edit mode, we will just run onComplete.run() at the end of this method.  For
    // Async mode we add the Runnable to the textarea as a client property, then run it
    // when editing eventually completes.
    Runnable onComplete = new Runnable() {

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

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

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

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

Example 52 with Switch

use of com.codename1.components.Switch in project CodenameOne by codenameone.

the class AndroidGraphics method drawLabelComponent.

public void drawLabelComponent(int cmpX, int cmpY, int cmpHeight, int cmpWidth, Style style, String text, Bitmap icon, Bitmap stateIcon, int preserveSpaceForState, int gap, boolean rtl, boolean isOppositeSide, int textPosition, int stringWidth, boolean isTickerRunning, int tickerShiftText, boolean endsWith3Points, int valign) {
    int clipX = getClipX();
    int clipY = getClipY();
    int clipW = getClipWidth();
    int clipH = getClipHeight();
    Font cn1Font = style.getFont();
    Object nativeFont = cn1Font.getNativeFont();
    impl.setNativeFont(this, nativeFont);
    setColor(style.getFgColor());
    canvas.save();
    concatenateAlpha(style.getFgAlpha());
    applyTransform();
    int iconWidth = 0;
    int iconHeight = 0;
    if (icon != null) {
        iconWidth = icon.getWidth();
        iconHeight = icon.getHeight();
    }
    int textDecoration = style.getTextDecoration();
    int stateIconSize = 0;
    int stateIconYPosition = 0;
    int leftPadding = style.getPaddingLeft(rtl);
    int rightPadding = style.getPaddingRight(rtl);
    int topPadding = style.getPaddingTop();
    int bottomPadding = style.getPaddingBottom();
    int fontHeight = 0;
    if (text == null) {
        text = "";
    }
    if (text.length() > 0) {
        fontHeight = cn1Font.getHeight();
    }
    if (stateIcon != null) {
        stateIconSize = stateIcon.getWidth();
        stateIconYPosition = cmpY + topPadding + (cmpHeight - topPadding - bottomPadding) / 2 - stateIconSize / 2;
        int tX = cmpX;
        if (isOppositeSide) {
            if (rtl) {
                tX += leftPadding;
            } else {
                tX = tX + cmpWidth - leftPadding - stateIconSize;
            }
            cmpWidth -= leftPadding - stateIconSize;
        } else {
            preserveSpaceForState = stateIconSize + gap;
            if (rtl) {
                tX = tX + cmpWidth - leftPadding - stateIconSize;
            } else {
                tX += leftPadding;
            }
        }
        drawImage(stateIcon, tX, stateIconYPosition);
    }
    // default for bottom left alignment
    int x = cmpX + leftPadding + preserveSpaceForState;
    int y = cmpY + topPadding;
    int align = reverseAlignForBidi(rtl, style.getAlignment());
    int textPos = reverseAlignForBidi(rtl, textPosition);
    // set initial x,y position according to the alignment and textPosition
    switch(align) {
        case Component.LEFT:
            switch(textPos) {
                case Label.LEFT:
                case Label.RIGHT:
                    y = y + (cmpHeight - (topPadding + bottomPadding + Math.max(((icon != null) ? iconHeight : 0), fontHeight))) / 2;
                    break;
                case Label.BOTTOM:
                case Label.TOP:
                    y = y + (cmpHeight - (topPadding + bottomPadding + ((icon != null) ? iconHeight + gap : 0) + fontHeight)) / 2;
                    break;
            }
            break;
        case Component.CENTER:
            switch(textPos) {
                case Label.LEFT:
                case Label.RIGHT:
                    x = x + (cmpWidth - (preserveSpaceForState + leftPadding + rightPadding + ((icon != null) ? iconWidth + gap : 0) + stringWidth)) / 2;
                    x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
                    y = y + (cmpHeight - (topPadding + bottomPadding + Math.max(((icon != null) ? iconHeight : 0), fontHeight))) / 2;
                    break;
                case Label.BOTTOM:
                case Label.TOP:
                    x = x + (cmpWidth - (preserveSpaceForState + leftPadding + rightPadding + Math.max(((icon != null) ? iconWidth + gap : 0), stringWidth))) / 2;
                    x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
                    y = y + (cmpHeight - (topPadding + bottomPadding + ((icon != null) ? iconHeight + gap : 0) + fontHeight)) / 2;
                    break;
            }
            break;
        case Component.RIGHT:
            switch(textPos) {
                case Label.LEFT:
                case Label.RIGHT:
                    x = cmpX + cmpWidth - rightPadding - (((icon != null) ? (iconWidth + gap) : 0) + stringWidth);
                    if (rtl) {
                        x = Math.max(x - preserveSpaceForState, cmpX + leftPadding);
                    } else {
                        x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
                    }
                    y = y + (cmpHeight - (topPadding + bottomPadding + Math.max(((icon != null) ? iconHeight : 0), fontHeight))) / 2;
                    break;
                case Label.BOTTOM:
                case Label.TOP:
                    x = cmpX + cmpWidth - rightPadding - (Math.max(((icon != null) ? (iconWidth) : 0), stringWidth));
                    x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
                    y = y + (cmpHeight - (topPadding + bottomPadding + ((icon != null) ? iconHeight + gap : 0) + fontHeight)) / 2;
                    break;
            }
            break;
        default:
            break;
    }
    int textSpaceW = cmpWidth - rightPadding - leftPadding;
    if (icon != null && (textPos == Label.RIGHT || textPos == Label.LEFT)) {
        textSpaceW = textSpaceW - iconWidth;
    }
    if (stateIcon != null) {
        textSpaceW = textSpaceW - stateIconSize;
    } else {
        textSpaceW = textSpaceW - preserveSpaceForState;
    }
    if (icon == null) {
        // no icon only string
        drawLabelString(nativeFont, text, x, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, stringWidth, fontHeight);
    } else {
        int strWidth = stringWidth;
        int iconStringWGap;
        int iconStringHGap;
        switch(textPos) {
            case Label.LEFT:
                if (iconHeight > fontHeight) {
                    iconStringHGap = (iconHeight - fontHeight) / 2;
                    strWidth = drawLabelStringValign(nativeFont, text, x, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, strWidth, iconStringHGap, iconHeight, fontHeight, valign);
                    drawImage(icon, x + strWidth + gap, y);
                } else {
                    iconStringHGap = (fontHeight - iconHeight) / 2;
                    strWidth = drawLabelString(nativeFont, text, x, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, strWidth, fontHeight);
                    drawImage(icon, x + strWidth + gap, y + iconStringHGap);
                }
                break;
            case Label.RIGHT:
                if (iconHeight > fontHeight) {
                    iconStringHGap = (iconHeight - fontHeight) / 2;
                    drawImage(icon, x, y);
                    drawLabelStringValign(nativeFont, text, x + iconWidth + gap, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, iconWidth, iconStringHGap, iconHeight, fontHeight, valign);
                } else {
                    iconStringHGap = (fontHeight - iconHeight) / 2;
                    drawImage(icon, x, y + iconStringHGap);
                    drawLabelString(nativeFont, text, x + iconWidth + gap, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, iconWidth, fontHeight);
                }
                break;
            case Label.BOTTOM:
                // center align the smaller
                if (iconWidth > strWidth) {
                    iconStringWGap = (iconWidth - strWidth) / 2;
                    drawImage(icon, x, y);
                    drawLabelString(nativeFont, text, x + iconStringWGap, y + iconHeight + gap, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, iconWidth, fontHeight);
                } else {
                    iconStringWGap = (Math.min(strWidth, textSpaceW) - iconWidth) / 2;
                    drawImage(icon, x + iconStringWGap, y);
                    drawLabelString(nativeFont, text, x, y + iconHeight + gap, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, iconWidth, fontHeight);
                }
                break;
            case Label.TOP:
                // center align the smaller
                if (iconWidth > strWidth) {
                    iconStringWGap = (iconWidth - strWidth) / 2;
                    drawLabelString(nativeFont, text, x + iconStringWGap, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, iconWidth, fontHeight);
                    drawImage(icon, x, y + fontHeight + gap);
                } else {
                    iconStringWGap = (Math.min(strWidth, textSpaceW) - iconWidth) / 2;
                    drawLabelString(nativeFont, text, x, y, textSpaceW, isTickerRunning, tickerShiftText, textDecoration, rtl, endsWith3Points, iconWidth, fontHeight);
                    drawImage(icon, x + iconStringWGap, y + fontHeight + gap);
                }
                break;
        }
    }
    unapplyTransform();
    canvas.restore();
    setClip(clipX, clipY, clipW, clipH);
}
Also used : Font(com.codename1.ui.Font)

Example 53 with Switch

use of com.codename1.components.Switch in project CodenameOne by codenameone.

the class IOSImplementation method updateNativeTextEditorFrame.

private static void updateNativeTextEditorFrame() {
    if (instance.currentEditing != null) {
        TextArea cmp = instance.currentEditing;
        final Style stl = cmp.getStyle();
        final boolean rtl = UIManager.getInstance().getLookAndFeel().isRTL();
        instance.doNotHideTextEditorSemaphore++;
        try {
            instance.currentEditing.requestFocus();
        } finally {
            instance.doNotHideTextEditorSemaphore--;
        }
        int x = cmp.getAbsoluteX() + cmp.getScrollX();
        int y = cmp.getAbsoluteY() + cmp.getScrollY();
        int w = cmp.getWidth();
        int h = cmp.getHeight();
        int pt = stl.getPaddingTop();
        int pb = stl.getPaddingBottom();
        int pl = stl.getPaddingLeft(rtl);
        int pr = stl.getPaddingRight(rtl);
        /*
            if(cmp.isSingleLineTextArea()) {
                switch(cmp.getVerticalAlignment()) {
                    case TextArea.CENTER:
                        if(h > cmp.getPreferredH()) {
                            y += (h / 2 - cmp.getPreferredH() / 2);
                        }
                        break;
                    case TextArea.BOTTOM:
                        if(h > cmp.getPreferredH()) {
                            y += (h - cmp.getPreferredH());
                        }
                        break;
                }
            }
            */
        int maxH = Display.getInstance().getDisplayHeight() - nativeInstance.getVKBHeight();
        if (h > maxH) {
            // For text areas, we don't want the keyboard to cover part of the
            // typing region.  So we will try to size the component to
            // to only go up to the top edge of the keyboard
            // that should allow the OS to enable scrolling properly.... at least
            // in theory.
            h = maxH;
        }
        nativeInstance.resizeNativeTextView(x, y, w, h, pt, pr, pb, pl);
    }
}
Also used : TextArea(com.codename1.ui.TextArea) Style(com.codename1.ui.plaf.Style)

Example 54 with Switch

use of com.codename1.components.Switch 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 55 with Switch

use of com.codename1.components.Switch in project CodenameOne by codenameone.

the class EditableResources method save.

/**
 * Allows us to store a modified resource file
 */
public void save(OutputStream out) throws IOException {
    if (overrideFile != null) {
        overrideResource.save(new FileOutputStream(overrideFile));
    }
    // disable override for the duration of the save so stuff from the override doesn't
    // get into the main resource file
    File overrideFileBackup = overrideFile;
    EditableResources overrideResourceBackup = overrideResource;
    overrideResource = null;
    overrideFile = null;
    try {
        DataOutputStream output = new DataOutputStream(out);
        String[] resourceNames = getResourceNames();
        keyOffset = 0;
        if (currentPassword != null) {
            output.writeShort(resourceNames.length + 2);
            output.writeByte(MAGIC_PASSWORD);
            output.writeUTF("" + ((char) encode('l')) + ((char) encode('w')));
            output.writeByte(encode(MAGIC_HEADER & 0xff));
        } else {
            output.writeShort(resourceNames.length + 1);
            // write the header of the resource file
            output.writeByte(MAGIC_HEADER);
        }
        output.writeUTF("");
        // the size of the header
        output.writeShort(6);
        output.writeShort(MAJOR_VERSION);
        output.writeShort(MINOR_VERSION);
        // currently resource file meta-data isn't supported
        output.writeShort(0);
        for (int iter = 0; iter < resourceNames.length; iter++) {
            // write the magic number
            byte magic = getResourceType(resourceNames[iter]);
            switch(magic) {
                case MAGIC_TIMELINE:
                case MAGIC_ANIMATION_LEGACY:
                case MAGIC_IMAGE_LEGACY:
                case MAGIC_INDEXED_IMAGE_LEGACY:
                    magic = MAGIC_IMAGE;
                    break;
                case MAGIC_THEME_LEGACY:
                    magic = MAGIC_THEME;
                    break;
                case MAGIC_FONT_LEGACY:
                    magic = MAGIC_FONT;
                    break;
            }
            if (currentPassword != null) {
                output.writeByte(encode(magic & 0xff));
                char[] chars = resourceNames[iter].toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    chars[i] = (char) encode(chars[i] & 0xffff);
                }
                output.writeUTF(new String(chars));
            } else {
                output.writeByte(magic);
                output.writeUTF(resourceNames[iter]);
            }
            switch(magic) {
                case MAGIC_IMAGE:
                    Object o = getResourceObject(resourceNames[iter]);
                    if (!(o instanceof MultiImage)) {
                        o = null;
                    }
                    saveImage(output, getImage(resourceNames[iter]), (MultiImage) o, BufferedImage.TYPE_INT_ARGB);
                    continue;
                case MAGIC_THEME:
                    saveTheme(output, getTheme(resourceNames[iter]), magic == MAGIC_THEME_LEGACY);
                    continue;
                case MAGIC_FONT:
                    saveFont(output, false, resourceNames[iter]);
                    continue;
                case MAGIC_DATA:
                    {
                        InputStream i = getData(resourceNames[iter]);
                        ByteArrayOutputStream outArray = new ByteArrayOutputStream();
                        int val = i.read();
                        while (val != -1) {
                            outArray.write(val);
                            val = i.read();
                        }
                        byte[] data = outArray.toByteArray();
                        output.writeInt(data.length);
                        output.write(data);
                        continue;
                    }
                case MAGIC_UI:
                    {
                        InputStream i = getUi(resourceNames[iter]);
                        ByteArrayOutputStream outArray = new ByteArrayOutputStream();
                        int val = i.read();
                        while (val != -1) {
                            outArray.write(val);
                            val = i.read();
                        }
                        byte[] data = outArray.toByteArray();
                        output.writeInt(data.length);
                        output.write(data);
                        continue;
                    }
                case MAGIC_L10N:
                    // we are getting the theme which allows us to acces the l10n data
                    saveL10N(output, getTheme(resourceNames[iter]));
                    continue;
                default:
                    throw new IOException("Corrupt theme file unrecognized magic number: " + Integer.toHexString(magic & 0xff));
            }
        }
        modified = false;
        updateModified();
        undoQueue.clear();
        redoQueue.clear();
    } finally {
        overrideFile = overrideFileBackup;
        overrideResource = overrideResourceBackup;
    }
}
Also used : DataOutputStream(java.io.DataOutputStream) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) AnimationObject(com.codename1.ui.animations.AnimationObject) File(java.io.File)

Aggregations

Component (com.codename1.ui.Component)19 Font (com.codename1.ui.Font)18 Container (com.codename1.ui.Container)15 Form (com.codename1.ui.Form)14 Style (com.codename1.ui.plaf.Style)12 Button (com.codename1.ui.Button)11 Image (com.codename1.ui.Image)11 TextArea (com.codename1.ui.TextArea)11 ArrayList (java.util.ArrayList)11 File (java.io.File)10 IOException (java.io.IOException)10 Hashtable (java.util.Hashtable)10 BorderLayout (com.codename1.ui.layouts.BorderLayout)9 Label (com.codename1.ui.Label)8 FileInputStream (java.io.FileInputStream)8 ActionListener (com.codename1.ui.events.ActionListener)7 TextField (com.codename1.ui.TextField)6 ActionEvent (com.codename1.ui.events.ActionEvent)6 BoxLayout (com.codename1.ui.layouts.BoxLayout)6 EncodedImage (com.codename1.ui.EncodedImage)5