Search in sources :

Example 6 with UI

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

the class ResourceEditorApp method generateResourceFile.

private static void generateResourceFile(File f, String themeName, String ui) throws Exception {
    System.out.println("Generating resource file " + f + " theme " + themeName + " template " + ui);
    EditableResources res = new EditableResources();
    // "native", "leather", "tzone", "tipster", "blank"
    String template = "Native_Theme";
    if (themeName.equalsIgnoreCase("leather")) {
        template = "Leather";
    }
    if (themeName.equalsIgnoreCase("chrome")) {
        template = "Chrome";
    }
    if (themeName.equalsIgnoreCase("tzone")) {
        template = "tzone_theme";
    }
    if (themeName.equalsIgnoreCase("tipster")) {
        template = "tipster_theme";
    }
    if (themeName.equalsIgnoreCase("socialboo")) {
        template = "socialboo";
    }
    if (themeName.equalsIgnoreCase("mapper")) {
        template = "mapper";
    }
    if (themeName.equalsIgnoreCase("flatblue")) {
        template = "FlatBlueTheme";
    }
    if (themeName.equalsIgnoreCase("flatred")) {
        template = "FlatRedTheme";
    }
    if (themeName.equalsIgnoreCase("flatorange")) {
        template = "FlatOrangeTheme";
    }
    if (themeName.equalsIgnoreCase("business")) {
        template = "BusinessTheme";
    }
    res.setTheme("Theme", importRes(res, template));
    if ("HiWorld".equalsIgnoreCase(ui)) {
        importRes(res, "HiWorldTemplate");
        generate(res, f);
    } else {
        if ("Tabs".equalsIgnoreCase(ui)) {
            importRes(res, "Tabs");
            generate(res, f);
        } else {
            if ("List".equalsIgnoreCase(ui)) {
                importRes(res, "ListOfItems");
                generate(res, f);
            } else {
                if ("NewHi".equalsIgnoreCase(ui)) {
                    importImage("android-icon.png", res);
                    importImage("apple-icon.png", res);
                    importImage("windows-icon.png", res);
                    importImage("duke-no-logos.png", res);
                    Map m = res.getTheme("Theme");
                    m.put("GetStarted.fgColor", "ffffff");
                    m.put("GetStarted.sel#fgColor", "ffffff");
                    m.put("GetStarted.press#fgColor", "ffffff");
                    m.put("GetStarted.bgColor", "339900");
                    m.put("GetStarted.sel#bgColor", "339900");
                    m.put("GetStarted.press#bgColor", "339900");
                    m.put("GetStarted.transparency", "255");
                    m.put("GetStarted.sel#transparency", "255");
                    m.put("GetStarted.press#transparency", "255");
                    Integer centerAlign = new Integer(4);
                    m.put("GetStarted.align", centerAlign);
                    m.put("GetStarted.sel#align", centerAlign);
                    m.put("GetStarted.press#align", centerAlign);
                    m.put("GetStarted.padding", "1,1,1,1");
                    m.put("GetStarted.padUnit", new byte[] { Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS });
                    m.put("GetStarted.sel#padding", "1,1,1,1");
                    m.put("GetStarted.sel#padUnit", new byte[] { Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS });
                    m.put("GetStarted.press#padding", "1,1,1,1");
                    m.put("GetStarted.press#padUnit", new byte[] { Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS });
                    m.put("GetStarted.font", new EditorTTFFont("native:MainLight", 3, 2.5f, Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM)));
                }
            }
        }
    }
    FileOutputStream os = new FileOutputStream(f);
    res.save(os);
    os.close();
}
Also used : EditorTTFFont(com.codename1.ui.EditorTTFFont) FileOutputStream(java.io.FileOutputStream) EditableResources(com.codename1.ui.util.EditableResources) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with UI

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

the class AddUIResource method addResource.

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

Example 8 with UI

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

the class CSSEngine method setNowrapText.

/**
 * Replaces a wrapped text with an unwrapped version.
 * This in fact removes all the labels that contains a single word each, and replaces them with one label that contains the whole text.
 * This way the label is not wrapped.
 *
 * @param label The first label of this text element (can be derived from ui but already fetched before the call)
 * @param ui The vector consisting all components (labels) that contain the text's words
 * @param newText The new text that should replace current components (unwrapped text without extra white spaces)
 * @param element The text element
 */
private void setNowrapText(Label label, Vector ui, String newText, HTMLElement element) {
    label.setText(newText);
    for (int i = 1; i < ui.size(); i++) {
        Component cmp = (Component) ui.elementAt(i);
        cmp.getParent().removeComponent(cmp);
    }
    if (label instanceof HTMLLink) {
        // Reset all associated link fragments so we don't have unneeded references
        ((HTMLLink) label).childLinks = new Vector();
    }
    element.setAssociatedComponents(label);
    label.getParent().revalidate();
}
Also used : Component(com.codename1.ui.Component) Vector(java.util.Vector)

Example 9 with UI

use of com.codename1.rad.ui.UI 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 10 with UI

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

the class CSSEngine method handleContentProperty.

/**
 * Handles a CSS content property
 *
 * @param element The element this content property
 * @param selector The CSS selector that includes the content property
 * @param htmlC The HTMLComponent
 */
