Example usage for org.apache.wicket.model AbstractReadOnlyModel AbstractReadOnlyModel

List of usage examples for org.apache.wicket.model AbstractReadOnlyModel AbstractReadOnlyModel

Introduction

In this page you can find the example usage for org.apache.wicket.model AbstractReadOnlyModel AbstractReadOnlyModel.

Prototype

AbstractReadOnlyModel

Source Link

Usage

From source file:com.servoy.j2db.server.headlessclient.dataui.WebAccordionPanel.java

License:Open Source License

public WebAccordionPanel(IApplication application, final RuntimeAccordionPanel scriptable, String name) {
    super(name);// w  w  w. ja  v a 2 s  . co m
    this.application = application;

    setOutputMarkupPlaceholderTag(true);
    accordion = new Accordion("accordion_" + name) {
        @Override
        public JsStatement statement() {
            JsStatement statement = super.statement();
            int index = getTabIndex();
            if (index > 0) // 0 is opened by default
            {
                statement = statement.chain("accordion", "'activate'", String.valueOf(index));
            }
            return statement;
        }
    };
    add(accordion);
    // disable animation, see http://forum.jquery.com/topic/jquery-accordion-not-work-on-ie-7
    accordion.setAnimated(new AccordionAnimated(Boolean.FALSE));
    accordion.setFillSpace(true);
    IModel<Integer> tabsModel = new AbstractReadOnlyModel<Integer>() {
        private static final long serialVersionUID = 1L;

        @Override
        public Integer getObject() {
            return Integer.valueOf(allTabs.size());
        }
    };
    final boolean useAJAX = Utils.getAsBoolean(application.getRuntimeProperties().get("useAJAX")); //$NON-NLS-1$

    accordion.add(new Loop("tabs", tabsModel) //$NON-NLS-1$
    {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final LoopItem item) {
            item.setRenderBodyOnly(true);
            final WebTabHolder holder = allTabs.get(item.getIteration());
            ServoySubmitLink link = new ServoySubmitLink("tablink", useAJAX)//$NON-NLS-1$
            {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    Page page = findPage();
                    if (page != null) {
                        boolean needsRelayout = false;
                        if (currentForm != null && currentForm != holder.getPanel()
                                && currentForm.getFormName().equals(holder.getPanel().getFormName())) {
                            needsRelayout = true;
                        }
                        setActiveTabPanel(holder.getPanel());
                        if (target != null) {
                            if (needsRelayout && page instanceof MainPage
                                    && ((MainPage) page).getController() != null) {
                                if (Utils.getAsBoolean(((MainPage) page).getController().getApplication()
                                        .getRuntimeProperties().get("enableAnchors"))) //$NON-NLS-1$
                                {
                                    target.appendJavascript("layoutEntirePage();"); //$NON-NLS-1$
                                }
                            }
                            relinkFormIfNeeded();
                            accordion.activate(target, item.getIteration());
                            WebEventExecutor.generateResponse(target, page);
                        }
                    }
                }

                @Override
                protected void disableLink(ComponentTag tag) {
                    // do nothing here
                }
            };
            link.setEnabled(holder.isEnabled() && WebAccordionPanel.this.isEnabled());
            if (holder.getIcon() != null) {
                accordion.hideIcons();
            }
            if (holder.getTooltip() != null) {
                link.setMetaData(TooltipAttributeModifier.TOOLTIP_METADATA, holder.getTooltip());
            }
            TabIndexHelper.setUpTabIndexAttributeModifier(link, tabSequenceIndex);
            link.add(TooltipAttributeModifier.INSTANCE);

            String text = holder.getText();
            if (holder.getDisplayedMnemonic() > 0) {
                final String mnemonic = Character.toString((char) holder.getDisplayedMnemonic());
                link.add(new SimpleAttributeModifier("accesskey", mnemonic)); //$NON-NLS-1$
                if (text != null && text.contains(mnemonic) && !HtmlUtils.hasUsefulHtmlContent(text)) {
                    StringBuffer sbBodyText = new StringBuffer(text);
                    int mnemonicIdx = sbBodyText.indexOf(mnemonic);
                    if (mnemonicIdx != -1) {
                        sbBodyText.insert(mnemonicIdx + 1, "</u>"); //$NON-NLS-1$
                        sbBodyText.insert(mnemonicIdx, "<u>"); //$NON-NLS-1$
                        text = sbBodyText.toString();
                    }
                }
            }

            Label label = new Label("linktext", new Model<String>(text)); //$NON-NLS-1$
            label.setEscapeModelStrings(false);
            if (holder.getIcon() != null) {
                label.add(new SimpleAttributeModifier("class", "accordionlinkmargin"));
            }
            link.add(label);
            ServoyTabIcon icon = new ServoyTabIcon("icon", holder, scriptable); //$NON-NLS-1$
            if (holder.getIcon() != null) {
                icon.add(new StyleAppendingModifier(new Model<String>() {
                    @Override
                    public String getObject() {
                        return "float: left;"; //$NON-NLS-1$
                    }
                }));
            }
            holder.getPanel().getWebForm().add(new StyleAppendingModifier(new Model<String>() {
                private int getAllPartsHeight() {
                    int height = 0;
                    if (getCurrentForm().getController().getDataRenderers() != null) {
                        IDataRenderer[] renderers = getCurrentForm().getController().getDataRenderers();
                        for (IDataRenderer renderer : renderers) {
                            if (renderer != null) {
                                height += renderer.getSize().height;
                            }
                        }
                    }
                    return height;
                }

                @Override
                public String getObject() {
                    String formStyle = "padding: 0px;"; //$NON-NLS-1$
                    if (getBorder() instanceof TitledBorder) {
                        int fsize = 0;
                        int height = getAllPartsHeight();
                        TitledBorder td = (TitledBorder) getBorder();
                        if (td.getTitleFont() != null)
                            fsize = td.getTitleFont().getSize();
                        if (fsize > 11)
                            height = getAllPartsHeight() - (fsize - 11);
                        formStyle += "height: " + height + "px;"; //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    return formStyle;
                }
            }));
            link.add(icon);
            item.add(link);
            item.add(new Label("webform", new Model<String>(""))); // temporary add  //$NON-NLS-1$//$NON-NLS-2$
            label.add(new StyleAppendingModifier(new Model<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    String style = "white-space: nowrap;"; //$NON-NLS-1$
                    if (font != null) {
                        Pair<String, String>[] fontPropetiesPair = PersistHelper
                                .createFontCSSProperties(PersistHelper.createFontString(font));
                        if (fontPropetiesPair != null) {
                            for (Pair<String, String> element : fontPropetiesPair) {
                                if (element == null)
                                    continue;
                                style += element.getLeft() + ": " + element.getRight() + ";"; //$NON-NLS-1$ //$NON-NLS-2$
                            }
                        }
                    }
                    if (holder.getForeground() != null) {
                        style += " color:" + PersistHelper.createColorString(holder.getForeground()); //$NON-NLS-1$
                    } else if (foreground != null) {
                        style += " color:" + PersistHelper.createColorString(foreground); //$NON-NLS-1$
                    }
                    return style;
                }
            }));
        }
    });
    add(new AbstractServoyDefaultAjaxBehavior() {
        @Override
        protected void respond(AjaxRequestTarget target) {
        }

        @Override
        public void renderHead(IHeaderResponse response) {
            super.renderHead(response);
            // avoid flickering, see also tabpanel
            response.renderOnDomReadyJavascript(
                    "var accordion = document.getElementById('" + WebAccordionPanel.this.getMarkupId()
                            + "');if (accordion){accordion.style.visibility = 'inherit';}");
        }
    });

    accordion.add(new StyleAppendingModifier(new Model<String>() {
        @Override
        public String getObject() {
            if (getBorder() instanceof TitledBorder) {
                return "margin-top: -0.4em;"; //"padding: 6px 0px 0px 0px; margin-top: -8px;"; //$NON-NLS-1$
            }
            return ""; //$NON-NLS-1$
        }
    }));

    add(new StyleAppendingModifier(new Model<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            return "visibility: hidden;"; //$NON-NLS-1$
        }
    }));
    add(StyleAttributeModifierModel.INSTANCE);
    this.scriptable = scriptable;
    ((ChangesRecorder) scriptable.getChangesRecorder()).setDefaultBorderAndPadding(null,
            TemplateGenerator.DEFAULT_LABEL_PADDING);
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebAnchoringHelper.java

