Search in sources :

Example 6 with IFieldComponent

use of com.servoy.j2db.ui.IFieldComponent in project servoy-client by Servoy.

the class WebEventExecutor method setRightClickCmd.

@Override
public void setRightClickCmd(String id, Object[] args) {
    if (id != null && useAJAX) {
        if (component instanceof ILabel || component instanceof IFieldComponent || component instanceof SortableCellViewHeader) {
            String sharedName = "Cmd";
            if (component instanceof SortableCellViewHeader) {
                sharedName = null;
            }
            component.add(new // $NON-NLS-1$
            ServoyAjaxEventBehavior(// $NON-NLS-1$
            "oncontextmenu", // $NON-NLS-1$
            sharedName, // $NON-NLS-1$
            true) {

                @Override
                protected void onEvent(AjaxRequestTarget target) {
                    WebEventExecutor.this.onEvent(JSEvent.EventType.rightClick, target, component, Utils.getAsInteger(RequestCycle.get().getRequest().getParameter(IEventExecutor.MODIFIERS_PARAMETER)), new // $NON-NLS-1$
                    Point(// $NON-NLS-1$
                    Utils.getAsInteger(RequestCycle.get().getRequest().getParameter("mx")), // $NON-NLS-1$
                    Utils.getAsInteger(RequestCycle.get().getRequest().getParameter("my"))), new Point(Utils.getAsInteger(RequestCycle.get().getRequest().getParameter("glx")), // $NON-NLS-1$
                    Utils.getAsInteger(RequestCycle.get().getRequest().getParameter("gly"))));
                }

                @Override
                protected CharSequence generateCallbackScript(final CharSequence partialCall) {
                    return super.generateCallbackScript(// $NON-NLS-1$
                    partialCall + "+Servoy.Utils.getActionParams(event," + ((component instanceof SortableCellViewHeader) ? "true" : "false") + ")");
                }

                @Override
                public boolean isEnabled(Component comp) {
                    if (super.isEnabled(comp)) {
                        if (comp instanceof IScriptableProvider && ((IScriptableProvider) comp).getScriptObject() instanceof IRuntimeComponent) {
                            // $NON-NLS-1$
                            Object oe = ((IRuntimeComponent) ((IScriptableProvider) comp).getScriptObject()).getClientProperty("ajax.enabled");
                            if (oe != null)
                                return Utils.getAsBoolean(oe);
                        }
                        return true;
                    }
                    return false;
                }

                // We need to return false, otherwise the context menu of the browser is displayed.
                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    return new AjaxCallDecorator() {

                        @Override
                        public CharSequence decorateScript(CharSequence script) {
                            // $NON-NLS-1$
                            return script + " return false;";
                        }
                    };
                }
            });
        }
    }
    super.setRightClickCmd(id, args);
}
Also used : IAjaxCallDecorator(org.apache.wicket.ajax.IAjaxCallDecorator) AjaxCallDecorator(org.apache.wicket.ajax.calldecorator.AjaxCallDecorator) IAjaxCallDecorator(org.apache.wicket.ajax.IAjaxCallDecorator) ILabel(com.servoy.j2db.ui.ILabel) Point(java.awt.Point) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) CloseableAjaxRequestTarget(com.servoy.j2db.server.headlessclient.CloseableAjaxRequestTarget) IRuntimeComponent(com.servoy.j2db.ui.runtime.IRuntimeComponent) IFieldComponent(com.servoy.j2db.ui.IFieldComponent) IComponent(com.servoy.j2db.ui.IComponent) IFieldComponent(com.servoy.j2db.ui.IFieldComponent) Component(org.apache.wicket.Component) FormComponent(org.apache.wicket.markup.html.form.FormComponent) IRuntimeComponent(com.servoy.j2db.ui.runtime.IRuntimeComponent) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider)

Example 7 with IFieldComponent

use of com.servoy.j2db.ui.IFieldComponent in project servoy-client by Servoy.

the class WebClientsApplication method init.

/**
 * @see wicket.protocol.http.WebApplication#init()
 */
