Search in sources :

Example 26 with Theme

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

the class SignIn method start.

public void start() {
    // new SignInFormGB(theme).show();
    // if (true) return;
    loginForm = new Form("Sign in Demo");
    loginForm.setLayout(new BorderLayout());
    Container center = new Container(new BoxLayout(BoxLayout.Y_AXIS));
    center.setUIID("ContainerWithPadding");
    Image logo = theme.getImage("CodenameOne.png");
    Label l = new Label(logo);
    Container flow = new Container(new FlowLayout(Component.CENTER));
    flow.addComponent(l);
    center.addComponent(flow);
    final TextField username = new TextField();
    username.setHint("Username");
    final TextField pass = new TextField();
    pass.setHint("Password");
    pass.setConstraint(TextField.PASSWORD);
    center.addComponent(username);
    center.addComponent(pass);
    Button signIn = new Button("Sign In");
    signIn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            if (username.getText().length() == 0 || pass.getText().length() == 0) {
                return;
            }
            UserForm userForm = new UserForm(username.getText(), (EncodedImage) theme.getImage("user.png"), null);
            userForm.show();
        }
    });
    center.addComponent(signIn);
    loginForm.addComponent(BorderLayout.CENTER, center);
    Container bottom = new Container(new BoxLayout(BoxLayout.Y_AXIS));
    Button loginWFace = new Button(theme.getImage("signin_facebook.png"));
    loginWFace.setUIID("LoginButton");
    loginWFace.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            // create your own app identity on facebook follow the guide here:
            // facebook-login.html
            String clientId = "1171134366245722";
            String redirectURI = "http://www.codenameone.com/";
            String clientSecret = "";
            if (clientSecret.length() == 0) {
                System.err.println("create your own facebook app follow the guide here:");
                System.err.println("http://www.codenameone.com/facebook-login.html");
                return;
            }
            Login fb = FacebookConnect.getInstance();
            fb.setClientId(clientId);
            fb.setRedirectURI(redirectURI);
            fb.setClientSecret(clientSecret);
            login = fb;
            fb.setCallback(new LoginListener(LoginListener.FACEBOOK));
            if (!fb.isUserLoggedIn()) {
                fb.doLogin();
            } else {
                showFacebookUser(fb.getAccessToken().getToken());
            }
        }
    });
    Button loginWG = new Button(theme.getImage("signin_google.png"));
    loginWG.setUIID("LoginButton");
    loginWG.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            SignIn.this.doFirebase();
            // create your own google project follow the guide here:
            // http://www.codenameone.com/google-login.html
            String clientId = "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com";
            String redirectURI = "https://www.codenameone.com/oauth2callback";
            String clientSecret = "650YqplrnAI0KXb9LMUnVNnx";
            if (clientSecret.length() == 0) {
                System.err.println("create your own google project follow the guide here:");
                System.err.println("http://www.codenameone.com/google-login.html");
                return;
            }
            Login gc = GoogleConnect.getInstance();
            gc.setClientId(clientId);
            gc.setRedirectURI(redirectURI);
            gc.setClientSecret(clientSecret);
            gc.setScope("https://www.googleapis.com/auth/plus.profile.emails.read https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file");
            login = gc;
            gc.setCallback(new LoginListener(LoginListener.GOOGLE));
            if (!gc.isUserLoggedIn()) {
                gc.doLogin();
            } else {
                showGoogleUser(gc.getAccessToken().getToken());
            }
        }
    });
    bottom.addComponent(loginWFace);
    bottom.addComponent(loginWG);
    loginForm.addComponent(BorderLayout.SOUTH, bottom);
    loginForm.show();
}
Also used : FlowLayout(com.codename1.ui.layouts.FlowLayout) Form(com.codename1.ui.Form) ActionEvent(com.codename1.ui.events.ActionEvent) BoxLayout(com.codename1.ui.layouts.BoxLayout) Label(com.codename1.ui.Label) Login(com.codename1.social.Login) EncodedImage(com.codename1.ui.EncodedImage) Image(com.codename1.ui.Image) EncodedImage(com.codename1.ui.EncodedImage) Container(com.codename1.ui.Container) BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) Button(com.codename1.ui.Button) TextField(com.codename1.ui.TextField)

Example 27 with Theme

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

the class CSSEngine method applyStyleToUIElement.

// //////
// CSS2 additions end
// /////
/**
 * Applies the given CSS directives to the component
 *
 * @param ui The component representing (part of) the element that the style should be applied to
 * @param selector The style attributes relating to this element
 * @param element The element the style should be applied to
 * @param htmlC The HTMLComponent to which this element belongs to
 * @param focus true if the style should be applied only to the selected state iof the ui (a result of pseudo-class selector a:focus etc.)
 */