License:Open Source License

public static Component getWrapperComponent(Component comp, IFormElement obj, int start, Dimension panelSize,
        boolean leftToRight, boolean isInListView) {
    MarkupContainer compWrapper = new WrapperContainer(
            ComponentFactory.getWebID(null, obj) + TemplateGenerator.WRAPPER_SUFFIX, comp);
    Point l = (obj).getLocation();
    if (isInListView) {
        // substract left indicator
        l.x = Math.max(l.x - 3, 0);
    }/*from  w w  w  . j ava  2  s  .  co m*/
    Dimension s = (obj).getSize();
    int anchors = 0;
    if (obj instanceof ISupportAnchors)
        anchors = ((ISupportAnchors) obj).getAnchors();
    int offsetWidth = s.width;
    int offsetHeight = s.height;
    if (comp instanceof ISupportWebBounds) {
        Rectangle b = ((ISupportWebBounds) comp).getWebBounds();
        offsetWidth = b.width;
        offsetHeight = b.height;
    }
    final String styleToReturn = WebAnchoringHelper.computeWrapperDivStyle(l.y, l.x, offsetWidth, offsetHeight,
            s.width, s.height, anchors, start, start + panelSize.height, panelSize.width, leftToRight);
    // first the default
    compWrapper.add(new StyleAppendingModifier(new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            return styleToReturn;
        }
    }));
    // then the style t hat can be set on the wrapped component
    compWrapper.add(StyleAttributeModifierModel.INSTANCE);
    // TODO: this needs to be done in a cleaner way. See what is the relation between
    // margin, padding and border when calculating the websize in ChangesRecorder vs. TemplateGenerator.
    // Looks like one of the three is not taken into account during calculations. For now decided to remove
    // the margin and leave the padding and border.
    comp.add(new StyleAppendingModifier(new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            return "margin: 0px;"; //$NON-NLS-1$
        }
    }));
    return compWrapper;
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebImageBeanHolder.java

License:Open Source License