@Override
protected void init() {
    // TODO this is a workaround to allow mobile test client that only starts Tomcat not to give exceptions (please remove if mobile test client initialises a full app. server in the future)
    if (ApplicationServerRegistry.get() == null)
        return;
    getResourceSettings().setResourceWatcher(new ServoyModificationWatcher(Duration.seconds(5)));
    // getResourceSettings().setResourcePollFrequency(Duration.seconds(5));
    getResourceSettings().setAddLastModifiedTimeToResourceReferenceUrl(true);
    getResourceSettings().setDefaultCacheDuration((int) Duration.days(365).seconds());
    getMarkupSettings().setCompressWhitespace(true);
    getMarkupSettings().setMarkupCache(new ServoyMarkupCache(this));
    // getMarkupSettings().setStripWicketTags(true);
    getResourceSettings().setResourceStreamLocator(new ServoyResourceStreamLocator(this));
    getResourceSettings().setPackageResourceGuard(new ServoyPackageResourceGuard());
    // getResourceSettings().setResourceFinder(createResourceFinder());
    getResourceSettings().setThrowExceptionOnMissingResource(false);
    getApplicationSettings().setPageExpiredErrorPage(ServoyExpiredPage.class);
    getApplicationSettings().setClassResolver(new ServoyClassResolver());
    getSessionSettings().setMaxPageMaps(15);
    // getRequestCycleSettings().setGatherExtendedBrowserInfo(true);
    getSecuritySettings().setCryptFactory(new CachingKeyInSessionSunJceCryptFactory());
    Settings settings = Settings.getInstance();
    // $NON-NLS-1$ //$NON-NLS-2$
    getDebugSettings().setOutputComponentPath(Utils.getAsBoolean(settings.getProperty("servoy.webclient.debug.wicketpath", "false")));
    if (// $NON-NLS-1$ //$NON-NLS-2$
    Utils.getAsBoolean(settings.getProperty("servoy.webclient.nice.urls", "false"))) {
        // $NON-NLS-1$
        mount(new HybridUrlCodingStrategy("/solutions", SolutionLoader.class));
        // $NON-NLS-1$
        mount(new HybridUrlCodingStrategy("/application", MainPage.class));
        mount(new // $NON-NLS-1$
        HybridUrlCodingStrategy(// $NON-NLS-1$
        "/ss", // $NON-NLS-1$
        SolutionLoader.class) {

            /**
             * @see wicket.request.target.coding.BookmarkablePageRequestTargetUrlCodingStrategy#matches(wicket.IRequestTarget)
             */
            @Override
            public boolean matches(IRequestTarget requestTarget) {
                return false;
            }
        });
    } else {
        // $NON-NLS-1$
        mountBookmarkablePage("/solutions", SolutionLoader.class);
        mount(new // $NON-NLS-1$
        BookmarkablePageRequestTargetUrlCodingStrategy(// $NON-NLS-1$
        "/ss", // $NON-NLS-1$
        SolutionLoader.class, // $NON-NLS-1$
        null) {

            /**
             * @see wicket.request.target.coding.BookmarkablePageRequestTargetUrlCodingStrategy#matches(wicket.IRequestTarget)
             */
            @Override
            public boolean matches(IRequestTarget requestTarget) {
                return false;
            }
        });
    }
    // $NON-NLS-1$ //$NON-NLS-2$
    long maxSize = Utils.getAsLong(settings.getProperty("servoy.webclient.maxuploadsize", "0"), false);
    if (maxSize > 0) {
        getApplicationSettings().setDefaultMaximumUploadSize(Bytes.kilobytes(maxSize));
    }
    // $NON-NLS-1$
    getSharedResources().putClassAlias(IApplication.class, "application");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(PageContributor.class, "pc");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(MaskBehavior.class, "mask");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(Application.class, "servoy");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(org.wicketstuff.calendar.markup.html.form.DatePicker.class, "datepicker");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(YUILoader.class, "yui");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(JQueryLoader.class, "jquery");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(TinyMCELoader.class, "tinymce");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(org.apache.wicket.markup.html.WicketEventReference.class, "wicketevent");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(org.apache.wicket.ajax.WicketAjaxReference.class, "wicketajax");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(MainPage.class, "servoyjs");
    // $NON-NLS-1$
    getSharedResources().putClassAlias(org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.class, "modalwindow");
    // $NON-NLS-1$
    PackageResource.bind(this, IApplication.class, "images/open_project.gif");
    // $NON-NLS-1$
    PackageResource.bind(this, IApplication.class, "images/save.gif");
    // $NON-NLS-1$//$NON-NLS-2$
    mountSharedResource("/formcss", "servoy/formcss");
    sharedMediaResource = new SharedMediaResource();
    // $NON-NLS-1$
    getSharedResources().add("media", sharedMediaResource);
    mount(new // $NON-NLS-1$ //$NON-NLS-2$
    SharedResourceRequestTargetUrlCodingStrategy(// $NON-NLS-1$ //$NON-NLS-2$
    "mediafolder", // $NON-NLS-1$ //$NON-NLS-2$
    "servoy/media") {

        @Override
        protected void appendParameters(AppendingStringBuffer url, Map<String, ?> parameters) {
            if (parameters != null && parameters.size() > 0) {
                // $NON-NLS-1$
                Object solutionName = parameters.get("s");
                if (solutionName != null)
                    appendPathParameter(url, null, solutionName.toString());
                // $NON-NLS-1$
                Object resourceId = parameters.get("id");
                if (resourceId != null)
                    appendPathParameter(url, null, resourceId.toString());
                StringBuilder queryParams = new StringBuilder();
                for (Entry<?, ?> entry1 : parameters.entrySet()) {
                    Object value = ((Entry<?, ?>) entry1).getValue();
                    if (value != null) {
                        Object key = ((Entry<?, ?>) entry1).getKey();
                        if (// $NON-NLS-1$ //$NON-NLS-2$
                        !"s".equals(key) && !"id".equals(key)) {
                            if (value instanceof String[]) {
                                String[] values = (String[]) value;
                                for (String value1 : values) {
                                    // $NON-NLS-1$
                                    if (queryParams.length() > 0)
                                        queryParams.append("&");
                                    // $NON-NLS-1$
                                    queryParams.append(key).append("=").append(value1);
                                }
                            } else {
                                // $NON-NLS-1$
                                if (queryParams.length() > 0)
                                    queryParams.append("&");
                                // $NON-NLS-1$
                                queryParams.append(key).append("=").append(value);
                            }
                        }
                    }
                }
                if (queryParams.length() > 0) {
                    // $NON-NLS-1$
                    url.append("?").append(queryParams);
                }
            }
        }

        @Override
        protected void appendPathParameter(AppendingStringBuffer url, String key, String value) {
            String escapedValue = value;
            // $NON-NLS-1$
            String[] values = escapedValue.split("/");
            if (values.length > 1) {
                StringBuilder sb = new StringBuilder(escapedValue.length());
                for (String str : values) {
                    sb.append(urlEncodePathComponent(str));
                    sb.append('/');
                }
                sb.setLength(sb.length() - 1);
                escapedValue = sb.toString();
            } else {
                escapedValue = urlEncodePathComponent(escapedValue);
            }
            if (!Strings.isEmpty(escapedValue)) {
                if (// $NON-NLS-1$
                !url.endsWith("/")) {
                    // $NON-NLS-1$
                    url.append("/");
                }
                // $NON-NLS-1$
                if (key != null)
                    url.append(urlEncodePathComponent(key)).append("/");
                url.append(escapedValue);
            }
        }

        /*
			 * (non-Javadoc)
			 * 
			 * @see org.apache.wicket.request.target.coding.AbstractRequestTargetUrlCodingStrategy#decodeParameters(java.lang.String, java.util.Map)
			 */
        @Override
        protected ValueMap decodeParameters(String urlFragment, Map<String, ?> urlParameters) {
            ValueMap map = new ValueMap();
            // $NON-NLS-1$
            final String[] pairs = urlFragment.split("/");
            if (pairs.length > 1) {
                // $NON-NLS-1$
                map.add("s", pairs[1]);
                StringBuffer sb = new StringBuffer();
                for (int i = 2; i < pairs.length; i++) {
                    sb.append(pairs[i]);
                    // $NON-NLS-1$
                    sb.append("/");
                }
                sb.setLength(sb.length() - 1);
                // $NON-NLS-1$
                map.add("id", sb.toString());
            }
            if (urlParameters != null) {
                map.putAll(urlParameters);
            }
            return map;
        }
    });
    // $NON-NLS-1$
    getSharedResources().add("resources", new ServeResources());
    // $NON-NLS-1$
    getSharedResources().add("formcss", new FormCssResource(this));
    if (// $NON-NLS-1$
    settings.getProperty("servoy.webclient.error.page", null) != null) {
        getApplicationSettings().setInternalErrorPage(ServoyErrorPage.class);
    }
    if (// $NON-NLS-1$
    settings.getProperty("servoy.webclient.pageexpired.page", null) != null) {
        getApplicationSettings().setPageExpiredErrorPage(ServoyPageExpiredPage.class);
    }
    addPreComponentOnBeforeRenderListener(new IComponentOnBeforeRenderListener() {

        public void onBeforeRender(Component component) {
            if (component instanceof IServoyAwareBean) {
                IModel model = component.getInnermostModel();
                WebForm webForm = component.findParent(WebForm.class);
                if (model instanceof RecordItemModel && webForm != null) {
                    IRecord record = (IRecord) ((RecordItemModel) model).getObject();
                    FormScope fs = webForm.getController().getFormScope();
                    if (record != null && fs != null) {
                        ((IServoyAwareBean) component).setSelectedRecord(new ServoyBeanState(record, fs));
                    }
                }
            } else if (!(component.getParent() instanceof WebDataCompositeTextField)) {
                if (!component.isEnabled()) {
                    boolean hasOnRender = (component instanceof IFieldComponent && ((IFieldComponent) component).getScriptObject() instanceof ISupportOnRenderCallback && ((ISupportOnRenderCallback) ((IFieldComponent) component).getScriptObject()).getRenderEventExecutor().hasRenderCallback());
                    if (!hasOnRender) {
                        // onrender may change the enable state
                        return;
                    }
                }
                Component targetComponent = null;
                boolean hasFocus = false, hasBlur = false;
                if (component instanceof IFieldComponent && ((IFieldComponent) component).getEventExecutor() != null) {
                    if (component instanceof WebDataCompositeTextField && ((WebDataCompositeTextField) component).getDelegate() instanceof Component) {
                        targetComponent = (Component) ((WebDataCompositeTextField) component).getDelegate();
                    } else {
                        targetComponent = component;
                    }
                    if (component instanceof WebBaseSelectBox) {
                        Component[] cs = ((WebBaseSelectBox) component).getFocusChildren();
                        if (cs != null && cs.length == 1)
                            targetComponent = cs[0];
                    }
                    if (component instanceof WebDataHtmlArea)
                        hasFocus = true;
                    // always install a focus handler when in a table view to detect change of selectedIndex and test for record validation
                    if (((IFieldComponent) component).getEventExecutor().hasEnterCmds() || component.findParent(WebCellBasedView.class) != null || (((IFieldComponent) component).getScriptObject() instanceof ISupportOnRenderCallback && ((ISupportOnRenderCallback) ((IFieldComponent) component).getScriptObject()).getRenderEventExecutor().hasRenderCallback())) {
                        hasFocus = true;
                    }
                    // Always trigger event on focus lost:
                    // 1) check for new selected index, record validation may have failed preventing a index changed
                    // 2) prevent focus gained to be called when field validation failed
                    // 3) general ondata change
                    hasBlur = true;
                } else if (component instanceof WebBaseLabel) {
                    targetComponent = component;
                    hasFocus = true;
                }
                if (targetComponent != null) {
                    MainPage mainPage = targetComponent.findParent(MainPage.class);
                    if (mainPage.isUsingAjax()) {
                        AbstractAjaxBehavior eventCallback = mainPage.getPageContributor().getEventCallback();
                        if (eventCallback != null) {
                            String callback = eventCallback.getCallbackUrl().toString();
                            if (component instanceof WebDataRadioChoice || component instanceof WebDataCheckBoxChoice || component instanceof WebDataLookupField || component instanceof WebDataComboBox || component instanceof WebDataListBox || component instanceof WebDataHtmlArea || component instanceof WebDataCompositeTextField) {
                                // is updated via ServoyChoiceComponentUpdatingBehavior or ServoyFormComponentUpdatingBehavior, this is just for events
                                callback += "&nopostdata=true";
                            }
                            for (IBehavior behavior : targetComponent.getBehaviors()) {
                                if (behavior instanceof EventCallbackModifier) {
                                    targetComponent.remove(behavior);
                                }
                            }
                            if (hasFocus) {
                                StringBuilder js = new StringBuilder();
                                // $NON-NLS-1$ //$NON-NLS-2$
                                js.append("eventCallback(this,'focus','").append(callback).append("',event)");
                                // $NON-NLS-1$
                                targetComponent.add(new EventCallbackModifier("onfocus", true, new Model<String>(js.toString())));
                                // $NON-NLS-1$ //$NON-NLS-2$
                                targetComponent.add(new EventCallbackModifier("onmousedown", true, new Model<String>("focusMousedownCallback(event)")));
                            }
                            if (hasBlur) {
                                boolean blockRequest = false;
                                // if component has ondatachange, check for blockrequest
                                if (component instanceof ISupportEventExecutor && ((ISupportEventExecutor) component).getEventExecutor().hasChangeCmd()) {
                                    WebClientSession webClientSession = WebClientSession.get();
                                    blockRequest = webClientSession != null && webClientSession.blockRequest();
                                }
                                StringBuilder js = new StringBuilder();
                                // $NON-NLS-1$ //$NON-NLS-2$
                                js.append("postEventCallback(this,'blur','").append(callback).append("',event," + blockRequest + ")");
                                // $NON-NLS-1$
                                targetComponent.add(new EventCallbackModifier("onblur", true, new Model<String>(js.toString())));
                            }
                        }
                    }
                }
            }
        }
    });
}
Also used : ValueMap(org.apache.wicket.util.value.ValueMap) WebBaseSelectBox(com.servoy.j2db.server.headlessclient.dataui.WebBaseSelectBox) WebDataLookupField(com.servoy.j2db.server.headlessclient.dataui.WebDataLookupField) IRequestTarget(org.apache.wicket.IRequestTarget) Settings(com.servoy.j2db.util.Settings) IWiQuerySettings(org.odlabs.wiquery.core.commons.IWiQuerySettings) IRequestCycleSettings(org.apache.wicket.settings.IRequestCycleSettings) WiQuerySettings(org.odlabs.wiquery.core.commons.WiQuerySettings) WebDataCheckBoxChoice(com.servoy.j2db.server.headlessclient.dataui.WebDataCheckBoxChoice) WebBaseLabel(com.servoy.j2db.server.headlessclient.dataui.WebBaseLabel) WebDataCompositeTextField(com.servoy.j2db.server.headlessclient.dataui.WebDataCompositeTextField) IRecord(com.servoy.j2db.dataprocessing.IRecord) WebCellBasedView(com.servoy.j2db.server.headlessclient.dataui.WebCellBasedView) WebDataRadioChoice(com.servoy.j2db.server.headlessclient.dataui.WebDataRadioChoice) RecordItemModel(com.servoy.j2db.server.headlessclient.dataui.RecordItemModel) HybridUrlCodingStrategy(org.apache.wicket.request.target.coding.HybridUrlCodingStrategy) ISupportOnRenderCallback(com.servoy.j2db.ui.ISupportOnRenderCallback) ISupportEventExecutor(com.servoy.j2db.ui.ISupportEventExecutor) FormScope(com.servoy.j2db.scripting.FormScope) IPageMapEntry(org.apache.wicket.session.pagemap.IPageMapEntry) Entry(java.util.Map.Entry) IServoyAwareBean(com.servoy.j2db.dataui.IServoyAwareBean) IBehavior(org.apache.wicket.behavior.IBehavior) WebDataComboBox(com.servoy.j2db.server.headlessclient.dataui.WebDataComboBox) IFieldComponent(com.servoy.j2db.ui.IFieldComponent) Component(org.apache.wicket.Component) AbstractAjaxBehavior(org.apache.wicket.behavior.AbstractAjaxBehavior) AppendingStringBuffer(org.apache.wicket.util.string.AppendingStringBuffer) IModel(org.apache.wicket.model.IModel) WebDataListBox(com.servoy.j2db.server.headlessclient.dataui.WebDataListBox) IComponentOnBeforeRenderListener(org.apache.wicket.application.IComponentOnBeforeRenderListener) AppendingStringBuffer(org.apache.wicket.util.string.AppendingStringBuffer) ServoyBeanState(com.servoy.j2db.component.ServoyBeanState) WebDataHtmlArea(com.servoy.j2db.server.headlessclient.dataui.WebDataHtmlArea) IModel(org.apache.wicket.model.IModel) RecordItemModel(com.servoy.j2db.server.headlessclient.dataui.RecordItemModel) Model(org.apache.wicket.model.Model) IFieldComponent(com.servoy.j2db.ui.IFieldComponent)