private void applyStyleToUIElement(Component ui, CSSElement selector, HTMLElement element, HTMLComponent htmlC) {
    // count++;
    // This is relevant only for non recursive types - otherwise we need to recheck everytime since it depends on the specific UI component class
    int styles = getApplicableStyles(ui, selector);
    // White spaces
    if (HTMLComponent.FIXED_WIDTH) {
        // This works well only in fixed width mode (Since we cannot "force" a newline in FlowLayout)
        // TODO - enable in FIXED_WIDTH for pre vs. normal/nowrap
        int space = selector.getAttrVal(CSSElement.CSS_WHITE_SPACE);
        if (space != -1) {
            switch(space) {
                case WHITE_SPACE_NORMAL:
                    setWrapRecursive(element, htmlC);
                    break;
                case WHITE_SPACE_NOWRAP:
                    setNowrapRecursive(element);
                    break;
                case WHITE_SPACE_PRE:
                    // TODO - Not implemented yet
                    break;
            }
        }
    }
    // Input format
    String v = selector.getAttributeById(CSSElement.CSS_WAP_INPUT_FORMAT);
    if ((v != null) && ((element.getTagId() == HTMLElement.TAG_TEXTAREA) || (element.getTagId() == HTMLElement.TAG_INPUT)) && (ui instanceof TextArea)) {
        v = omitQuotesIfExist(v);
        // This may return a new instance of TextField taht has to be updated in the tree. This is alos the reason why input format is the first thing checked - see HTMLInputFormat.applyConstraints
        ui = htmlC.setInputFormat((TextArea) ui, v);
        element.setAssociatedComponents(ui);
    }
    // Input emptyOK
    int inputRequired = selector.getAttrVal(CSSElement.CSS_WAP_INPUT_REQUIRED);
    if ((inputRequired != -1) && ((element.getTagId() == HTMLElement.TAG_TEXTAREA) || (element.getTagId() == HTMLElement.TAG_INPUT)) && (ui instanceof TextArea)) {
        if (inputRequired == INPUT_REQUIRED_TRUE) {
            htmlC.setInputRequired(((TextArea) ui), true);
        } else if (inputRequired == INPUT_REQUIRED_FALSE) {
            htmlC.setInputRequired(((TextArea) ui), false);
        }
    }
    // Display
    int disp = selector.getAttrVal(CSSElement.CSS_DISPLAY);
    switch(disp) {
        case DISPLAY_NONE:
            if (ui.getParent() != null) {
                ui.getParent().removeComponent(ui);
            } else {
                // special case for display in the BODY tag
                if (ui instanceof Container) {
                    ((Container) ui).removeAll();
                }
            }
            return;
        case // Animate component (ticker-like)
        DISPLAY_MARQUEE:
            htmlC.marqueeComponents.addElement(ui);
            break;
    }
    // Visibility
    int visibility = selector.getAttrVal(CSSElement.CSS_VISIBILITY);
    if (visibility != -1) {
        boolean visible = (visibility == VISIBILITY_VISIBLE);
        setVisibleRecursive(ui, visible);
        if (!visible) {
            // Don't waste time on processing hidden elements, though technically the size of the element is still reserved and should be according to style
            return;
        } else {
            // Need to turn on visibility of all component's parents, in case they were declared hidden
            setParentsVisible(ui);
        }
    }
    // 
    // Dimensions
    // 
    // TODO - debug: Width and Height don't always work - for simple components they usually do, but for containers either they don't have any effect or some inner components (with size restrictions) disappear
    // We use the entire display width and height as reference since htmlC still doesn't have a preferred size or actual size
    // Width
    // TODO - Width/Height is disabled currently, since it causes a lot of side effects, making some components disappear
    /*
        int width=selector.getAttrLengthVal(CSSElement.CSS_WIDTH,ui,Display.getInstance().getDisplayWidth());

        // Height
        int height=selector.getAttrLengthVal(CSSElement.CSS_HEIGHT,ui,Display.getInstance().getDisplayHeight());

        if (!HTMLComponent.PROCESS_HTML_MP1_ONLY) {
            int minWidth=selector.getAttrLengthVal(CSSElement.CSS_MIN_WIDTH,ui,Display.getInstance().getDisplayWidth());
            int maxWidth=selector.getAttrLengthVal(CSSElement.CSS_MAX_WIDTH,ui,Display.getInstance().getDisplayWidth());
            int minHeight=selector.getAttrLengthVal(CSSElement.CSS_MIN_HEIGHT,ui,Display.getInstance().getDisplayHeight());
            int maxHeight=selector.getAttrLengthVal(CSSElement.CSS_MAX_HEIGHT,ui,Display.getInstance().getDisplayHeight());

            if (width==-1) { // process min/max only if exact was not specified
                if ((minWidth!=-1) && (minWidth>ui.getPreferredW())) {
                    width=minWidth;
                }
                if ((maxWidth!=-1) && (maxWidth<ui.getPreferredW())) {
                    width=maxWidth;
                }
            }
            if (height==-1) { // process min/max only if exact was not specified
                if ((minHeight!=-1) && (minHeight>ui.getPreferredH())) {
                    height=minHeight;
                }
                if ((maxHeight!=-1) && (maxHeight<ui.getPreferredH())) {
                    height=maxHeight;
                }
            }
        }

        if ((width!=-1) || (height!=-1)) {
            if (width==-1) {
                width=ui.getPreferredW();
            }
            if (height==-1) {
                height=ui.getPreferredH();
            }
            ui.setPreferredSize(new Dimension(width,height));
        }
        */
    // 
    // Colors
    // 
    // Background Color
    int bgColor = selector.getAttrVal(CSSElement.CSS_BACKGROUND_COLOR);
    if (bgColor != -1) {
        if ((styles & STYLE_UNSELECTED) != 0) {
            ui.getUnselectedStyle().setBgColor(bgColor);
            ui.getUnselectedStyle().setBgTransparency(255);
        }
        if ((styles & STYLE_SELECTED) != 0) {
            ui.getSelectedStyle().setBgColor(bgColor);
            ui.getSelectedStyle().setBgTransparency(255);
        }
        if ((styles & STYLE_PRESSED) != 0) {
            ((HTMLLink) ui).getPressedStyle().setBgColor(bgColor);
            ((HTMLLink) ui).getPressedStyle().setBgTransparency(255);
        }
    }
    // Foreground color
    int fgColor = selector.getAttrVal(CSSElement.CSS_COLOR);
    if (fgColor != -1) {
        setColorRecursive(ui, fgColor, selector);
    }
    // Background Image
    v = selector.getAttributeById(CSSElement.CSS_BACKGROUND_IMAGE);
    if (v != null) {
        String url = getCSSUrl(v);
        if (url != null) {
            // Setting an alternative bgPainter that can support CSS background properties
            CSSBgPainter bgPainter = new CSSBgPainter(ui);
            // Background tiling
            byte bgType = (byte) selector.getAttrVal(CSSElement.CSS_BACKGROUND_REPEAT);
            if (bgType == -1) {
                // default value
                bgType = Style.BACKGROUND_IMAGE_TILE_BOTH;
            }
            // Note that we don't set transparency to 255, since the image may have its own transparency/opaque areas - we don't want to block the entire component/container entirely
            if ((styles & STYLE_SELECTED) != 0) {
                ui.getSelectedStyle().setBgPainter(bgPainter);
                ui.getSelectedStyle().setBackgroundType(bgType);
            }
            if ((styles & STYLE_UNSELECTED) != 0) {
                ui.getUnselectedStyle().setBgPainter(bgPainter);
                ui.getUnselectedStyle().setBackgroundType(bgType);
            }
            if ((styles & STYLE_PRESSED) != 0) {
                ((HTMLLink) ui).getPressedStyle().setBgPainter(bgPainter);
                ((HTMLLink) ui).getPressedStyle().setBackgroundType(bgType);
            }
            // The background image itself
            if (htmlC.showImages) {
                if (htmlC.getDocumentInfo() != null) {
                    htmlC.getThreadQueue().addBgImage(ui, htmlC.convertURL(url), styles);
                } else {
                    if (DocumentInfo.isAbsoluteURL(url)) {
                        htmlC.getThreadQueue().addBgImage(ui, url, styles);
                    } else {
                        if (htmlC.getHTMLCallback() != null) {
                            htmlC.getHTMLCallback().parsingError(HTMLCallback.ERROR_NO_BASE_URL, selector.getTagName(), selector.getAttributeName(new Integer(CSSElement.CSS_BACKGROUND_IMAGE)), url, "Ignoring background image file referred in a CSS file/segment (" + url + "), since page was set by setBody/setHTML/setDOM so there's no way to access relative URLs");
                        }
                    }
                }
            }
            for (int i = CSSElement.CSS_BACKGROUND_POSITION_X; i <= CSSElement.CSS_BACKGROUND_POSITION_Y; i++) {
                int pos = selector.getAttrVal(i);
                if (pos != -1) {
                    bgPainter.setPosition(i, pos);
                }
            }
            // or 'scroll' (default) which means the it moves with scrolling (Like usually in CodenameOne backgrounds)
            if (selector.getAttrVal((CSSElement.CSS_BACKGROUND_ATTACHMENT)) == BG_ATTACHMENT_FIXED) {
                bgPainter.setFixed();
            }
        }
    }
    // TODO - float: none/left/right
    // TODO - clear: none/left/right/both
    // Margin
    Component marginComp = ui;
    if (ui instanceof Label) {
        // If this is a Label/HTMLLink we do not apply the margin individually to each word, but rather to the whole block
        marginComp = ui.getParent();
    } else if ((element.getTagId() == HTMLElement.TAG_LI) && (ui.getParent().getLayout() instanceof BorderLayout)) {
        marginComp = ui.getParent();
    }
    for (int i = CSSElement.CSS_MARGIN_TOP; i <= CSSElement.CSS_MARGIN_RIGHT; i++) {
        int marginPixels = -1;
        if ((i == CSSElement.CSS_MARGIN_TOP) || (i == CSSElement.CSS_MARGIN_BOTTOM)) {
            // Here the used component is ui and not marginComp, since we're interested in the font size (which will be corrent in Labels not in their containers)
            marginPixels = selector.getAttrLengthVal(i, ui, htmlC.getHeight());
        } else {
            marginPixels = selector.getAttrLengthVal(i, ui, htmlC.getWidth());
        }
        if (marginPixels >= 0 && marginComp != null) {
            if ((styles & STYLE_SELECTED) != 0) {
                marginComp.getSelectedStyle().setMargin(i - CSSElement.CSS_MARGIN_TOP, marginPixels);
                // parent when the link focuses
                if ((ui instanceof HTMLLink) && (styles == STYLE_SELECTED)) {
                    ((HTMLLink) ui).setParentChangesOnFocus();
                }
            }
            if ((styles & STYLE_UNSELECTED) != 0) {
                marginComp.getUnselectedStyle().setMargin(i - CSSElement.CSS_MARGIN_TOP, marginPixels);
            }
        // Since we don't apply the margin/padding on the component but rather on its parent
        // There is no point in setting the PRESSED style since we don't have a pressed event from Button, nor do we have a pressedStyle for containers
        // That's why we can't do the same trick as in selected style, and the benefit of this rather "edge" case (That is anyway not implemented in all browsers) seems rather small
        // if ((styles & STYLE_PRESSED)!=0) {
        // ((HTMLLink)ui).getPressedStyle().setMargin(i-CSSElement.CSS_MARGIN_TOP, marginPixels);
        // }
        }
    }
    Component padComp = ui;
    if (ui instanceof Label) {
        padComp = ui.getParent();
    } else if ((element.getTagId() == HTMLElement.TAG_LI) && (ui.getParent().getLayout() instanceof BorderLayout)) {
        padComp = ui.getParent();
    }
    for (int i = CSSElement.CSS_PADDING_TOP; i <= CSSElement.CSS_PADDING_RIGHT; i++) {
        int padPixels = -1;
        if ((i == CSSElement.CSS_PADDING_TOP) || (i == CSSElement.CSS_PADDING_BOTTOM)) {
            padPixels = selector.getAttrLengthVal(i, ui, htmlC.getHeight());
        } else {
            padPixels = selector.getAttrLengthVal(i, ui, htmlC.getWidth());
        }
        if (padPixels >= 0) {
            // Only positive or 0
            if ((styles & STYLE_SELECTED) != 0) {
                if (padComp != null) {
                    padComp.getSelectedStyle().setPadding(i - CSSElement.CSS_PADDING_TOP, padPixels);
                }
                if ((ui instanceof HTMLLink) && (styles == STYLE_SELECTED)) {
                    // See comment on margins
                    ((HTMLLink) ui).setParentChangesOnFocus();
                }
            }
            if ((styles & STYLE_UNSELECTED) != 0) {
                if (padComp != null) {
                    padComp.getUnselectedStyle().setPadding(i - CSSElement.CSS_PADDING_TOP, padPixels);
                }
            }
        // See comment in margin on why PRESSED was dropped
        // if ((styles & STYLE_PRESSED)!=0) {
        // ((HTMLLink)padComp).getPressedStyle().setPadding(i-CSSElement.CSS_PADDING_TOP, padPixels);
        // }
        }
    }
    // 
    // Text
    // 
    // Text Alignment
    int align = selector.getAttrVal(CSSElement.CSS_TEXT_ALIGN);
    if (align != -1) {
        switch(element.getTagId()) {
            case HTMLElement.TAG_TD:
            case HTMLElement.TAG_TH:
                setTableCellAlignment(element, ui, align, true);
                break;
            case HTMLElement.TAG_TR:
                setTableCellAlignmentTR(element, ui, align, true);
                break;
            case HTMLElement.TAG_TABLE:
                setTableAlignment(ui, align, true);
                break;
            default:
                // TODO - this sometimes may collide with the HTML align attribute. If the style of the same tag has alignment it overrides the align attribute, but if it is inherited, the align tag prevails
                setTextAlignmentRecursive(ui, align);
        }
    }
    // Vertical align
    int valign = selector.getAttrVal(CSSElement.CSS_VERTICAL_ALIGN);
    if (valign != -1) {
        switch(element.getTagId()) {
            case HTMLElement.TAG_TD:
            case HTMLElement.TAG_TH:
                setTableCellAlignment(element, ui, valign, false);
                break;
            case HTMLElement.TAG_TR:
                setTableCellAlignmentTR(element, ui, valign, false);
                break;
            // break;
            default:
        }
    }
    // Text Transform
    int transform = selector.getAttrVal(CSSElement.CSS_TEXT_TRANSFORM);
    if (transform != -1) {
        setTextTransformRecursive(ui, transform);
    }
    // Text indentation
    int indent = selector.getAttrLengthVal(CSSElement.CSS_TEXT_INDENT, ui, htmlC.getWidth());
    if (indent >= 0) {
        // Only positive (0 also as it may cancel previous margins)
        setTextIndentationRecursive(ui, indent);
    }
    // 
    // Font
    // 
    // Font family
    String fontFamily = selector.getAttributeById(CSSElement.CSS_FONT_FAMILY);
    if (fontFamily != null) {
        int index = fontFamily.indexOf(',');
        if (index != -1) {
            // Currently we ignore font families fall back (i.e. Arial,Helvetica,Sans-serif) since even finding a match for one font is quite expensive performance-wise
            fontFamily = fontFamily.substring(0, index);
        }
    }
    // Font Style
    int fontStyle = selector.getAttrVal(CSSElement.CSS_FONT_STYLE);
    // Font Weight
    int fontWeight = selector.getAttrVal(CSSElement.CSS_FONT_WEIGHT);
    int fontSize = selector.getAttrLengthVal(CSSElement.CSS_FONT_SIZE, ui, ui.getStyle().getFont().getHeight());
    if (fontSize < -1) {
        int curSize = ui.getStyle().getFont().getHeight();
        if (fontSize == CSSElement.FONT_SIZE_LARGER) {
            fontSize = curSize + 2;
        } else if (fontSize == CSSElement.FONT_SIZE_SMALLER) {
            fontSize = curSize - 2;
        }
    }
    // Since J2ME doesn't support small-caps fonts, when a small-caps font varinat is requested
    // the font-family is changed to "smallcaps" which should be loaded to HTMLComponent and the theme as a bitmap font
    // If no smallcaps font is found at all, then the family stays the same, but if even only one is found - the best match will be used.
    int fontVariant = selector.getAttrVal(CSSElement.CSS_FONT_VARIANT);
    if ((fontVariant == FONT_VARIANT_SMALLCAPS) && (htmlC.isSmallCapsFontAvailable())) {
        fontFamily = CSSElement.SMALL_CAPS_STRING;
    }
    // Process font only if once of the font CSS properties was mentioned and valid
    if ((fontFamily != null) || (fontSize != -1) || (fontStyle != -1) || (fontWeight != -1)) {
        setFontRecursive(htmlC, ui, fontFamily, fontSize, fontStyle, fontWeight, selector);
    }
    // List style
    int listType = -1;
    String listImg = null;
    Component borderUi = ui;
    if ((element.getTagId() == HTMLElement.TAG_LI) || (element.getTagId() == HTMLElement.TAG_UL) || (element.getTagId() == HTMLElement.TAG_OL) || (element.getTagId() == HTMLElement.TAG_DIR) || (element.getTagId() == HTMLElement.TAG_MENU)) {
        int listPos = selector.getAttrVal(CSSElement.CSS_LIST_STYLE_POSITION);
        if (listPos == LIST_STYLE_POSITION_INSIDE) {
            // Padding and not margin since background color should affect also the indented space
            ui.getStyle().setPadding(Component.LEFT, ui.getStyle().getMargin(Component.LEFT) + INDENT_LIST_STYLE_POSITION);
            Container parent = ui.getParent();
            if (parent.getLayout() instanceof BorderLayout) {
                borderUi = parent;
            }
        }
        listType = selector.getAttrVal(CSSElement.CSS_LIST_STYLE_TYPE);
        listImg = getCSSUrl(selector.getAttributeById(CSSElement.CSS_LIST_STYLE_IMAGE));
    }
    // Border
    Border[] borders = new Border[4];
    // Used to prevent drawing a border in the middle of two words in the same segment
    boolean leftBorder = false;
    // Used to prevent drawing a border in the middle of two words in the same segment
    boolean rightBorder = false;
    boolean hasBorder = false;
    if ((borderUi == ui) && (element.getUi().size() > 1)) {
        if (element.getUi().firstElement() == borderUi) {
            leftBorder = true;
        } else if (element.getUi().lastElement() == borderUi) {
            rightBorder = true;
        }
    } else {
        leftBorder = true;
        rightBorder = true;
    }
    for (int i = Component.TOP; i <= Component.RIGHT; i++) {
        if ((i == Component.BOTTOM) || (i == Component.TOP) || ((i == Component.LEFT) && (leftBorder)) || ((i == Component.RIGHT) && (rightBorder))) {
            borders[i] = createBorder(selector, borderUi, i, styles, BORDER);
            if (borders[i] != null) {
                hasBorder = true;
            }
        }
    }
    if (hasBorder) {
        Border curBorder = borderUi.getUnselectedStyle().getBorder();
        if (((styles & STYLE_SELECTED) != 0) && ((styles & STYLE_UNSELECTED) == 0)) {
            curBorder = borderUi.getSelectedStyle().getBorder();
        }
        if ((styles & STYLE_PRESSED) != 0) {
            curBorder = ((HTMLLink) borderUi).getSelectedStyle().getBorder();
        }
        // In case this element was assigned a top border for instance, and then by belonging to another tag/class/id it has also a bottom border - this merges the two (and gives priority to the new one)
        if ((curBorder != null) && (curBorder.getCompoundBorders() != null)) {
            // TODO - This doesn't cover the case of having another border (i.e. table/fieldset?) - Can also assign the non-CSS border to the other corners?
            // curBorder.
            Border[] oldBorders = curBorder.getCompoundBorders();
            for (int i = Component.TOP; i <= Component.RIGHT; i++) {
                if (borders[i] == null) {
                    borders[i] = oldBorders[i];
                }
            }
        }
        Border border = Border.createCompoundBorder(borders[Component.TOP], borders[Component.BOTTOM], borders[Component.LEFT], borders[Component.RIGHT]);
        if (border != null) {
            if ((styles & STYLE_SELECTED) != 0) {
                borderUi.getSelectedStyle().setBorder(border);
            }
            if ((styles & STYLE_UNSELECTED) != 0) {
                borderUi.getUnselectedStyle().setBorder(border);
            }
            if ((styles & STYLE_PRESSED) != 0) {
                ((HTMLLink) borderUi).getPressedStyle().setBorder(border);
            }
            if (borderUi.getParent() != null) {
                borderUi.getParent().revalidate();
            } else if (borderUi instanceof Container) {
                ((Container) borderUi).revalidate();
            }
        }
    }
    // 
    // Specific elements styling
    // 
    // Access keys
    v = selector.getAttributeById(CSSElement.CSS_WAP_ACCESSKEY);
    if ((v != null) && (v.length() >= 1) && (// These are the only tags that can accpet an access key
    (element.getTagId() == HTMLElement.TAG_INPUT) || (element.getTagId() == HTMLElement.TAG_TEXTAREA) || (element.getTagId() == HTMLElement.TAG_LABEL) || // For A tags this is applied only to the first word, no need to apply it to each word of the link
    ((element.getTagId() == HTMLElement.TAG_A) && (ui instanceof HTMLLink) && ((HTMLLink) ui).parentLink == null))) {
        // The accesskey string may consist fallback assignments (comma seperated) and multiple assignments (space seperated) and any combination of those
        // For example: "send *, #" (meaning: assign both the send and * keys, and if failed to assign one of those assign the # key instead)
        int index = v.indexOf(',');
        boolean assigned = false;
        while (index != -1) {
            // Handle fallback access keys
            String key = v.substring(0, index).trim();
            v = v.substring(index + 1);
            assigned = processAccessKeys(key, htmlC, ui);
            if (assigned) {
                // comma denotes fallback, and once we succeeded assigning the accesskey, the others are irrelevant
                break;
            }
            index = v.indexOf(',');
        }
        if (!assigned) {
            processAccessKeys(v.trim(), htmlC, ui);
        }
    }
    if (!HTMLComponent.PROCESS_HTML_MP1_ONLY) {
        // Text decoration (In HTML-MP1 the only mandatory decoration is 'none')
        int decoration = selector.getAttrVal(CSSElement.CSS_TEXT_DECORATION);
        if (decoration == TEXT_DECOR_NONE) {
            removeTextDecorationRecursive(ui, selector);
        } else if (decoration == TEXT_DECOR_UNDERLINE) {
            setTextDecorationRecursive(ui, Style.TEXT_DECORATION_UNDERLINE, selector);
        } else if (decoration == TEXT_DECOR_LINETHROUGH) {
            setTextDecorationRecursive(ui, Style.TEXT_DECORATION_STRIKETHRU, selector);
        } else if (decoration == TEXT_DECOR_OVERLINE) {
            setTextDecorationRecursive(ui, Style.TEXT_DECORATION_OVERLINE, selector);
        }
        // Word spacing
        if (!HTMLComponent.FIXED_WIDTH) {
            // The relative dimension is 0, since percentage doesn't work with word-spacing in browsers
            int wordSpace = selector.getAttrLengthVal(CSSElement.CSS_WORD_SPACING, ui, 0);
            if (wordSpace != -1) {
                setWordSpacingRecursive(ui, wordSpace);
            }
        }
        // Line height
        // Technically the font height should be queried when actually resizing the line (since it may differ for a big block) - but since this would be ery time consuming and also major browsers don't take it into account - we'll do the same
        // int lineHeight=selector.getAttrLengthVal(CSSElement.CSS_LINE_HEIGHT, ui, ui.getStyle().getFont().getHeight());
        int lineHeight = selector.getAttrLengthVal(CSSElement.CSS_LINE_HEIGHT, ui, ui.getStyle().getFont().getHeight());
        if (lineHeight != -1) {
            // 100% means normal line height (don't add margin). Sizes below will not work, even they do in regular browsers
            lineHeight = Math.max(0, lineHeight - ui.getStyle().getFont().getHeight());
            setLineHeightRecursive(ui, lineHeight / 2);
        }
        // Quotes
        String quotesStr = selector.getAttributeById(CSSElement.CSS_QUOTES);
        if (quotesStr != null) {
            Vector quotes = htmlC.getWords(quotesStr, Component.LEFT, false);
            int size = quotes.size();
            if ((size == 2) || (size == 4)) {
                String[] quotesArr = new String[4];
                for (int i = 0; i < size; i++) {
                    quotesArr[i] = omitQuotesIfExist((String) quotes.elementAt(i));
                }
                if (size == 2) {
                    // If only 2 quotes are specified they are used both as primary and secondary
                    quotesArr[2] = quotesArr[0];
                    quotesArr[3] = quotesArr[1];
                }
                setQuotesRecursive(ui, quotesArr);
            }
        }
        // Outline
        Border outline = createBorder(selector, borderUi, 0, styles, OUTLINE);
        if (outline != null) {
            if ((styles & STYLE_SELECTED) != 0) {
                addOutlineToStyle(borderUi.getSelectedStyle(), outline);
            }
            if ((styles & STYLE_UNSELECTED) != 0) {
                addOutlineToStyle(borderUi.getUnselectedStyle(), outline);
            }
            if ((styles & STYLE_PRESSED) != 0) {
                addOutlineToStyle(((HTMLLink) borderUi).getPressedStyle(), outline);
            }
            if (borderUi.getParent() != null) {
                borderUi.getParent().revalidate();
            } else if (borderUi instanceof Container) {
                ((Container) borderUi).revalidate();
            }
        }
        // Direction
        int dir = selector.getAttrVal(CSSElement.CSS_DIRECTION);
        if (dir != -1) {
            setDirectionRecursive(ui, dir == DIRECTION_RTL);
        }
        // Table properties
        if (ui instanceof HTMLTable) {
            int tableProp = selector.getAttrVal(CSSElement.CSS_BORDER_COLLAPSE);
            if (tableProp != -1) {
                ((HTMLTable) ui).setCollapseBorder(tableProp == BORDER_COLLAPSE_COLLAPSE);
            }
            tableProp = selector.getAttrVal(CSSElement.CSS_EMPTY_CELLS);
            if (tableProp != -1) {
                ((HTMLTable) ui).setDrawEmptyCellsBorder(tableProp == EMPTY_CELLS_SHOW);
            }
            // bottom = 0 , top = 1
            tableProp = selector.getAttrVal(CSSElement.CSS_CAPTION_SIDE);
            if (tableProp != -1) {
                Container tableParentCont = ui.getParent();
                // should result in 0 when the caption is at the bottom, and 1 when the caption is on top
                int tablePos = tableParentCont.getComponentIndex(ui);
                if (tableProp != tablePos) {
                    Component caption = tableParentCont.getComponentAt((tablePos + 1) % 2);
                    tableParentCont.removeComponent(caption);
                    tableParentCont.addComponent(tablePos, caption);
                }
            }
            String spacing = selector.getAttributeById(CSSElement.CSS_BORDER_SPACING);
            if (spacing != null) {
                spacing = spacing.trim();
                int index = spacing.indexOf(' ');
                int spaceH = 0;
                int spaceV = 0;
                if (index == -1) {
                    // one value only
                    spaceH = CSSElement.convertLengthVal(CSSElement.convertUnitsOrPercentage(spacing), ui, ui.getPreferredW());
                    spaceV = spaceH;
                } else {
                    String spaceHoriz = spacing.substring(0, index);
                    String spaceVert = spacing.substring(index + 1);
                    spaceH = CSSElement.convertLengthVal(CSSElement.convertUnitsOrPercentage(spaceHoriz), ui, ui.getPreferredW());
                    spaceV = CSSElement.convertLengthVal(CSSElement.convertUnitsOrPercentage(spaceVert), ui, ui.getPreferredH());
                }
                ((HTMLTable) ui).setBorderSpacing(spaceH, spaceV);
            }
        }
    }
    // This is since in some cases other elements can come between a OL/UL and its LI items (Though illegal in HTML, it can occur)
    if ((listType != -1) || (listImg != null)) {
        if (element.getTagId() == HTMLElement.TAG_LI) {
            if (ui instanceof Container) {
                Container liCont = (Container) ui;
                Container liParent = liCont.getParent();
                Component firstComp = liParent.getComponentAt(0);
                if (firstComp instanceof Container) {
                    Container bulletCont = (Container) firstComp;
                    if (bulletCont.getComponentCount() > 0) {
                        Component listItemCmp = bulletCont.getComponentAt(0);
                        if (listItemCmp instanceof Component) {
                            HTMLListItem listItem = ((HTMLListItem) listItemCmp);
                            listItem.setStyleType(listType);
                            listItem.setImage(listImg);
                        }
                    }
                }
            }
        } else if ((element.getTagId() == HTMLElement.TAG_UL) || (element.getTagId() == HTMLElement.TAG_OL) || (element.getTagId() == HTMLElement.TAG_DIR) || (element.getTagId() == HTMLElement.TAG_MENU)) {
            Container ulCont = (Container) ui;
            for (int i = 0; i < ulCont.getComponentCount(); i++) {
                Component cmp = ulCont.getComponentAt(i);
                if (cmp instanceof Container) {
                    Container liCont = (Container) cmp;
                    if (liCont.getComponentCount() >= 1) {
                        cmp = liCont.getComponentAt(0);
                        if (cmp instanceof Container) {
                            Container liContFirstLine = (Container) cmp;
                            if (liContFirstLine.getComponentCount() >= 1) {
                                cmp = liContFirstLine.getComponentAt(0);
                                if (cmp instanceof HTMLListItem) {
                                    HTMLListItem listItem = (HTMLListItem) cmp;
                                    listItem.setStyleType(listType);
                                    listItem.setImage(listImg);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : TextArea(com.codename1.ui.TextArea) Label(com.codename1.ui.Label) Container(com.codename1.ui.Container) BorderLayout(com.codename1.ui.layouts.BorderLayout) Component(com.codename1.ui.Component) Border(com.codename1.ui.plaf.Border) Vector(java.util.Vector)

Example 28 with Theme

use of com.codename1.ui.util.xml.Theme in project codenameone-google-maps by codenameone.

the class GoogleMapsTestApp method init.

public void init(Object context) {
    try {
        Resources theme = Resources.openLayered("/theme");
        UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
        Display.getInstance().setCommandBehavior(Display.COMMAND_BEHAVIOR_SIDE_NAVIGATION);
        UIManager.getInstance().getLookAndFeel().setMenuBarClass(SideMenuBar.class);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : Resources(com.codename1.ui.util.Resources) IOException(java.io.IOException)

Example 29 with Theme

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

the class UIManager method parseStyle.

/**
 * Creates a style by providing style strings in a specific format. This method allows for the use of inline styles
 * to override the styles in {@link com.codename1.ui.Component}
 * @param theme Theme used to retrieve images referenced in the style strings.
 * @param id The style ID (UIID) to use to cache the style inside the theme.
 * @param prefix Prefix to use for styles.  Corresponds to the {@literal prefix} argument in {@link #getComponentStyleImpl(java.lang.String, boolean, java.lang.String)
 * @param baseStyle The style class from which this new style should derive.
 * @param selected True if this is for a selected style.
 * @param styleString Array of style strings to be parsed.  The format is {@literal key1:value1; key2:value2; etc...}.  While this looks similar to CSS, it is important to note that it is NOT
 * CSS.  The keys and values correspond to the properties of {@link com.codename1.ui.plaf.Style} and their associated values.
 * @return A style object representing the styles that were provided in the styleString.
 *
 * <h3>Example Usage</h3>
 *
 * {@code
 * Style s = parseStyle(theme, "Button[MyCustomButton]", "", "Button", false,
 *     "fgColor:ff0000; font:18mm; border: 1px solid ff0000; bgType:none; padding: 3mm; margin: 1mm");
 *
 * // Create a 9-piece image border on the fly:
 * Style s = parseStyle(theme, "Button[MyCustomButton]", "", "Button", false,
 *      "border:splicedImage /notes.png 0.3 0.4 0.3 0.4");
 *      // This splices the image found at /notes.png into 9 pieces.  Splice insets are specified by the 4 floating point values
 *      // at the end of the border directive:  [top] [right] [bottom] [left].
 * }
 */
Style parseStyle(Resources theme, String id, String prefix, String baseStyle, boolean selected, String... styleString) {
    String cacheKey = selected ? id + ".sel" : id + "." + prefix;
    String originalId = id;
    if (id == null || id.length() == 0) {
        // if no id return the default style
        id = "";
    } else {
        id = id + ".";
    }
    if (Arrays.toString(styleString).equals(parseCache().get(cacheKey)) && ((selected && selectedStyles.containsKey(id)) || (!selected && this.styles.containsKey(id)))) {
        return getComponentStyleImpl(originalId, selected, prefix);
    }
    parseCache().put(cacheKey, Arrays.toString(styleString));
    Style base = baseStyle != null ? getComponentStyleImpl(baseStyle, selected, prefix) : null;
    Map<String, String> styles = new HashMap<String, String>();
    for (String str : styleString) {
        StyleParser.parseString(styles, str);
    }
    StyleInfo styleInfo = new StyleInfo(styles);
    if (prefix != null && prefix.length() > 0) {
        id += prefix;
    }
    if (themeProps == null) {
        resetThemeProps(null);
    }
    if (baseStyle != null) {
        themeProps.put(id + "derive", baseStyle);
    } else {
        themeProps.remove(id + "derive");
    }
    String val = null;
    Integer bgColor = styleInfo.getBgColor();
    if (bgColor != null) {
        themeProps.put(id + Style.BG_COLOR, Integer.toHexString(bgColor));
    } else {
        themeProps.remove(id + Style.BG_COLOR);
    }
    Integer fgColor = styleInfo.getFgColor();
    if (fgColor != null) {
        themeProps.put(id + Style.FG_COLOR, Integer.toHexString(fgColor));
    } else {
        themeProps.remove(id + Style.FG_COLOR);
    }
    BorderInfo border = styleInfo.getBorder();
    if (border != null) {
        themeProps.put(id + Style.BORDER, border.createBorder(theme));
    } else {
        themeProps.remove(id + Style.BORDER);
    }
    Integer bgType = styleInfo.getBgType();
    if (bgType != null) {
        themeProps.put(id + Style.BACKGROUND_TYPE, bgType.byteValue());
    } else {
        themeProps.remove(id + Style.BACKGROUND_TYPE);
    }
    ImageInfo bgImage = styleInfo.getBgImage();
    if (bgImage != null) {
        themeProps.put(id + Style.BG_IMAGE, bgImage.getImage(theme));
    } else {
        themeProps.remove(id + Style.BG_IMAGE);
    }
    MarginInfo margin = styleInfo.getMargin();
    if (margin != null) {
        float[] marginArr = margin.createMargin(base);
        themeProps.put(id + Style.MARGIN, marginArr[Component.TOP] + "," + marginArr[Component.BOTTOM] + "," + marginArr[Component.LEFT] + "," + marginArr[Component.RIGHT]);
        byte[] unitArr = margin.createMarginUnit(base);
        themeProps.put(id + Style.MARGIN_UNIT, new byte[] { unitArr[Component.TOP], unitArr[Component.BOTTOM], unitArr[Component.LEFT], unitArr[Component.RIGHT] });
    } else {
        themeProps.remove(id + Style.MARGIN);
        themeProps.remove(id + Style.MARGIN_UNIT);
    }
    PaddingInfo padding = styleInfo.getPadding();
    if (padding != null) {
        float[] paddingArr = padding.createPadding(base);
        themeProps.put(id + Style.PADDING, paddingArr[Component.TOP] + "," + paddingArr[Component.BOTTOM] + "," + paddingArr[Component.LEFT] + "," + paddingArr[Component.RIGHT]);
        byte[] unitArr = padding.createPaddingUnit(base);
        themeProps.put(id + Style.PADDING_UNIT, new byte[] { unitArr[Component.TOP], unitArr[Component.BOTTOM], unitArr[Component.LEFT], unitArr[Component.RIGHT] });
    } else {
        themeProps.remove(id + Style.PADDING);
        themeProps.remove(id + Style.PADDING_UNIT);
    }
    Integer transparency = styleInfo.getTransparency();
    if (transparency != null) {
        themeProps.put(id + Style.TRANSPARENCY, String.valueOf(transparency.intValue()));
    } else {
        themeProps.remove(id + Style.TRANSPARENCY);
    }
    Integer opacity = styleInfo.getOpacity();
    if (opacity != null) {
        themeProps.put(id + Style.OPACITY, String.valueOf(opacity.intValue()));
    } else {
        themeProps.remove(id + Style.OPACITY);
    }
    Integer alignment = styleInfo.getAlignment();
    if (alignment != null) {
        themeProps.put(id + Style.ALIGNMENT, alignment);
    } else {
        themeProps.remove(id + Style.ALIGNMENT);
    }
    Integer textDecoration = styleInfo.getTextDecoration();
    if (textDecoration != null) {
        themeProps.put(id + Style.TEXT_DECORATION, textDecoration);
    } else {
        themeProps.remove(id + Style.TEXT_DECORATION);
    }
    FontInfo font = styleInfo.getFont();
    if (font != null) {
        themeProps.put(id + Style.FONT, font.createFont(base));
    } else {
        themeProps.remove(id + Style.FONT);
    }
    if (selected)
        selectedStyles.remove(id);
    else
        this.styles.remove(id);
    return getComponentStyleImpl(originalId, selected, prefix);
}
Also used : HashMap(java.util.HashMap) BorderInfo(com.codename1.ui.plaf.StyleParser.BorderInfo) PaddingInfo(com.codename1.ui.plaf.StyleParser.PaddingInfo) MarginInfo(com.codename1.ui.plaf.StyleParser.MarginInfo) StyleInfo(com.codename1.ui.plaf.StyleParser.StyleInfo) ImageInfo(com.codename1.ui.plaf.StyleParser.ImageInfo) FontInfo(com.codename1.ui.plaf.StyleParser.FontInfo)

Example 30 with Theme

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

the class EditableResources method openFileWithXMLSupport.

public void openFileWithXMLSupport(File f) throws IOException {
    if (xmlEnabled && f.getParentFile().getName().equals("src")) {
        File res = new File(f.getParentFile().getParentFile(), "res");
        if (res.exists()) {
            File xml = new File(res, f.getName().substring(0, f.getName().length() - 3) + "xml");
            if (xml.exists()) {
                loadingMode = true;
                com.codename1.ui.Font.clearBitmapCache();
                clear();
                try {
                    File resDir = new File(res, f.getName().substring(0, f.getName().length() - 4));
                    // open the XML file...
                    JAXBContext ctx = JAXBContext.newInstance(ResourceFileXML.class);
                    ResourceFileXML xmlData = (ResourceFileXML) ctx.createUnmarshaller().unmarshal(xml);
                    boolean normalize = xmlData.getMajorVersion() > 1 || xmlData.getMinorVersion() > 5;
                    majorVersion = (short) xmlData.getMajorVersion();
                    minorVersion = (short) xmlData.getMinorVersion();
                    xmlUI = xmlData.isUseXmlUI();
                    if (xmlData.getData() != null) {
                        for (Data d : xmlData.getData()) {
                            setResource(d.getName(), MAGIC_DATA, readFile(resDir, d.getName(), normalize));
                        }
                    }
                    if (xmlData.getLegacyFont() != null) {
                        for (LegacyFont d : xmlData.getLegacyFont()) {
                            String name = d.getName();
                            if (normalize) {
                                name = normalizeFileName(name);
                            }
                            DataInputStream fi = new DataInputStream(new FileInputStream(new File(resDir, name)));
                            setResource(d.getName(), MAGIC_FONT, loadFont(fi, d.getName(), false));
                            fi.close();
                        }
                    }
                    if (xmlData.getImage() != null) {
                        for (com.codename1.ui.util.xml.Image d : xmlData.getImage()) {
                            if (d.getType() == null) {
                                // standara JPG or PNG
                                String name = d.getName();
                                if (normalize) {
                                    name = normalizeFileName(name);
                                }
                                FileInputStream fi = new FileInputStream(new File(resDir, name));
                                EncodedImage e = EncodedImage.create(fi);
                                fi.close();
                                setResource(d.getName(), MAGIC_IMAGE, e);
                                continue;
                            }
                            if ("svg".equals(d.getType())) {
                                setResource(d.getName(), MAGIC_IMAGE, Image.createSVG(d.getType(), false, readFile(resDir, d.getName(), normalize)));
                                continue;
                            }
                            if ("timeline".equals(d.getType())) {
                                String name = d.getName();
                                if (normalize) {
                                    name = normalizeFileName(name);
                                }
                                DataInputStream fi = new DataInputStream(new FileInputStream(new File(resDir, name)));
                                setResource(d.getName(), MAGIC_IMAGE, readTimeline(fi));
                                fi.close();
                                continue;
                            }
                            if ("multi".equals(d.getType())) {
                                String name = d.getName();
                                if (normalize) {
                                    name = normalizeFileName(name);
                                }
                                File multiImageDir = new File(resDir, name);
                                File hd4k = new File(multiImageDir, "4k.png");
                                File hd2 = new File(multiImageDir, "2hd.png");
                                File hd560 = new File(multiImageDir, "560.png");
                                File hd = new File(multiImageDir, "hd.png");
                                File veryhigh = new File(multiImageDir, "veryhigh.png");
                                File high = new File(multiImageDir, "high.png");
                                File medium = new File(multiImageDir, "medium.png");
                                File low = new File(multiImageDir, "low.png");
                                File veryLow = new File(multiImageDir, "verylow.png");
                                Map<Integer, EncodedImage> images = new HashMap<Integer, EncodedImage>();
                                if (hd4k.exists()) {
                                    images.put(new Integer(Display.DENSITY_4K), EncodedImage.create(readFileNoNormal(hd4k)));
                                }
                                if (hd2.exists()) {
                                    images.put(new Integer(Display.DENSITY_2HD), EncodedImage.create(readFileNoNormal(hd2)));
                                }
                                if (hd560.exists()) {
                                    images.put(new Integer(Display.DENSITY_560), EncodedImage.create(readFileNoNormal(hd560)));
                                }
                                if (hd.exists()) {
                                    images.put(new Integer(Display.DENSITY_HD), EncodedImage.create(readFileNoNormal(hd)));
                                }
                                if (veryhigh.exists()) {
                                    images.put(new Integer(Display.DENSITY_VERY_HIGH), EncodedImage.create(readFileNoNormal(veryhigh)));
                                }
                                if (high.exists()) {
                                    images.put(new Integer(Display.DENSITY_HIGH), EncodedImage.create(readFileNoNormal(high)));
                                }
                                if (medium.exists()) {
                                    images.put(new Integer(Display.DENSITY_MEDIUM), EncodedImage.create(readFileNoNormal(medium)));
                                }
                                if (low.exists()) {
                                    images.put(new Integer(Display.DENSITY_LOW), EncodedImage.create(readFileNoNormal(low)));
                                }
                                if (veryLow.exists()) {
                                    images.put(new Integer(Display.DENSITY_VERY_LOW), EncodedImage.create(readFileNoNormal(veryLow)));
                                }
                                int[] dpis = new int[images.size()];
                                EncodedImage[] imageArray = new EncodedImage[images.size()];
                                int count = 0;
                                for (Map.Entry<Integer, EncodedImage> m : images.entrySet()) {
                                    dpis[count] = m.getKey().intValue();
                                    imageArray[count] = m.getValue();
                                    count++;
                                }
                                MultiImage result = new MultiImage();
                                result.setDpi(dpis);
                                result.setInternalImages(imageArray);
                                setResource(d.getName(), MAGIC_IMAGE, result);
                                continue;
                            }
                        }
                    }
                    if (xmlData.getL10n() != null) {
                        for (L10n d : xmlData.getL10n()) {
                            Hashtable<String, Hashtable<String, String>> l10n = new Hashtable<String, Hashtable<String, String>>();
                            for (Lang l : d.getLang()) {
                                Hashtable<String, String> language = new Hashtable<String, String>();
                                if (l != null && l.getEntry() != null) {
                                    for (Entry e : l.getEntry()) {
                                        language.put(e.getKey(), e.getValue());
                                    }
                                }
                                l10n.put(l.getName(), language);
                            }
                            setResource(d.getName(), MAGIC_L10N, l10n);
                        }
                    }
                    if (xmlData.getTheme() != null) {
                        for (Theme d : xmlData.getTheme()) {
                            Hashtable<String, Object> theme = new Hashtable<String, Object>();
                            theme.put("uninitialized", Boolean.TRUE);
                            if (d.getVal() != null) {
                                for (Val v : d.getVal()) {
                                    String key = v.getKey();
                                    if (key.endsWith("align") || key.endsWith("textDecoration")) {
                                        theme.put(key, Integer.valueOf(v.getValue()));
                                        continue;
                                    }
                                    if (key.endsWith(Style.BACKGROUND_TYPE) || key.endsWith(Style.BACKGROUND_ALIGNMENT)) {
                                        theme.put(key, Byte.valueOf(v.getValue()));
                                        continue;
                                    }
                                    // padding and or margin type
                                    if (key.endsWith("Unit")) {
                                        String[] s = v.getValue().split(",");
                                        theme.put(key, new byte[] { Byte.parseByte(s[0]), Byte.parseByte(s[1]), Byte.parseByte(s[2]), Byte.parseByte(s[3]) });
                                        continue;
                                    }
                                    theme.put(key, v.getValue());
                                }
                            }
                            if (d.getBorder() != null) {
                                for (com.codename1.ui.util.xml.Border b : d.getBorder()) {
                                    if ("empty".equals(b.getType())) {
                                        theme.put(b.getKey(), Border.createEmpty());
                                        continue;
                                    }
                                    if ("round".equals(b.getType())) {
                                        RoundBorder rb = RoundBorder.create();
                                        rb = rb.color(b.getRoundBorderColor());
                                        rb = rb.rectangle(b.isRectangle());
                                        rb = rb.shadowBlur(b.getShadowBlur());
                                        rb = rb.shadowOpacity(b.getShadowOpacity());
                                        rb = rb.shadowSpread((int) b.getShadowSpread(), b.isShadowMM());
                                        rb = rb.shadowX(b.getShadowX());
                                        rb = rb.shadowY(b.getShadowY());
                                        rb = rb.stroke(b.getStrokeThickness(), b.isStrokeMM());
                                        rb = rb.strokeColor(b.getStrokeColor());
                                        rb = rb.strokeOpacity(b.getStrokeOpacity());
                                        theme.put(b.getKey(), rb);
                                        continue;
                                    }
                                    if ("roundRect".equals(b.getType())) {
                                        RoundRectBorder rb = RoundRectBorder.create();
                                        rb = rb.shadowBlur(b.getShadowBlur());
                                        rb = rb.shadowOpacity(b.getShadowOpacity());
                                        rb = rb.shadowSpread(b.getShadowSpread());
                                        rb = rb.shadowX(b.getShadowX());
                                        rb = rb.shadowY(b.getShadowY());
                                        rb = rb.stroke(b.getStrokeThickness(), b.isStrokeMM());
                                        rb = rb.strokeColor(b.getStrokeColor());
                                        rb = rb.strokeOpacity(b.getStrokeOpacity());
                                        rb = rb.bezierCorners(b.isBezierCorners());
                                        rb = rb.bottomOnlyMode(b.isBottomOnlyMode());
                                        rb = rb.topOnlyMode(b.isTopOnlyMode());
                                        rb = rb.cornerRadius(b.getCornerRadius());
                                        theme.put(b.getKey(), rb);
                                        continue;
                                    }
                                    if ("line".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            if (b.isMillimeters()) {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().floatValue()));
                                            } else {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().intValue()));
                                            }
                                        } else {
                                            if (b.isMillimeters()) {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().floatValue(), b.getColor().intValue()));
                                            } else {
                                                theme.put(b.getKey(), Border.createLineBorder(b.getThickness().intValue(), b.getColor().intValue()));
                                            }
                                        }
                                        continue;
                                    }
                                    if ("underline".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createUndelineBorder(b.getThickness().intValue()));
                                        } else {
                                            theme.put(b.getKey(), Border.createUnderlineBorder(b.getThickness().intValue(), b.getColor().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("rounded".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createRoundBorder(b.getArcW().intValue(), b.getArcH().intValue()));
                                        } else {
                                            theme.put(b.getKey(), Border.createRoundBorder(b.getArcW().intValue(), b.getArcH().intValue(), b.getColor().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("etchedRaised".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createEtchedRaised());
                                        } else {
                                            theme.put(b.getKey(), Border.createEtchedRaised(b.getColor().intValue(), b.getColorB().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("etchedLowered".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createEtchedLowered());
                                        } else {
                                            theme.put(b.getKey(), Border.createEtchedLowered(b.getColor().intValue(), b.getColorB().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("bevelLowered".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createBevelLowered());
                                        } else {
                                            theme.put(b.getKey(), Border.createBevelLowered(b.getColor().intValue(), b.getColorB().intValue(), b.getColorC().intValue(), b.getColorD().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("bevelRaised".equals(b.getType())) {
                                        if (b.getColor() == null) {
                                            theme.put(b.getKey(), Border.createBevelRaised());
                                        } else {
                                            theme.put(b.getKey(), Border.createBevelRaised(b.getColor().intValue(), b.getColorB().intValue(), b.getColorC().intValue(), b.getColorD().intValue()));
                                        }
                                        continue;
                                    }
                                    if ("image".equals(b.getType())) {
                                        int imageCount = 2;
                                        if (b.getI9() != null) {
                                            imageCount = 9;
                                        } else {
                                            if (b.getI8() != null) {
                                                imageCount = 8;
                                            } else {
                                                if (b.getI3() != null) {
                                                    imageCount = 3;
                                                }
                                            }
                                        }
                                        String[] borderInstance;
                                        switch(imageCount) {
                                            case 2:
                                                borderInstance = new String[] { b.getI1(), b.getI2() };
                                                break;
                                            case 3:
                                                borderInstance = new String[] { b.getI1(), b.getI2(), b.getI3() };
                                                break;
                                            case 8:
                                                borderInstance = new String[] { b.getI1(), b.getI2(), b.getI3(), b.getI4(), b.getI5(), b.getI6(), b.getI7(), b.getI8() };
                                                break;
                                            default:
                                                borderInstance = new String[] { b.getI1(), b.getI2(), b.getI3(), b.getI4(), b.getI5(), b.getI6(), b.getI7(), b.getI8(), b.getI9() };
                                                break;
                                        }
                                        theme.put(b.getKey(), borderInstance);
                                        continue;
                                    }
                                    if ("imageH".equals(b.getType())) {
                                        theme.put(b.getKey(), new String[] { "h", b.getI1(), b.getI2(), b.getI3() });
                                        continue;
                                    }
                                    if ("imageV".equals(b.getType())) {
                                        theme.put(b.getKey(), new String[] { "v", b.getI1(), b.getI2(), b.getI3() });
                                        continue;
                                    }
                                }
                            }
                            if (d.getFont() != null) {
                                for (com.codename1.ui.util.xml.Font b : d.getFont()) {
                                    if ("ttf".equals(b.getType())) {
                                        com.codename1.ui.Font system = com.codename1.ui.Font.createSystemFont(b.getFace().intValue(), b.getStyle().intValue(), b.getSize().intValue());
                                        EditorTTFFont t;
                                        if (b.getName().startsWith("native:")) {
                                            t = new EditorTTFFont(b.getName(), b.getSizeSettings().intValue(), b.getActualSize().floatValue(), system);
                                        } else {
                                            t = new EditorTTFFont(new File(f.getParentFile(), b.getName()), b.getSizeSettings().intValue(), b.getActualSize().floatValue(), system);
                                        }
                                        theme.put(b.getKey(), t);
                                        continue;
                                    }
                                    if ("system".equals(b.getType())) {
                                        com.codename1.ui.Font system = com.codename1.ui.Font.createSystemFont(b.getFace().intValue(), b.getStyle().intValue(), b.getSize().intValue());
                                        theme.put(b.getKey(), system);
                                        continue;
                                    }
                                // bitmap fonts aren't supported right now
                                }
                            }
                            if (d.getGradient() != null) {
                                for (com.codename1.ui.util.xml.Gradient b : d.getGradient()) {
                                    theme.put(b.getKey(), new Object[] { b.getColor1(), b.getColor2(), b.getPosX(), b.getPosY(), b.getRadius() });
                                }
                            }
                            setResource(d.getName(), MAGIC_THEME, theme);
                        }
                    }
                    // we load the UI last since it might depend on images or other elements in the future
                    if (xmlData.getUi() != null) {
                        if (xmlData.isUseXmlUI()) {
                            ArrayList<ComponentEntry> guiElements = new ArrayList<ComponentEntry>();
                            // place renderers first
                            final ArrayList<String> renderers = new ArrayList<String>();
                            for (Ui d : xmlData.getUi()) {
                                JAXBContext componentContext = JAXBContext.newInstance(ComponentEntry.class);
                                File uiFile = new File(resDir, normalizeFileName(d.getName()) + ".ui");
                                ComponentEntry uiXMLData = (ComponentEntry) componentContext.createUnmarshaller().unmarshal(uiFile);
                                guiElements.add(uiXMLData);
                                uiXMLData.findRendererers(renderers);
                            }
                            Collections.sort(guiElements, new Comparator<ComponentEntry>() {

                                private final ArrayList<String> entries1 = new ArrayList<String>();

                                private final ArrayList<String> entries2 = new ArrayList<String>();

                                @Override
                                public int compare(ComponentEntry o1, ComponentEntry o2) {
                                    if (renderers.contains(o1.getName())) {
                                        return -1;
                                    }
                                    if (renderers.contains(o2.getName())) {
                                        return 1;
                                    }
                                    entries1.clear();
                                    entries2.clear();
                                    o1.findEmbeddedDependencies(entries1);
                                    o2.findEmbeddedDependencies(entries2);
                                    if (entries1.size() == 0) {
                                        if (entries2.size() == 0) {
                                            return 0;
                                        }
                                        return -1;
                                    } else {
                                        if (entries2.size() == 0) {
                                            return 1;
                                        }
                                    }
                                    for (String e : entries1) {
                                        if (e.equals(o2.getName())) {
                                            return 1;
                                        }
                                    }
                                    for (String e : entries2) {
                                        if (e.equals(o1.getName())) {
                                            return -1;
                                        }
                                    }
                                    return 0;
                                }
                            });
                            for (ComponentEntry uiXMLData : guiElements) {
                                UIBuilderOverride uib = new UIBuilderOverride();
                                com.codename1.ui.Container cnt = uib.createInstance(uiXMLData, this);
                                // encountered an error loading the component fallback to loading with the binary types
                                if (cnt == null) {
                                    for (Ui ui : xmlData.getUi()) {
                                        setResource(uiXMLData.getName(), MAGIC_UI, readFile(resDir, ui.getName(), normalize));
                                    }
                                    break;
                                } else {
                                    byte[] data = UserInterfaceEditor.persistContainer(cnt, this);
                                    setResource(uiXMLData.getName(), MAGIC_UI, data);
                                }
                            }
                        } else {
                            for (Ui d : xmlData.getUi()) {
                                setResource(d.getName(), MAGIC_UI, readFile(resDir, d.getName(), normalize));
                            }
                        }
                    }
                    loadingMode = false;
                    modified = false;
                    updateModified();
                    // can occure when a resource file is opened via the constructor
                    if (undoQueue != null) {
                        undoQueue.clear();
                        redoQueue.clear();
                    }
                    return;
                } catch (JAXBException err) {
                    err.printStackTrace();
                }
            }
        }
    }
    openFile(new FileInputStream(f));
}
Also used : Val(com.codename1.ui.util.xml.Val) LegacyFont(com.codename1.ui.util.xml.LegacyFont) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EditorTTFFont(com.codename1.ui.EditorTTFFont) ComponentEntry(com.codename1.ui.util.xml.comps.ComponentEntry) ResourceFileXML(com.codename1.ui.util.xml.ResourceFileXML) JAXBException(javax.xml.bind.JAXBException) Lang(com.codename1.ui.util.xml.Lang) FileInputStream(java.io.FileInputStream) Ui(com.codename1.ui.util.xml.Ui) AnimationObject(com.codename1.ui.animations.AnimationObject) RoundBorder(com.codename1.ui.plaf.RoundBorder) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) L10n(com.codename1.ui.util.xml.L10n) JAXBContext(javax.xml.bind.JAXBContext) Entry(com.codename1.ui.util.xml.Entry) ComponentEntry(com.codename1.ui.util.xml.comps.ComponentEntry) RoundRectBorder(com.codename1.ui.plaf.RoundRectBorder) Hashtable(java.util.Hashtable) Data(com.codename1.ui.util.xml.Data) DataInputStream(java.io.DataInputStream) EncodedImage(com.codename1.ui.EncodedImage) Theme(com.codename1.ui.util.xml.Theme)

Aggregations

Hashtable (java.util.Hashtable)18 AnimationObject (com.codename1.ui.animations.AnimationObject)16 IOException (java.io.IOException)16 EncodedImage (com.codename1.ui.EncodedImage)12 Border (com.codename1.ui.plaf.Border)12 Image (com.codename1.ui.Image)10 RoundBorder (com.codename1.ui.plaf.RoundBorder)10 RoundRectBorder (com.codename1.ui.plaf.RoundRectBorder)10 BufferedImage (java.awt.image.BufferedImage)8 FileInputStream (java.io.FileInputStream)8 Resources (com.codename1.ui.util.Resources)7 File (java.io.File)7 EditorTTFFont (com.codename1.ui.EditorTTFFont)6 EditableResources (com.codename1.ui.util.EditableResources)6 InputStream (java.io.InputStream)6 EditorFont (com.codename1.ui.EditorFont)5 DataInputStream (java.io.DataInputStream)5 Container (com.codename1.ui.Container)4 Form (com.codename1.ui.Form)4 Label (com.codename1.ui.Label)4