public WebImageBeanHolder(IApplication application, RuntimeScriptButton scriptable, String id, JComponent bean,
        int anchoring) {
    super(application, scriptable, id, ""); //$NON-NLS-1$
    ((ChangesRecorder) scriptable.getChangesRecorder()).setDefaultBorderAndPadding(null, null);
    this.bean = bean;
    this.anchoring = anchoring;
    if (bean != null)
        bean.addComponentListener(new ComponentAdapter() {
            @Override/*from  ww w  .  j a v a2  s .c  om*/
            public void componentResized(ComponentEvent e) {
                if (!WebImageBeanHolder.this.getSize().equals(WebImageBeanHolder.this.bean.getSize())) {
                    WebImageBeanHolder.this.getScriptObject().setSize(WebImageBeanHolder.this.bean.getWidth(),
                            WebImageBeanHolder.this.bean.getHeight());
                }
            }
        });
    setMediaOption(8 + 1);

    add(new AttributeModifier("src", new AbstractReadOnlyModel<String>() //$NON-NLS-1$
    {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            return urlFor(IResourceListener.INTERFACE) + "&x=" + Math.random(); //$NON-NLS-1$
        }

    }));

    icon = new MediaResource();

    final boolean useAnchors = Utils.getAsBoolean(application.getRuntimeProperties().get("enableAnchors")); //$NON-NLS-1$
    if (useAnchors) {
        if ((anchoring & (IAnchorConstants.WEST | IAnchorConstants.EAST)) != 0
                || (anchoring & (IAnchorConstants.NORTH | IAnchorConstants.SOUTH)) != 0) {
            add(new AbstractServoyDefaultAjaxBehavior() {
                @Override
                public void renderHead(IHeaderResponse response) {
                    super.renderHead(response);

                    String beanHolderId = WebImageBeanHolder.this.getMarkupId();

                    int width = getSize().width;
                    int height = getSize().height;

                    StringBuffer sb = new StringBuffer();
                    sb.append("if(typeof(beansPreferredSize) != \"undefined\")\n").append("{\n"); //$NON-NLS-1$ //$NON-NLS-2$
                    sb.append("beansPreferredSize['").append(beanHolderId).append("'] = new Array();\n"); //$NON-NLS-1$ //$NON-NLS-2$
                    sb.append("beansPreferredSize['").append(beanHolderId).append("']['height'] = ") //$NON-NLS-1$//$NON-NLS-2$
                            .append(height).append(";\n"); //$NON-NLS-1$
                    sb.append("beansPreferredSize['").append(beanHolderId).append("']['width'] = ") //$NON-NLS-1$//$NON-NLS-2$
                            .append(width).append(";\n"); //$NON-NLS-1$
                    sb.append("beansPreferredSize['").append(beanHolderId).append("']['callback'] = '") //$NON-NLS-1$//$NON-NLS-2$
                            .append(getCallbackUrl()).append("';\n"); //$NON-NLS-1$
                    sb.append("}\n"); //$NON-NLS-1$
                    response.renderOnLoadJavascript(sb.toString());
                }

                @Override
                protected void respond(AjaxRequestTarget target) {
                    String sWidthHint = getComponent().getRequest().getParameter("width"); //$NON-NLS-1$ 
                    String sHeightHint = getComponent().getRequest().getParameter("height"); //$NON-NLS-1$ 
                    int widthHint = Integer.parseInt(sWidthHint);
                    int heightHint = Integer.parseInt(sHeightHint);

                    setSize(new Dimension(widthHint, heightHint));
                    WebEventExecutor.generateResponse(target, getComponent().getPage());
                }
            });
        }
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebTabPanel.java

License:Open Source License

public WebTabPanel(IApplication application, final RuntimeTabPanel scriptable, String name, int orient,
        boolean oneTab) {
    super(name);// w w  w. java2 s. co  m
    this.application = application;
    this.orient = orient;

    final boolean useAJAX = Utils.getAsBoolean(application.getRuntimeProperties().get("useAJAX")); //$NON-NLS-1$
    setOutputMarkupPlaceholderTag(true);

    if (orient != TabPanel.SPLIT_HORIZONTAL && orient != TabPanel.SPLIT_VERTICAL)
        add(new Label("webform", new Model<String>("")));//temporary add, in case the tab panel does not contain any tabs //$NON-NLS-1$ //$NON-NLS-2$

    // TODO check ignore orient and oneTab??
    IModel<Integer> tabsModel = new AbstractReadOnlyModel<Integer>() {
        private static final long serialVersionUID = 1L;

        @Override
        public Integer getObject() {
            return Integer.valueOf(allTabs.size());
        }
    };

    if (orient != TabPanel.HIDE && orient != TabPanel.SPLIT_HORIZONTAL && orient != TabPanel.SPLIT_VERTICAL
            && !(orient == TabPanel.DEFAULT_ORIENTATION && oneTab)) {
        add(new Loop("tablinks", tabsModel) //$NON-NLS-1$
        {
            private static final long serialVersionUID = 1L;

            private String focusedItem;

            @Override
            protected void populateItem(final LoopItem item) {
                final WebTabHolder holder = allTabs.get(item.getIteration());
                MarkupContainer link = null;
                link = new ServoySubmitLink("tablink", useAJAX) //$NON-NLS-1$
                {
                    private static final long serialVersionUID = 1L;

                    /**
                     * @see wicket.ajax.markup.html.AjaxFallbackLink#onClick(wicket.ajax.AjaxRequestTarget)
                     */
                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        Page page = findPage();
                        if (page != null) {
                            setActiveTabPanel(holder.getPanel());
                            if (target != null) {
                                relinkAtTabPanel(WebTabPanel.this);
                                focusedItem = item.getId();
                                WebEventExecutor.generateResponse(target, page);
                            }
                        }
                    }

                    private void relinkAtForm(WebForm form) {
                        form.visitChildren(WebTabPanel.class, new IVisitor<WebTabPanel>() {
                            public Object component(WebTabPanel wtp) {
                                relinkAtTabPanel(wtp);
                                return IVisitor.CONTINUE_TRAVERSAL;
                            }
                        });
                    }

                    private void relinkAtTabPanel(WebTabPanel wtp) {
                        wtp.relinkFormIfNeeded();
                        wtp.visitChildren(WebForm.class, new IVisitor<WebForm>() {
                            public Object component(WebForm form) {
                                relinkAtForm(form);
                                return IVisitor.CONTINUE_TRAVERSAL;
                            }
                        });
                    }

                    @Override
                    protected void disableLink(final ComponentTag tag) {
                        // if the tag is an anchor proper
                        if (tag.getName().equalsIgnoreCase("a") || tag.getName().equalsIgnoreCase("link") //$NON-NLS-1$//$NON-NLS-2$
                                || tag.getName().equalsIgnoreCase("area")) //$NON-NLS-1$
                        {
                            // Remove any href from the old link
                            tag.remove("href"); //$NON-NLS-1$
                            tag.remove("onclick"); //$NON-NLS-1$
                        }
                    }

                };

                if (item.getId().equals(focusedItem)) {
                    IRequestTarget currentRequestTarget = RequestCycle.get().getRequestTarget();
                    if (currentRequestTarget instanceof AjaxRequestTarget) {
                        ((AjaxRequestTarget) currentRequestTarget).focusComponent(link);
                    }
                    focusedItem = null;
                }

                if (holder.getTooltip() != null) {
                    link.setMetaData(TooltipAttributeModifier.TOOLTIP_METADATA, holder.getTooltip());
                }

                TabIndexHelper.setUpTabIndexAttributeModifier(link, tabSequenceIndex);
                link.add(TooltipAttributeModifier.INSTANCE);

                if (item.getIteration() == 0)
                    link.add(new AttributeModifier("firsttab", true, new Model<Boolean>(Boolean.TRUE))); //$NON-NLS-1$
                link.setEnabled(holder.isEnabled() && WebTabPanel.this.isEnabled());

                String text = holder.getText();
                if (holder.getDisplayedMnemonic() > 0) {
                    final String mnemonic = Character.toString((char) holder.getDisplayedMnemonic());
                    link.add(new SimpleAttributeModifier("accesskey", mnemonic)); //$NON-NLS-1$
                    if (text != null && text.contains(mnemonic) && !HtmlUtils.hasUsefulHtmlContent(text)) {
                        StringBuffer sbBodyText = new StringBuffer(text);
                        int mnemonicIdx = sbBodyText.indexOf(mnemonic);
                        if (mnemonicIdx != -1) {
                            sbBodyText.insert(mnemonicIdx + 1, "</u>"); //$NON-NLS-1$
                            sbBodyText.insert(mnemonicIdx, "<u>"); //$NON-NLS-1$
                            text = sbBodyText.toString();
                        }
                    }
                }
                ServoyTabIcon tabIcon = new ServoyTabIcon("icon", holder, scriptable); //$NON-NLS-1$
                link.add(tabIcon);

                Label label = new Label("linktext", new Model<String>(text)); //$NON-NLS-1$
                label.setEscapeModelStrings(false);
                link.add(label);
                item.add(link);
                IModel<String> selectedOrDisabledClass = new AbstractReadOnlyModel<String>() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String getObject() {
                        if (!holder.isEnabled() || !WebTabPanel.this.isEnabled()) {
                            if (currentForm == holder.getPanel()) {
                                return "disabled_selected_tab"; //$NON-NLS-1$
                            }
                            return "disabled_tab"; //$NON-NLS-1$
                        } else {
                            if (currentForm == holder.getPanel()) {
                                return "selected_tab"; //$NON-NLS-1$
                            }
                            return "deselected_tab"; //$NON-NLS-1$
                        }
                    }
                };
                item.add(new AttributeModifier("class", true, selectedOrDisabledClass)); //$NON-NLS-1$
                label.add(new StyleAppendingModifier(new Model<String>() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String getObject() {
                        String style = "white-space: nowrap;"; //$NON-NLS-1$
                        if (foreground != null) {
                            style += " color:" + PersistHelper.createColorString(foreground); //$NON-NLS-1$
                        }
                        if (holder.getIcon() != null) {
                            style += "; padding-left: 3px"; //$NON-NLS-1$
                        }
                        return style;
                    }
                }));
            }
        });

        // All tab panels get their tabs rearranged after they make it to the browser.
        // On Chrome & Safari the tab rearrangement produces an ugly flicker effect, because
        // initially the tabs are not visible and then they are made visible. By
        // sending the tab as invisible and turning it to visible only after the tabs
        // are arranged, this jumping/flickering effect is gone. However a small delay can now be
        // noticed in Chrome & Safari, which should also be eliminated somehow.
        // The tab panel is set to visible in function "rearrageTabsInTabPanel" from "servoy.js".
        add(new StyleAppendingModifier(new Model<String>() {
            private static final long serialVersionUID = 1L;

            @Override
            public String getObject() {
                return "visibility: hidden;overflow:hidden"; //$NON-NLS-1$
            }
        }));

        add(new AbstractServoyDefaultAjaxBehavior() {

            @Override
            protected void respond(AjaxRequestTarget target) {
            }

            @Override
            public void renderHead(IHeaderResponse response) {
                super.renderHead(response);
                boolean dontRearrangeHere = false;

                if (!(getRequestCycle().getRequestTarget() instanceof AjaxRequestTarget)
                        && Utils.getAsBoolean(((MainPage) getPage()).getController().getApplication()
                                .getRuntimeProperties().get("enableAnchors"))) //$NON-NLS-1$
                {
                    Component parentForm = getParent();
                    while ((parentForm != null) && !(parentForm instanceof WebForm))
                        parentForm = parentForm.getParent();
                    if (parentForm != null) {
                        int anch = ((WebForm) parentForm).getAnchors(WebTabPanel.this.getMarkupId());
                        if (anch != 0 && anch != IAnchorConstants.DEFAULT)
                            dontRearrangeHere = true;
                    }
                }
                if (!dontRearrangeHere) {
                    String jsCall = "rearrageTabsInTabPanel('" + WebTabPanel.this.getMarkupId() + "');"; //$NON-NLS-1$ //$NON-NLS-2$
                    // Safari and Konqueror have some problems with the "domready" event, so for those
                    // browsers we'll use the "load" event. Otherwise use "domready", it reduces the flicker
                    // effect when rearranging the tabs.
                    ClientProperties clp = ((WebClientInfo) Session.get().getClientInfo()).getProperties();
                    if (clp.isBrowserKonqueror() || clp.isBrowserSafari())
                        response.renderOnLoadJavascript(jsCall);
                    else
                        response.renderOnDomReadyJavascript(jsCall);
                }
            }

            @Override
            public boolean isEnabled(Component component) {
                return WebClientSession.get().useAjax();
            }

        });
    }
    add(StyleAttributeModifierModel.INSTANCE);
    add(TooltipAttributeModifier.INSTANCE);
    this.scriptable = scriptable;
    ((ChangesRecorder) scriptable.getChangesRecorder()).setDefaultBorderAndPadding(null,
            TemplateGenerator.DEFAULT_LABEL_PADDING);
}