Example 8 with IFieldComponent

use of com.servoy.j2db.ui.IFieldComponent in project servoy-client by Servoy.

the class MainPage method respond.

/**
 * Respond to focus/blur events.
 */
@SuppressWarnings("nls")
public void respond(AjaxRequestTarget target, final String event, final String markupId) {
    Component component = (Component) visitChildren(IComponent.class, new IVisitor<Component>() {

        public Object component(Component c) {
            Component targetComponent = c;
            if (c instanceof WebBaseSelectBox && ("blur".equals(event) || "focus".equals(event))) {
                Component[] cs = ((WebBaseSelectBox) c).getFocusChildren();
                if (cs != null && cs.length == 1)
                    targetComponent = cs[0];
            }
            if (targetComponent.getMarkupId().equals(markupId)) {
                return c;
            }
            return IVisitor.CONTINUE_TRAVERSAL;
        }
    });
    if (component == null) {
        // $NON-NLS-1$
        Debug.log("Component not found markupId " + markupId);
        return;
    }
    IFormUIInternal<?> formui = component.findParent(IFormUIInternal.class);
    if (formui != null && formui.isDesignMode()) {
        // $NON-NLS-1$
        Debug.log("Event ignored because of design mode");
        return;
    }
    if (component instanceof IFieldComponent) {
        WebEventExecutor eventExecutor = (WebEventExecutor) ((IFieldComponent) component).getEventExecutor();
        if (eventExecutor != null) {
            if ("focus".equals(event)) {
                int webModifier = Utils.getAsInteger(RequestCycle.get().getRequest().getParameter(IEventExecutor.MODIFIERS_PARAMETER));
                StartEditOnFocusGainedEventBehavior.startEditing(component, WebEventExecutor.convertModifiers(webModifier), target);
                eventExecutor.onEvent(JSEvent.EventType.focusGained, target, component, webModifier);
            } else if ("blur".equals(event)) {
                // test if the data is really posted by looking up the key.
                if (component instanceof FormComponent<?> && RequestCycle.get().getRequest().getParameter("nopostdata") == null) {
                    // changed data is posted
                    ((FormComponent<?>) component).processInput();
                }
                eventExecutor.onEvent(JSEvent.EventType.focusLost, target, component, IEventExecutor.MODIFIERS_UNSPECIFIED);
            } else {
                Debug.trace("Ignored event " + event);
            }
        } else {
            Debug.trace("Ignored event, no eventExecutor");
        }
    } else {
        // other non-field components like WebLabel
        ServoyForm form = component.findParent(ServoyForm.class);
        if (form != null) {
            // JS might change the page this form belongs to... so remember it now
            Page page = form.getPage();
            int webModifier = Utils.getAsInteger(RequestCycle.get().getRequest().getParameter(IEventExecutor.MODIFIERS_PARAMETER));
            WebEventExecutor.setSelectedIndex(component, target, WebEventExecutor.convertModifiers(webModifier), true);
            WebEventExecutor.generateResponse(target, page);
        }
    }
}
Also used : WebEventExecutor(com.servoy.j2db.server.headlessclient.dataui.WebEventExecutor) FormComponent(org.apache.wicket.markup.html.form.FormComponent) IComponent(com.servoy.j2db.ui.IComponent) WebPage(org.apache.wicket.markup.html.WebPage) Page(org.apache.wicket.Page) WebBaseSelectBox(com.servoy.j2db.server.headlessclient.dataui.WebBaseSelectBox) IFieldComponent(com.servoy.j2db.ui.IFieldComponent) IComponent(com.servoy.j2db.ui.IComponent) IFieldComponent(com.servoy.j2db.ui.IFieldComponent) Component(org.apache.wicket.Component) FormComponent(org.apache.wicket.markup.html.form.FormComponent) Point(java.awt.Point)