private void handleContentProperty(HTMLElement element, CSSElement selector, HTMLComponent htmlC) {
    boolean after = ((selector.getSelectorPseudoClass() & CSSElement.PC_AFTER) != 0);
    String content = selector.getAttributeById(CSSElement.CSS_CONTENT);
    if (content != null) {
        // if there's no content, we don't add anything
        Component cmp = after ? (Component) element.getUi().lastElement() : (Component) element.getUi().firstElement();
        Component styleCmp = cmp;
        Container parent = null;
        int pos = 0;
        if (cmp instanceof Container) {
            parent = ((Container) cmp);
            while ((parent.getComponentCount() > 0) && (parent.getComponentAt(after ? parent.getComponentCount() - 1 : 0) instanceof Container)) {
                // find the actual content
                parent = (Container) parent.getComponentAt(after ? parent.getComponentCount() - 1 : 0);
            }
            if (parent.getComponentCount() > 0) {
                pos = after ? parent.getComponentCount() - 1 : 0;
                styleCmp = parent.getComponentAt(pos);
            }
        } else {
            parent = cmp.getParent();
            pos = cmp.getParent().getComponentIndex(cmp);
        }
        if (after) {
            pos++;
        }
        int initPos = pos;
        String str = "";
        // to make sure the last expression is evaluated, note that this will not print an extra space in any case, since it is out of the quotes if any
        content = content + " ";
        boolean segment = false;
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            Label lbl = null;
            if (c == '"') {
                segment = !segment;
                if ((!segment) && (str.length() > 0)) {
                    lbl = new Label(str);
                    str = "";
                }
            } else if (CSSParser.isWhiteSpace(c)) {
                if (segment) {
                    str += c;
                    lbl = new Label(str);
                } else if (str.length() > 0) {
                    lbl = evalContentExpression(htmlC, str, element, selector);
                    if (lbl == null) {
                        // if we didn't find a match we search for the following expressions which are used to remove added content
                        int removeQuoteType = -1;
                        boolean removeAll = false;
                        if ((str.equals("none")) || (str.equals("normal"))) {
                            // normal/none means remove all content
                            removeAll = true;
                        } else if (str.equals("no-open-quote")) {
                            // 0 is the quote type for open quote, 1 for closed one
                            removeQuoteType = 0;
                        } else if (str.equals("no-close-quote")) {
                            removeQuoteType = 1;
                        }
                        if ((removeAll) || (removeQuoteType != -1)) {
                            Vector v = element.getUi();
                            if (v != null) {
                                Vector toRemove = new Vector();
                                for (Enumeration e = v.elements(); e.hasMoreElements(); ) {
                                    Component ui = (Component) e.nextElement();
                                    String conStr = (String) ui.getClientProperty(CLIENT_PROPERTY_CSS_CONTENT);
                                    if ((conStr != null) && (((after) && (conStr.equals("a"))) || ((!after) && (conStr.equals("b"))))) {
                                        boolean remove = true;
                                        if (removeQuoteType != -1) {
                                            Object obj = ui.getClientProperty(HTMLComponent.CLIENT_PROPERTY_QUOTE);
                                            if (obj != null) {
                                                int quoteType = ((Integer) obj).intValue();
                                                remove = (quoteType == removeQuoteType);
                                            } else {
                                                remove = false;
                                            }
                                        }
                                        if (remove) {
                                            parent.removeComponent(ui);
                                            toRemove.addElement(ui);
                                        }
                                    }
                                }
                                for (Enumeration e = toRemove.elements(); e.hasMoreElements(); ) {
                                    v.removeElement(e.nextElement());
                                }
                            }
                            // stop processing after removal clauses such as none/normal
                            return;
                        }
                    }
                }
                str = "";
            } else {
                str += c;
            }
            if (lbl != null) {
                if (after) {
                    element.addAssociatedComponent(lbl);
                } else {
                    element.addAssociatedComponentAt(pos - initPos, lbl);
                }
                lbl.setUnselectedStyle(new Style(styleCmp.getUnselectedStyle()));
                lbl.putClientProperty(CLIENT_PROPERTY_CSS_CONTENT, after ? "a" : "b");
                if (parent.getComponentCount() == 0) {
                    parent.addComponent(lbl);
                } else {
                    parent.addComponent(pos, lbl);
                }
                pos++;
                applyStyleToUIElement(lbl, selector, element, htmlC);
            }
        }
    }
}
Also used : Container(com.codename1.ui.Container) Enumeration(java.util.Enumeration) Label(com.codename1.ui.Label) Style(com.codename1.ui.plaf.Style) Component(com.codename1.ui.Component) Vector(java.util.Vector)

Aggregations

Component (com.codename1.ui.Component)10 Label (com.codename1.ui.Label)9 ArrayList (java.util.ArrayList)9 Container (com.codename1.ui.Container)8 Form (com.codename1.ui.Form)8 IOException (java.io.IOException)8 TextArea (com.codename1.ui.TextArea)6 BorderLayout (com.codename1.ui.layouts.BorderLayout)6 HashMap (java.util.HashMap)6 Vector (java.util.Vector)6 Entity (com.codename1.rad.models.Entity)5 Hashtable (java.util.Hashtable)5 EntityList (com.codename1.rad.models.EntityList)4 ActionNode (com.codename1.rad.nodes.ActionNode)4 EncodedImage (com.codename1.ui.EncodedImage)4 FontImage (com.codename1.ui.FontImage)4 Border (com.codename1.ui.plaf.Border)4 Log (com.codename1.io.Log)3 EntityTypeBuilder.entityTypeBuilder (com.codename1.rad.models.EntityTypeBuilder.entityTypeBuilder)3 Thing (com.codename1.rad.schemas.Thing)3