From source file:com.servoy.j2db.server.headlessclient.MainPage.java

License:Open Source License

@SuppressWarnings("nls")
private void init(WebClient sc) {
    setStatelessHint(false);//  w w  w.  ja  va  2 s . c  om
    client = sc;
    webForms = new ArrayList<IFormUIInternal<?>>();

    title = new Label("title", new Model<String>("Servoy Web Client")); //$NON-NLS-1$ //$NON-NLS-2$
    title.setOutputMarkupId(true);
    add(title);

    useAJAX = Utils.getAsBoolean(client.getRuntimeProperties().get("useAJAX")); //$NON-NLS-1$
    int dataNotifyFrequency = Utils
            .getAsInteger(sc.getSettings().getProperty("servoy.webclient.datanotify.frequency", "5")); //$NON-NLS-1$  //$NON-NLS-2$
    if (dataNotifyFrequency > 0 && useAJAX) {
        add(new AbstractAjaxTimerBehavior(Duration.seconds(dataNotifyFrequency)) {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onTimer(AjaxRequestTarget target) {
                if (isServoyEnabled() && !client.getFlattenedSolution().isInDesign(null)
                        && String.valueOf(MainPage.this.getCurrentVersionNumber())
                                .equals(RequestCycle.get().getRequest().getParameter("pvs"))) {
                    WebEventExecutor.generateResponse(target, MainPage.this);
                }
            }

            @Override
            public void renderHead(IHeaderResponse response) {
                if (isServoyEnabled()) {
                    super.renderHead(response);

                    String jsTimerScript = getJsTimeoutCall(getUpdateInterval());
                    response.renderJavascript("function restartTimer() {" + jsTimerScript + "}", //$NON-NLS-1$//$NON-NLS-2$
                            "restartTimer"); //$NON-NLS-1$
                }
            }

            @Override
            protected CharSequence getPreconditionScript() {
                return "onAjaxCall(); if(Servoy.DD.isDragging) Servoy.DD.isRestartTimerNeeded=true; return !Servoy.DD.isDragging && !Servoy.redirectingOnSolutionClose;"; //$NON-NLS-1$
            }

            @Override
            protected CharSequence getFailureScript() {
                return "onAjaxError();restartTimer();"; //$NON-NLS-1$
            }

            @Override
            protected CharSequence getCallbackScript() {
                // if it is not enabled then just return an empty function. so that the timer stops.
                if (isServoyEnabled()) {
                    return generateCallbackScript("wicketAjaxGet('" + //$NON-NLS-1$
                    getCallbackUrl(onlyTargetActivePage()) + "&ignoremp=true&pvs=" //$NON-NLS-1$
                            + MainPage.this.getCurrentVersionNumber() + "'");
                }
                return "Servoy.Utils.nop()";
            }

            @Override
            public CharSequence getCallbackUrl(boolean onlyTargetActivePage) {
                if (getComponent() == null) {
                    throw new IllegalArgumentException(
                            "Behavior must be bound to a component to create the URL"); //$NON-NLS-1$
                }
                return getComponent().urlFor(this, AlwaysLastPageVersionRequestListenerInterface.INTERFACE);
            }

            @Override
            protected String findIndicatorId() {
                return null; // main page defines it and the timer shouldnt show it
            }

            /*
             * this can't be isEnabled(component) of the behavior itself because IE8 will constant call this on closed (modal)windows. So then this is
             * marked as disabled and an AbortException is thrown what our code sees as a server error and will constantly restart the timer.
             */
            private boolean isServoyEnabled() {
                return ((getController() != null && getController().isFormVisible()) || closingAsWindow);
            }

        });

    }
    add(new TriggerOrientationChangeAjaxBehavior());
    add(new TriggerResizeAjaxBehavior());

    add(new AbstractServoyLastVersionAjaxBehavior() {
        @Override
        protected void execute(AjaxRequestTarget target) {
            for (ServoyDivDialog divDialog : divDialogs.getOrderedByOpenSequence()) {
                if (!divDialog.isShown()) {
                    // this means a refresh was probably triggered and we must re-show these... because we do not keep closed dialogs in divDialogs
                    int x = divDialog.getX();
                    int y = divDialog.getY();
                    int w = divDialog.getWidth();
                    int h = divDialog.getHeight();
                    divDialog.show(target, null);
                    divDialog.setBounds(target, x, y, w, h, null);
                }
            }
            WebEventExecutor.generateResponse(target, MainPage.this);
        }

        @Override
        public void renderHead(IHeaderResponse response) {
            super.renderHead(response);
            response.renderOnDomReadyJavascript(getCallbackScript(true).toString());
        }

        @Override
        public boolean isEnabled(Component component) {
            return divDialogs.size() > 0 && super.isEnabled(component);
        }
    });

    body = new WebMarkupContainer("servoy_page") //$NON-NLS-1$
    {
        private static final long serialVersionUID = 1L;

        /**
         * @see org.apache.wicket.Component#onComponentTag(org.apache.wicket.markup.ComponentTag)
         */
        @Override
        protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);
            tag.putAll(bodyAttributes);
        }
    };
    body.add(new AttributeModifier("dir", true, new AbstractReadOnlyModel<String>() //$NON-NLS-1$
    {

        @Override
        public String getObject() {
            String value = AttributeModifier.VALUELESS_ATTRIBUTE_REMOVE;
            Locale l = client.getLocale();
            Solution solution = client.getSolution();

            if (solution != null && l != null) {
                value = OrientationApplier.getHTMLContainerOrientation(l, solution.getTextOrientation());
            }
            return value;
        }
    }));

    add(body);
    pageContributor = new PageContributor(client, "contribution");
    body.add(pageContributor);

    Label loadingIndicator = new Label("loading_indicator", sc.getI18NMessage("servoy.general.loading"));
    loadingIndicator.add(new SimpleAttributeModifier("style", "display:none;"));

    body.add(loadingIndicator);
    divDialogsParent = new WebMarkupContainer(DIV_DIALOGS_REPEATER_PARENT_ID);
    divDialogsParent.setOutputMarkupPlaceholderTag(true);
    divDialogsParent.setVisible(false);
    body.add(divDialogsParent);

    if (useAJAX) {
        add(new TriggerUpdateAjaxBehavior()); // for when another page needs to trigger an ajax update on this page using js (see media upload)

        divDialogRepeater = new RepeatingView(DIV_DIALOG_REPEATER_ID);
        divDialogsParent.add(divDialogRepeater);

        fileUploadWindow = new ServoyDivDialog(FILE_UPLOAD_DIALOG_ID);
        body.add(fileUploadWindow);
        fileUploadWindow.setModal(true);
        fileUploadWindow.setPageMapName(null);
        fileUploadWindow.setCookieName("dialog_fileupload");
        fileUploadWindow.setResizable(true);
        fileUploadWindow.setInitialHeight(150);
        fileUploadWindow.setInitialWidth(400);
        fileUploadWindow.setMinimalHeight(130);
        fileUploadWindow.setMinimalWidth(400);
        fileUploadWindow.setUseInitialHeight(true); // no effect, can be removed
        fileUploadWindow.setPageCreator(new ModalWindow.PageCreator() {
            private static final long serialVersionUID = 1L;

            public Page createPage() {
                return new MediaUploadPage(PageMap.forName(FILE_UPLOAD_PAGEMAP), mediaUploadCallback,
                        mediaUploadMultiSelect, getController().getApplication());
            }
        });
        fileUploadWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
            private static final long serialVersionUID = 1L;

            public void onClose(AjaxRequestTarget target) {
                divDialogs.remove(FILE_UPLOAD_PAGEMAP);
                fileUploadWindow.setPageMapName(null);
                fileUploadWindow.remove(fileUploadWindow.getContentId());
                restoreFocusedComponentInParentIfNeeded();
                WebEventExecutor.generateResponse(target, findPage());
            }
        });
    } else {
        divDialogsParent.add(new Label("divdialogs"));
        body.add(new Label("fileuploaddialog")); //$NON-NLS-1$
    }

    IModel<String> styleHrefModel = new AbstractReadOnlyModel<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            if (main != null) {
                return getRequest().getRelativePathPrefixToContextRoot() + "servoy-webclient/templates/" + //$NON-NLS-1$
                client.getClientProperty(WEBCONSTANTS.WEBCLIENT_TEMPLATES_DIR)
                        + "/servoy_web_client_default.css"; //$NON-NLS-1$
            }
            return null;
        }
    };
    Label main_form_style = new Label("main_form_style"); //$NON-NLS-1$
    main_form_style.add(new AttributeModifier("href", true, styleHrefModel)); //$NON-NLS-1$
    add(main_form_style);

    IModel<List<IFormUIInternal<?>>> loopModel = new AbstractReadOnlyModel<List<IFormUIInternal<?>>>() {
        private static final long serialVersionUID = 1L;

        @Override
        public List<IFormUIInternal<?>> getObject() {
            return webForms;
        }
    };

    listview = new ListView<IFormUIInternal<?>>("forms", loopModel) //$NON-NLS-1$
    {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<IFormUIInternal<?>> item) {
            final WebForm form = (WebForm) item.getModelObject();
            tempRemoveMainForm = true;
            try {
                if (form.getParent() != null) {
                    form.remove(); // TODO isn't this already done by item.add(form) below in wicket's impl?
                }
                item.add(form);
            } finally {
                tempRemoveMainForm = false;
            }

            IFormLayoutProvider layoutProvider = FormLayoutProviderFactory.getFormLayoutProvider(client,
                    client.getSolution(), form.getController().getForm(), form.getController().getName());

            TextualStyle styleToReturn = null;

            if ((navigator != null) && (form == navigator.getFormUI())) {
                styleToReturn = layoutProvider.getLayoutForForm(navigator.getForm().getSize().width, true,
                        false);
            } else if (form == main) {
                int customNavWidth = 0;
                if (navigator != null)
                    customNavWidth = navigator.getForm().getSize().width;
                styleToReturn = layoutProvider.getLayoutForForm(customNavWidth, false, false);
            }
            if (styleToReturn != null) {
                form.add(new StyleAppendingModifier(styleToReturn) {
                    @Override
                    public boolean isEnabled(Component component) {
                        // Laurian: looks like bogus condition, shouldn't this be || as in WebForm ?
                        return (component.findParent(WebTabPanel.class) == null)
                                && (component.findParent(WebSplitPane.class) == null);
                    }
                });
            }
            TabIndexHelper.setUpTabIndexAttributeModifier(item, ISupportWebTabSeq.SKIP);
        }

        @Override
        protected ListItem<IFormUIInternal<?>> newItem(final int index) {
            return new ListItem<IFormUIInternal<?>>(index, getListItemModel(getModel(), index)) {
                @Override
                public void remove(Component component) {
                    super.remove(component);
                    // for example when a form is shown in a popup form (window plugin) it must know that it's main page changed
                    if (!tempRemoveMainForm && component instanceof WebForm) {
                        WebForm formUI = ((WebForm) component);
                        if (MainPage.this == formUI.getMainPage()) {
                            // if the form is visible and it will be now removed from the mainpage
                            // then call notifyVisble false on it to let the form know it will hide
                            // we can't do much if that is blocked by an onhide here.
                            // (could be triggered by a browser back button)
                            if (formUI.getController().isFormVisible()) {
                                List<Runnable> invokeLaterRunnables = new ArrayList<Runnable>();
                                formUI.getController().notifyVisible(false, invokeLaterRunnables);
                                Utils.invokeLater(client, invokeLaterRunnables);
                            }
                            formUI.setMainPage(null);
                        }
                    }
                }
            };
        }

        /**
         * @see org.apache.wicket.markup.html.list.ListView#onBeforeRender()
         */
        @Override
        protected void onBeforeRender() {
            super.onBeforeRender();
            // now first initialize all the tabs so that data from
            // tab x doesn't change anymore (so that it could alter data in tab y)
            // don't know if this still does anything because we need to do it
            // in the onBeforeRender of WebTabPanel itself, else tableviews don't have there models yet..
            visitChildren(WebTabPanel.class, new IVisitor<WebTabPanel>() {
                public Object component(WebTabPanel wtp) {
                    wtp.initalizeFirstTab();
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });

            addWebAnchoringInfoIfNeeded();
        }
    };
    listview.setReuseItems(true);
    // if versioning is disabled then table views can go wrong (don't rollback on a submit)
    //listview.setVersioned(false);

    Form form = new ServoyForm("servoy_dataform"); //$NON-NLS-1$

    form.add(new SimpleAttributeModifier("autocomplete", "off")); //$NON-NLS-1$ //$NON-NLS-2$
    if (useAJAX)
        form.add(new SimpleAttributeModifier("onsubmit", "return false;")); //$NON-NLS-1$ //$NON-NLS-2$

    form.add(listview);
    WebMarkupContainer defaultButton = new WebMarkupContainer("defaultsubmitbutton", new Model()); //$NON-NLS-1$
    defaultButton.setVisible(!useAJAX);
    form.add(defaultButton);

    StylePropertyChangeMarkupContainer container = new StylePropertyChangeMarkupContainer("externaldivsparent");
    form.add(container);
    PageContributorRepeatingView repeatingView = new PageContributorRepeatingView("externaldivs", container);
    container.add(repeatingView);
    pageContributor.addRepeatingView(repeatingView);

    body.add(form);
}