Example 9 with IFieldComponent

use of com.servoy.j2db.ui.IFieldComponent in project servoy-client by Servoy.

the class ComponentFactory method createField.

private static IComponent createField(IApplication application, Form form, Field field, IDataProviderLookup dataProviderLookup, IScriptExecuter el, boolean printing) {
    ValueList valuelist = application.getFlattenedSolution().getValueList(field.getValuelistID());
    ComponentFormat fieldFormat = ComponentFormat.getComponentFormat(field.getFormat(), field.getDataProviderID(), dataProviderLookup, application);
    IDataProvider dp = null;
    if (field.getDataProviderID() != null && dataProviderLookup != null) {
        try {
            dp = dataProviderLookup.getDataProvider(field.getDataProviderID());
        } catch (RepositoryException e) {
            Debug.error(e);
        }
    }
    // apply any style
    Insets style_margin = null;
    int style_halign = -1;
    boolean hasBorder = false;
    Pair<IStyleSheet, IStyleRule> styleInfo = getStyleForBasicComponent(application, field, form);
    if (styleInfo != null) {
        IStyleSheet ss = styleInfo.getLeft();
        IStyleRule s = styleInfo.getRight();
        if (ss != null && s != null) {
            style_margin = ss.getMargin(s);
            style_halign = ss.getHAlign(s);
            hasBorder = ss.hasBorder(s);
        }
    }
    IStylePropertyChangesRecorder jsChangeRecorder = application.getItemFactory().createChangesRecorder();
    IFieldComponent fl;
    AbstractRuntimeField<? extends IFieldComponent> scriptable;
    switch(field.getDisplayType()) {
        case Field.PASSWORD:
            {
                RuntimeDataPassword so;
                scriptable = so = new RuntimeDataPassword(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataPassword(so, getWebID(form, field));
                so.setComponent(fl, field);
            }
            break;
        case Field.RTF_AREA:
            {
                RuntimeRtfArea so;
                scriptable = so = new RuntimeRtfArea(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataTextEditor(so, getWebID(form, field), RTF_AREA, field.getEditable());
                so.setComponent(fl, field);
                if (fl instanceof IScrollPane) {
                    applyScrollBarsProperty((IScrollPane) fl, field);
                }
            }
            break;
        case Field.HTML_AREA:
            {
                RuntimeHTMLArea so;
                scriptable = so = new RuntimeHTMLArea(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataTextEditor(so, getWebID(form, field), HTML_AREA, field.getEditable());
                so.setComponent(fl, field);
                if (fl instanceof IScrollPane) {
                    applyScrollBarsProperty((IScrollPane) fl, field);
                }
            }
            break;
        case Field.TEXT_AREA:
            {
                RuntimeTextArea so;
                scriptable = so = new RuntimeTextArea(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataTextArea(so, getWebID(form, field));
                so.setComponent(fl, field);
                if (fl instanceof IScrollPane) {
                    applyScrollBarsProperty((IScrollPane) fl, field);
                }
            }
            break;
        case Field.CHECKS:
            {
                AbstractRuntimeValuelistComponent<IFieldComponent> so;
                if (valuelist != null) {
                    IValueList list = getRealValueList(application, valuelist, true, fieldFormat.dpType, fieldFormat.parsedFormat, field.getDataProviderID());
                    if (isSingleValue(valuelist)) {
                        scriptable = so = new RuntimeCheckbox(jsChangeRecorder, application);
                        fl = application.getItemFactory().createCheckBox((RuntimeCheckbox) so, getWebID(form, field), application.getI18NMessageIfPrefixed(field.getText()), list);
                    } else {
                        scriptable = so = new RuntimeCheckBoxChoice(jsChangeRecorder, application);
                        fl = application.getItemFactory().createDataChoice((RuntimeCheckBoxChoice) so, getWebID(form, field), list, false, fieldFormat == null || fieldFormat.dpType == IColumnTypes.TEXT);
                        if (fl instanceof IScrollPane) {
                            applyScrollBarsProperty((IScrollPane) fl, field);
                        }
                    }
                } else {
                    scriptable = so = new RuntimeCheckbox(jsChangeRecorder, application);
                    fl = application.getItemFactory().createCheckBox((RuntimeCheckbox) so, getWebID(form, field), application.getI18NMessageIfPrefixed(field.getText()), null);
                }
                so.setComponent(fl, field);
            }
            break;
        case Field.RADIOS:
            {
                AbstractRuntimeValuelistComponent<IFieldComponent> so;
                IValueList list = getRealValueList(application, valuelist, true, fieldFormat.dpType, fieldFormat.parsedFormat, field.getDataProviderID());
                if (isSingleValue(valuelist)) {
                    scriptable = so = new RuntimeRadioButton(jsChangeRecorder, application);
                    fl = application.getItemFactory().createRadioButton((RuntimeRadioButton) so, getWebID(form, field), application.getI18NMessageIfPrefixed(field.getText()), list);
                } else {
                    scriptable = so = new RuntimeRadioChoice(jsChangeRecorder, application);
                    fl = application.getItemFactory().createDataChoice((RuntimeRadioChoice) so, getWebID(form, field), list, true, false);
                    if (fl instanceof IScrollPane) {
                        applyScrollBarsProperty((IScrollPane) fl, field);
                    }
                }
                so.setComponent(fl, field);
            }
            break;
        case Field.COMBOBOX:
            {
                RuntimeDataCombobox so;
                scriptable = so = new RuntimeDataCombobox(jsChangeRecorder, application);
                IValueList list = getRealValueList(application, valuelist, true, fieldFormat.dpType, fieldFormat.parsedFormat, field.getDataProviderID());
                fl = application.getItemFactory().createDataComboBox(so, getWebID(form, field), list);
                so.setComponent(fl, field);
            }
            break;
        case Field.CALENDAR:
            {
                RuntimeDataCalendar so;
                scriptable = so = new RuntimeDataCalendar(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataCalendar(so, getWebID(form, field));
                so.setComponent(fl, field);
            }
            break;
        case Field.IMAGE_MEDIA:
            {
                RuntimeMediaField so;
                scriptable = so = new RuntimeMediaField(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataImgMediaField(so, getWebID(form, field));
                if (fl instanceof IScrollPane) {
                    applyScrollBarsProperty((IScrollPane) fl, field);
                }
                so.setComponent(fl, field);
            }
            break;
        case Field.TYPE_AHEAD:
            if (field.getValuelistID() > 0) {
                fl = createTypeAheadWithValueList(application, form, field, dataProviderLookup, fieldFormat.uiType, fieldFormat.parsedFormat, jsChangeRecorder);
                if (fl == null)
                    return null;
                scriptable = (AbstractRuntimeField<? extends IFieldComponent>) fl.getScriptObject();
                break;
            }
            if (// only allow plain columns
            dp != null && dp.getColumnWrapper() != null && dp.getColumnWrapper().getRelations() == null) {
                RuntimeDataLookupField so;
                scriptable = so = new RuntimeDataLookupField(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataLookupField(so, getWebID(form, field), form.getServerName(), form.getTableName(), dp == null ? field.getDataProviderID() : dp.getDataProviderID());
                so.setComponent(fl, field);
                break;
            } else {
                RuntimeDataField so;
                scriptable = so = new RuntimeDataField(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataField(so, getWebID(form, field));
                so.setComponent(fl, field);
                break;
            }
        // $FALL-THROUGH$
        case Field.LIST_BOX:
        case Field.MULTISELECT_LISTBOX:
            {
                boolean multiSelect = (field.getDisplayType() == Field.MULTISELECT_LISTBOX);
                RuntimeListBox so;
                scriptable = so = new RuntimeListBox(jsChangeRecorder, application, multiSelect);
                IValueList list = getRealValueList(application, valuelist, true, fieldFormat.dpType, fieldFormat.parsedFormat, field.getDataProviderID());
                fl = application.getItemFactory().createListBox(so, getWebID(form, field), list, multiSelect);
                so.setComponent(fl, field);
            }
            break;
        case Field.SPINNER:
            {
                RuntimeSpinner so;
                scriptable = so = new RuntimeSpinner(jsChangeRecorder, application);
                IValueList list = getRealValueList(application, valuelist, true, fieldFormat.dpType, fieldFormat.parsedFormat, field.getDataProviderID());
                fl = application.getItemFactory().createSpinner(so, getWebID(form, field), list);
                so.setComponent(fl, field);
                break;
            }
        // else treat as the default case: TEXT_FIELD
        default:
            // Field.TEXT_FIELD
            if (field.getValuelistID() > 0) {
                fl = createTypeAheadWithValueList(application, form, field, dataProviderLookup, fieldFormat.uiType, fieldFormat.parsedFormat, jsChangeRecorder);
                if (fl == null)
                    return null;
                scriptable = (AbstractRuntimeField<? extends IFieldComponent>) fl.getScriptObject();
            } else {
                RuntimeDataField so;
                scriptable = so = new RuntimeDataField(jsChangeRecorder, application);
                fl = application.getItemFactory().createDataField(so, getWebID(form, field));
                so.setComponent(fl, field);
            }
    }
    if (fl instanceof ISupportAsyncLoading) {
        ((ISupportAsyncLoading) fl).setAsyncLoadingEnabled(!printing);
    }
    fl.setSelectOnEnter(field.getSelectOnEnter());
    fl.setEditable(field.getEditable());
    try {
        int halign = field.getHorizontalAlignment();
        if (halign != -1) {
            fl.setHorizontalAlignment(halign);
        } else if (style_halign != -1) {
            fl.setHorizontalAlignment(style_halign);
        }
    } catch (RuntimeException e) {
    // just ignore...Debug.error(e);
    }
    fl.setToolTipText(application.getI18NMessageIfPrefixed(field.getToolTipText()));
    fl.setTitleText(application.getI18NMessageIfPrefixed(field.getText()));
    fl.setDataProviderID(dp == null ? field.getDataProviderID() : dp.getDataProviderID());
    if (field.getDataProviderID() != null && dataProviderLookup != null) {
        if (scriptable instanceof IFormatScriptComponent) {
            ((IFormatScriptComponent) scriptable).setComponentFormat(fieldFormat);
        }
        if (dp != null) {
            // if (valuelist != null && valuelist.getValueListType() != ValueList.CUSTOM_VALUES) type = valuelist.getDisplayValueType();
            int l = dp.getLength();
            int defaultType = Column.mapToDefaultType(fieldFormat.dpType);
            boolean skipMaxLength = false;
            if (valuelist != null) {
                // if the display values are different than the real values, then maxlength should be skipped
                IValueList vl = getRealValueList(application, valuelist, true, fieldFormat.dpType, fieldFormat.parsedFormat, dp.getDataProviderID());
                skipMaxLength = vl.hasRealValues();
            }
            if (l > 0 && (defaultType == IColumnTypes.TEXT || defaultType == IColumnTypes.MEDIA) && !skipMaxLength) {
                fl.setMaxLength(l);
            }
        }
    }
    // fl.setOpaque(!field.getTransparent());
    if (field.getDisplaysTags()) {
        fl.setNeedEntireState(true);
        if (field.getDataProviderID() == null && field.getText() != null && fl instanceof IDisplayTagText) {
            ((IDisplayTagText) fl).setTagText(field.getText());
        }
    }
    if (// el is an ActionListener
    el != null) {
        fl.addScriptExecuter(el);
        Object[] cmds = combineMethodsToCommands(form, form.getOnElementFocusGainedMethodID(), "onElementFocusGainedMethodID", field, field.getOnFocusGainedMethodID(), "onFocusGainedMethodID");
        if (cmds != null)
            fl.setEnterCmds((String[]) cmds[0], (Object[][]) cmds[1]);
        cmds = combineMethodsToCommands(form, form.getOnElementFocusLostMethodID(), "onElementFocusLostMethodID", field, field.getOnFocusLostMethodID(), "onFocusLostMethodID");
        if (cmds != null)
            fl.setLeaveCmds((String[]) cmds[0], (Object[][]) cmds[1]);
        if (field.getOnActionMethodID() > 0)
            fl.setActionCmd(Integer.toString(field.getOnActionMethodID()), Utils.parseJSExpressions(field.getFlattenedMethodArguments("onActionMethodID")));
        if (field.getOnDataChangeMethodID() > 0)
            fl.setChangeCmd(Integer.toString(field.getOnDataChangeMethodID()), Utils.parseJSExpressions(field.getFlattenedMethodArguments("onDataChangeMethodID")));
        if (field.getOnRightClickMethodID() > 0)
            fl.setRightClickCommand(Integer.toString(field.getOnRightClickMethodID()), Utils.parseJSExpressions(field.getFlattenedMethodArguments("onRightClickMethodID")));
    }
    int onRenderMethodID = field.getOnRenderMethodID();
    AbstractBase onRenderPersist = field;
    if (onRenderMethodID <= 0) {
        onRenderMethodID = form.getOnRenderMethodID();
        onRenderPersist = form;
    }
    if (onRenderMethodID > 0) {
        RenderEventExecutor renderEventExecutor = scriptable.getRenderEventExecutor();
        renderEventExecutor.setRenderCallback(Integer.toString(onRenderMethodID), Utils.parseJSExpressions(onRenderPersist.getFlattenedMethodArguments("onRenderMethodID")));
        IForm rendererForm = application.getFormManager().getForm(form.getName());
        IScriptExecuter rendererScriptExecuter = rendererForm instanceof FormController ? ((FormController) rendererForm).getScriptExecuter() : null;
        renderEventExecutor.setRenderScriptExecuter(rendererScriptExecuter);
    }
    applyBasicComponentProperties(application, fl, field, styleInfo);
    if (fl instanceof INullableAware) {
        INullableAware nullAware = (INullableAware) fl;
        boolean allowNull = true;
        // become 0 (because it is unchecked) so that the user does not need to check/uncheck it for save
        try {
            if (dataProviderLookup != null && dataProviderLookup.getTable() != null && field.getDataProviderID() != null) {
                String dataproviderId = dp == null ? field.getDataProviderID() : dp.getDataProviderID();
                if (dataProviderLookup.getTable().getColumn(dataproviderId) != null) {
                    allowNull = dataProviderLookup.getTable().getColumn(dataproviderId).getAllowNull();
                }
            }
        } catch (RepositoryException e) {
        // maybe this field is not linked to a table column... so leave it true
        }
        nullAware.setAllowNull(allowNull);
    }
    Insets m = field.getMargin();
    if (m == null)
        m = style_margin;
    if (m != null) {
        fl.setMargin(m);
        if (fl instanceof IMarginAwareBorder) {
            if (field.getBorderType() != null || hasBorder) {
                Border b = fl.getBorder();
                if (b != null) {
                    fl.setBorder(BorderFactory.createCompoundBorder(b, BorderFactory.createEmptyBorder(m.top, m.left, m.bottom, m.right)));
                }
            }
        }
    }
    if (fl.getScriptObject() instanceof HasRuntimePlaceholder) {
        ((HasRuntimePlaceholder) fl.getScriptObject()).setPlaceholderText(field.getPlaceholderText());
    }
    return fl;
}
Also used : RuntimeDataCombobox(com.servoy.j2db.ui.scripting.RuntimeDataCombobox) Insets(java.awt.Insets) IScrollPane(com.servoy.j2db.ui.IScrollPane) ValueList(com.servoy.j2db.persistence.ValueList) LookupValueList(com.servoy.j2db.dataprocessing.LookupValueList) CustomValueList(com.servoy.j2db.dataprocessing.CustomValueList) IValueList(com.servoy.j2db.dataprocessing.IValueList) RuntimeHTMLArea(com.servoy.j2db.ui.scripting.RuntimeHTMLArea) IForm(com.servoy.j2db.IForm) IDataProvider(com.servoy.j2db.persistence.IDataProvider) RuntimeMediaField(com.servoy.j2db.ui.scripting.RuntimeMediaField) RuntimeRtfArea(com.servoy.j2db.ui.scripting.RuntimeRtfArea) HasRuntimePlaceholder(com.servoy.j2db.ui.runtime.HasRuntimePlaceholder) RuntimeDataPassword(com.servoy.j2db.ui.scripting.RuntimeDataPassword) RuntimeDataCalendar(com.servoy.j2db.ui.scripting.RuntimeDataCalendar) IValueList(com.servoy.j2db.dataprocessing.IValueList) RuntimeDataField(com.servoy.j2db.ui.scripting.RuntimeDataField) FormController(com.servoy.j2db.FormController) RuntimeRadioButton(com.servoy.j2db.ui.scripting.RuntimeRadioButton) RuntimeDataLookupField(com.servoy.j2db.ui.scripting.RuntimeDataLookupField) IStyleSheet(com.servoy.j2db.util.IStyleSheet) RuntimeCheckbox(com.servoy.j2db.ui.scripting.RuntimeCheckbox) IScriptExecuter(com.servoy.j2db.IScriptExecuter) AbstractBase(com.servoy.j2db.persistence.AbstractBase) RepositoryException(com.servoy.j2db.persistence.RepositoryException) RuntimeRadioChoice(com.servoy.j2db.ui.scripting.RuntimeRadioChoice) RuntimeCheckBoxChoice(com.servoy.j2db.ui.scripting.RuntimeCheckBoxChoice) RuntimeTextArea(com.servoy.j2db.ui.scripting.RuntimeTextArea) AbstractRuntimeValuelistComponent(com.servoy.j2db.ui.scripting.AbstractRuntimeValuelistComponent) IStyleRule(com.servoy.j2db.util.IStyleRule) RuntimeListBox(com.servoy.j2db.ui.scripting.RuntimeListBox) RuntimeSpinner(com.servoy.j2db.ui.scripting.RuntimeSpinner) IFormatScriptComponent(com.servoy.j2db.ui.scripting.IFormatScriptComponent) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) RenderEventExecutor(com.servoy.j2db.ui.RenderEventExecutor) IFieldComponent(com.servoy.j2db.ui.IFieldComponent) IStylePropertyChangesRecorder(com.servoy.j2db.ui.IStylePropertyChangesRecorder) Border(javax.swing.border.Border) TitledBorder(javax.swing.border.TitledBorder) IDisplayTagText(com.servoy.j2db.ui.IDisplayTagText)

Aggregations

IFieldComponent (com.servoy.j2db.ui.IFieldComponent)9 Component (org.apache.wicket.Component)6 IComponent (com.servoy.j2db.ui.IComponent)5 Point (java.awt.Point)4 GraphicalComponent (com.servoy.j2db.persistence.GraphicalComponent)3 CustomValueList (com.servoy.j2db.dataprocessing.CustomValueList)2 IDisplay (com.servoy.j2db.dataprocessing.IDisplay)2 IDisplayData (com.servoy.j2db.dataprocessing.IDisplayData)2 IValueList (com.servoy.j2db.dataprocessing.IValueList)2 LookupValueList (com.servoy.j2db.dataprocessing.LookupValueList)2 IServoyAwareBean (com.servoy.j2db.dataui.IServoyAwareBean)2 Field (com.servoy.j2db.persistence.Field)2 IDataProviderLookup (com.servoy.j2db.persistence.IDataProviderLookup)2 ISupportPrinting (com.servoy.j2db.persistence.ISupportPrinting)2 ISupportTabSeq (com.servoy.j2db.persistence.ISupportTabSeq)2 RepositoryException (com.servoy.j2db.persistence.RepositoryException)2 ValueList (com.servoy.j2db.persistence.ValueList)2 WebBaseSelectBox (com.servoy.j2db.server.headlessclient.dataui.WebBaseSelectBox)2 IRuntimeComponent (com.servoy.j2db.ui.runtime.IRuntimeComponent)2 AbstractRuntimeBaseComponent (com.servoy.j2db.ui.scripting.AbstractRuntimeBaseComponent)2