From source file:com.ttdev.wicketpagetest.sample.spring.PageRefreshingTR.java

License:Open Source License

public PageRefreshingTR() {
    values = Arrays.asList(new Integer[] { 0, 0, 0 });
    ListView<Integer> eachRow = new ListView<Integer>("eachRow", values) {

        private static final long serialVersionUID = 1L;

        @Override/*  ww  w  .j a v  a2  s  . c  o  m*/
        protected void populateItem(final ListItem<Integer> item) {
            item.setOutputMarkupId(true);
            item.add(new Label("count", new AbstractReadOnlyModel<Integer>() {

                private static final long serialVersionUID = 1L;

                @Override
                public Integer getObject() {
                    return getRowCount(item);
                }

            }));
            item.add(new Label("sum", new AbstractReadOnlyModel<Integer>() {

                private static final long serialVersionUID = 1L;

                @Override
                public Integer getObject() {
                    Integer c = getRowCount(item);
                    int sum = 0;
                    for (int i = 0; i <= c; i++) {
                        sum += i;
                    }
                    return sum;
                }
            }));
            item.add(new AjaxLink<Void>("inc") {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    values.set(item.getIndex(), getRowCount(item) + 1);
                    target.add(item);
                }
            });
        }
    };
    add(eachRow);
}

From source file:com.ttdev.wicketpagetest.sample.spring.PalettePage.java

License:Open Source License

public PalettePage() {
    Form<Void> f = new Form<Void>("f") {
        private static final long serialVersionUID = 1L;

        @Override//from  w  ww .ja va2  s  . co m
        protected void onSubmit() {
            for (Product p : selectedProducts) {
                ps.delete(p);
            }
        }
    };
    add(f);
    selectedProducts = new ArrayList<Product>();
    final List<Product> availableProducts = ps.getAll();
    Palette<Product> palette = new Palette<Product>("palette",
            new PropertyModel<List<Product>>(this, "selectedProducts"),
            new AbstractReadOnlyModel<List<Product>>() {

                private static final long serialVersionUID = 1L;

                @Override
                public List<Product> getObject() {
                    return availableProducts;
                }

            }, new ChoiceRenderer<Product>("name", "id"), 3, true);
    f.add(palette);
}

From source file:com.ttdev.wicketpagetest.sample.spring.ThrottlingAjaxPage.java

License:Open Source License

public ThrottlingAjaxPage() {
    TextField<String> inputField = new TextField<String>("input", new PropertyModel<String>(this, "input"));
    add(inputField);//w  ww .  j  a va  2s .co m
    AjaxFormComponentUpdatingBehavior onkeyupBehavior = new AjaxFormComponentUpdatingBehavior("onkeyup") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.add(outputLabel);
        }
    };
    inputField.add(onkeyupBehavior);
    outputLabel = new Label("output", new AbstractReadOnlyModel<Integer>() {

        private static final long serialVersionUID = 1L;

        @Override
        public Integer getObject() {
            return input.length();
        }
    });
    add(outputLabel);
    outputLabel.setOutputMarkupId(true);
}

From source file:com.userweave.application.ModuleConfigurationContainer.java

License:Open Source License

public void setCounterDisplayModels() {

    if (counterDisplay != null) {

        counterDisplay.setModuleConfigurationDescriptionModel(new AbstractReadOnlyModel() {

            @Override//from  w  w  w .  ja v  a2s  . c o m
            public Object getObject() {
                LocalizedString activeConfigurationDescription = getActiveConfigurationDescription();
                if (activeConfigurationDescription != null) {
                    return LocalizationUtils.getValue(activeConfigurationDescription, getLocale());
                } else {
                    return null;
                }
            }
        });

        counterDisplay.setCountModel(new AbstractReadOnlyModel() {

            @Override
            public Object getObject() {
                if (configurationAvailable()) {
                    return new Integer(configurationIndex + 1);
                } else {
                    return new Integer(0);
                }
            }
        });

        counterDisplay.setMaxCountModel(new AbstractReadOnlyModel() {

            @Override
            public Object getObject() {
                return new Integer(configurations.size());
            }
        });

        counterDisplay.setPercentCountModel(new AbstractReadOnlyModel() {

            @Override
            public Object getObject() {

                float percent = (float) (configurationIndex + 1) / (float) configurations.size() * 100;

                return new String((int) percent + " %");
            }
        });
    }
}

From source file:com.userweave.pages.components.slidableajaxtabpanel.SlidableAjaxTabbedPanel.java

License:Open Source License

/**
 * Initializes this panel with the tabs.
 *///from   ww  w  .  j av a 2s  . c  o  m
private void init() {
    int sizeOfTabList = this.tabs.size();

    if (sizeOfTabList == 0) {
        updateDisplayTabList(tabs, DIR_LEFT);
    } else if (sizeOfTabList < displaySize) {
        updateDisplayTabList(tabs.subList(leftIndex, sizeOfTabList), DIR_LEFT);
    } else {
        updateDisplayTabList(tabs.subList(leftIndex, displaySize), DIR_LEFT);
    }

    setOutputMarkupId(true);

    setVersioned(false);

    createAndAddSliders();

    /*
     * Container class for the tabs in the markup.
     */
    WebMarkupContainer tabsContainer = new WebMarkupContainer("tabs-container") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);
            tag.put("class", getTabContainerCssClass());
        }
    };

    tabsContainer.setOutputMarkupId(true);

    add(tabsContainer);

    /*
     * Model for the Loop class which populates this panel.
     */
    final IModel tabCount = new AbstractReadOnlyModel() {
        private static final long serialVersionUID = 1L;

        @Override
        public Object getObject() {
            return new Integer(SlidableAjaxTabbedPanel.this.displayTabList.size());
        }
    };

    /*
     * Populate this panel with tabs.
     */
    //      tabsContainer.add(getLoop("tabs", tabCount));
}