Search in sources :

Example 1 with ServoyBeanState

use of com.servoy.j2db.component.ServoyBeanState in project servoy-client by Servoy.

the class CellAdapter method getTableCellEditorComponent.

/*
	 * @see TableCellEditor#getTableCellEditorComponent(JTable, Object, boolean, int, int)
	 */
public Component getTableCellEditorComponent(JTable jtable, Object value, boolean isSelected, int row, int column) {
    if (editor == null || !isVisible(editor) || !(jtable.getModel() instanceof IFoundSetInternal)) {
        return empty;
    }
    IRecordInternal newRec = ((IFoundSetInternal) jtable.getModel()).getRecord(row);
    if (isSelected) {
        Color bgColor = getBgColor(jtable, isSelected, row, true);
        if (bgColor != null && editor instanceof JComponent)
            ((JComponent) editor).setOpaque(true);
        if (bgColor == null) {
            // unselected background is the default background color of the editor.
            bgColor = unselectedBackground;
        }
        lastEditorBgColor = bgColor;
        if (editor instanceof ISupportsDoubleBackground) {
            ((ISupportsDoubleBackground) editor).setBackground(bgColor, unselectedBackground);
        } else {
            editor.setBackground(bgColor);
        }
        Color fgColor = getFgColor(jtable, isSelected, row);
        if (fgColor == null) {
            // unselected foreground is the default foreground color of the editor.
            fgColor = unselectedForeground;
        }
        lastEditorFgColor = fgColor;
        if (editor instanceof ISupportsDoubleBackground) {
            ((ISupportsDoubleBackground) editor).setForeground(fgColor, unselectedForeground);
        } else {
            editor.setForeground(fgColor);
        }
        Font font = getFont(jtable, isSelected, row);
        if (font == null) {
            // unselected font is the default font of the editor.
            font = unselectedFont;
        }
        lastEditorFont = font;
        editor.setFont(font);
        Border styleBorder = getBorder(jtable, isSelected, row);
        if (styleBorder != null && editor instanceof JComponent) {
            if (editor instanceof AbstractButton && !((AbstractButton) editor).isBorderPainted()) {
                ((AbstractButton) editor).setBorderPainted(true);
            }
            Border marginBorder = null;
            if (noFocusBorder instanceof EmptyBorder) {
                marginBorder = noFocusBorder;
            } else if (noFocusBorder instanceof CompoundBorder && ((CompoundBorder) noFocusBorder).getInsideBorder() instanceof EmptyBorder) {
                marginBorder = ((CompoundBorder) noFocusBorder).getInsideBorder();
            }
            // if we have margin set on the component, keep it along with the style border
            if (marginBorder != null) {
                styleBorder = new CompoundBorder(styleBorder, marginBorder);
            }
            ((JComponent) editor).setBorder(styleBorder);
        }
    }
    // try
    // {
    // if (currentEditingState != null && newRec != currentEditingState && currentEditingState.isEditing())
    // {
    // currentEditingState.stopEditing();
    // }
    // }
    // catch (Exception e)
    // {
    // Debug.error(e);
    // }
    currentEditingState = newRec;
    if (currentEditingState != null) {
        if (editor instanceof IScriptableProvider) {
            IScriptable scriptable = ((IScriptableProvider) editor).getScriptObject();
            if (scriptable instanceof ISupportOnRenderCallback) {
                RenderEventExecutor renderEventExecutor = ((ISupportOnRenderCallback) scriptable).getRenderEventExecutor();
                if (renderEventExecutor != null && renderEventExecutor.hasRenderCallback()) {
                    renderEventExecutor.setRenderState(currentEditingState, row, isSelected, true);
                }
            }
        }
        // if not enabled or not editable do not start the edit
        if (editor instanceof IDisplay && ((IDisplay) editor).isEnabled() && !((IDisplay) editor).isReadOnly()) {
            DisplaysAdapter.startEdit(dal, (IDisplay) editor, currentEditingState);
        }
        if (editor instanceof IDisplayRelatedData) {
            IDisplayRelatedData drd = (IDisplayRelatedData) editor;
            IRecordInternal state = ((IFoundSetInternal) jtable.getModel()).getRecord(row);
            if (state != null) {
                drd.setRecord(state, true);
            }
        }
        if (// && dataProviderID != null)
        editor instanceof IDisplayData) {
            try {
                Object data = dal.getValueObject(currentEditingState, dataProviderID);
                if (data instanceof DbIdentValue) {
                    data = ((DbIdentValue) data).getPkValue();
                }
                convertAndSetValue(((IDisplayData) editor), data);
            } catch (IllegalArgumentException iae) {
                Debug.error(iae);
            }
        }
        if (editor instanceof IServoyAwareBean) {
            ((IServoyAwareBean) editor).setSelectedRecord(new ServoyBeanState(currentEditingState, dal.getFormScope()));
        }
        if (editor instanceof IScriptableProvider && !(editor instanceof IDisplayData) && !(editor instanceof IDisplayRelatedData)) {
            IScriptable scriptable = ((IScriptableProvider) editor).getScriptObject();
            if (scriptable instanceof ISupportOnRenderCallback) {
                RenderEventExecutor renderEventExecutor = ((ISupportOnRenderCallback) scriptable).getRenderEventExecutor();
                if (renderEventExecutor != null && renderEventExecutor.hasRenderCallback()) {
                    renderEventExecutor.fireOnRender(editor instanceof JTextComponent ? ((JTextComponent) editor).isEditable() : false);
                }
            }
        }
    }
    return editor.isVisible() ? editor : empty;
}
Also used : AbstractButton(javax.swing.AbstractButton) IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) IFoundSetInternal(com.servoy.j2db.dataprocessing.IFoundSetInternal) Color(java.awt.Color) JComponent(javax.swing.JComponent) ISupportOnRenderCallback(com.servoy.j2db.ui.ISupportOnRenderCallback) IDisplay(com.servoy.j2db.dataprocessing.IDisplay) JTextComponent(javax.swing.text.JTextComponent) Font(java.awt.Font) IScriptable(com.servoy.j2db.scripting.IScriptable) IDisplayRelatedData(com.servoy.j2db.dataprocessing.IDisplayRelatedData) IServoyAwareBean(com.servoy.j2db.dataui.IServoyAwareBean) ServoyBeanState(com.servoy.j2db.component.ServoyBeanState) DbIdentValue(com.servoy.j2db.dataprocessing.ValueFactory.DbIdentValue) CompoundBorder(javax.swing.border.CompoundBorder) RenderEventExecutor(com.servoy.j2db.ui.RenderEventExecutor) IDisplayData(com.servoy.j2db.dataprocessing.IDisplayData) EventObject(java.util.EventObject) EmptyBorder(javax.swing.border.EmptyBorder) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider) Border(javax.swing.border.Border) CompoundBorder(javax.swing.border.CompoundBorder) EmptyBorder(javax.swing.border.EmptyBorder) SpecialMatteBorder(com.servoy.j2db.util.gui.SpecialMatteBorder) ISupportsDoubleBackground(com.servoy.j2db.ui.ISupportsDoubleBackground)

Example 2 with ServoyBeanState

use of com.servoy.j2db.component.ServoyBeanState in project servoy-client by Servoy.

the class CellAdapter method getTableCellRendererComponent.

/*
	 * @see TableCellRenderer#getTableCellRendererComponent(JTable, Object, boolean, boolean, int, int)
	 */
public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, final int row, final int column) {
    if (renderer == null || !isVisible(renderer) || !(jtable.getModel() instanceof IFoundSetInternal)) {
        return empty;
    }
    final ISwingFoundSet foundset = (ISwingFoundSet) jtable.getModel();
    if (foundset != tableViewFoundset) {
        // foundset changed
        this.tableViewFoundset = foundset;
        rowAndDataprovider.clear();
    }
    final IRecordInternal state;
    try {
        state = foundset.getRecord(row);
    } catch (RuntimeException re) {
        // $NON-NLS-1$
        Debug.error("Error getting row ", re);
        return empty;
    }
    RenderEventExecutor renderEventExecutor = null;
    IScriptRenderMethods renderable = null;
    if (renderer instanceof IScriptableProvider) {
        IScriptable scriptable = ((IScriptableProvider) renderer).getScriptObject();
        if (scriptable instanceof ISupportOnRenderCallback) {
            renderEventExecutor = ((ISupportOnRenderCallback) scriptable).getRenderEventExecutor();
            renderable = ((ISupportOnRenderCallback) scriptable).getRenderable();
        }
    }
    Color bgColor = getBgColor(jtable, isSelected, row, false);
    if (bgColor != null && renderer instanceof JComponent)
        ((JComponent) renderer).setOpaque(true);
    Color fgColor = getFgColor(jtable, isSelected, row);
    Font font = getFont(jtable, isSelected, row);
    // so that getLocation and getWidth in scripting on tableviews do work.
    if (editor != null && editor.getParent() == null) {
        Rectangle cellRect = jtable.getCellRect(row, column, false);
        editor.setLocation(cellRect.x, cellRect.y);
        editor.setSize(cellRect.width, cellRect.height);
    }
    boolean isRenderWithOnRender = renderEventExecutor != null && renderEventExecutor.hasRenderCallback() && renderable instanceof RenderableWrapper;
    Color renderBgColor = null;
    if (isSelected) {
        if (!isRenderWithOnRender || renderEventExecutor.isDifferentRenderState(state, row, isSelected)) {
            Color tableSelectionColor = jtable.getSelectionForeground();
            if (bgColor != null) {
                tableSelectionColor = adjustColorDifference(bgColor, tableSelectionColor);
            }
            ((RenderableWrapper) renderable).clearProperty(RenderableWrapper.PROPERTY_FGCOLOR);
            renderer.setForeground(fgColor != null ? fgColor : tableSelectionColor);
            ((RenderableWrapper) renderable).clearProperty(RenderableWrapper.PROPERTY_BGCOLOR);
            renderBgColor = (bgColor != null ? bgColor : jtable.getSelectionBackground());
            renderer.setBackground(renderBgColor);
            if (font != null) {
                ((RenderableWrapper) renderable).clearProperty(RenderableWrapper.PROPERTY_FONT);
                renderer.setFont(font);
            }
        } else if (isRenderWithOnRender && foundset.getSize() == 1) {
            // if the foundset contains a single record, we need to force trigger onRender
            // because renderEventExecutor refers already to the changed render state
            renderEventExecutor.setRenderStateChanged();
        }
    } else {
        if (isRenderWithOnRender) {
            if (renderEventExecutor.isDifferentRenderState(state, row, isSelected)) {
                Color newBGColor = bgColor != null ? bgColor : componentBgColor;
                if (newBGColor != null) {
                    ((RenderableWrapper) renderable).clearProperty(RenderableWrapper.PROPERTY_BGCOLOR);
                    renderBgColor = newBGColor;
                    renderer.setBackground(renderBgColor);
                }
                Color newFGColor = fgColor != null ? fgColor : componentFgColor;
                if (newFGColor != null) {
                    ((RenderableWrapper) renderable).clearProperty(RenderableWrapper.PROPERTY_FGCOLOR);
                    renderer.setForeground(newFGColor);
                } else if (newBGColor != null) {
                    renderer.setForeground(adjustColorDifference(newBGColor, jtable.getForeground()));
                }
                Font newFont = font != null ? font : componentFont;
                if (newFont != null) {
                    ((RenderableWrapper) renderable).clearProperty(RenderableWrapper.PROPERTY_FONT);
                    renderer.setFont(newFont);
                }
            }
        } else {
            // now get the editors background. if we don't do that then scripting doesn't show up
            Color background = editor.getBackground();
            if (background != null && !background.equals(lastEditorBgColor)) {
                unselectedBackground = background;
                lastEditorBgColor = background;
            }
            Font editorFont = editor.getFont();
            if (editorFont != null && !editorFont.equals(lastEditorFont)) {
                unselectedFont = editorFont;
            }
            if (editor instanceof IDisplayData && ((IDisplayData) editor).isValueValid() || !(editor instanceof IDisplayData)) {
                Color foreground = editor.getForeground();
                if (foreground != null && !foreground.equals(lastEditorFgColor)) {
                    unselectedForeground = foreground;
                }
                Color currentForeground = (fgColor != null ? fgColor : (unselectedForeground != null) ? unselectedForeground : jtable.getForeground());
                renderer.setForeground(currentForeground);
            }
            Color currentColor = (bgColor != null ? bgColor : (unselectedBackground != null) ? unselectedBackground : jtable.getBackground());
            renderer.setBackground(currentColor);
            Font currentFont = (font != null ? font : (unselectedFont != null) ? unselectedFont : jtable.getFont());
            renderer.setFont(currentFont);
        }
    }
    if (renderer instanceof JComponent) {
        applyRowBorder((JComponent) renderer, jtable, isSelected, row, hasFocus);
    }
    // $NON-NLS-1$
    boolean printing = Utils.getAsBoolean(application.getRuntimeProperties().get("isPrinting"));
    if (renderEventExecutor != null && renderEventExecutor.hasRenderCallback()) {
        renderEventExecutor.setRenderState(state, row, isSelected, true);
    }
    if (renderer instanceof IDisplayRelatedData) {
        IDisplayRelatedData drd = (IDisplayRelatedData) renderer;
        String relationName = drd.getSelectedRelationName();
        if (state != null) {
            if (relationName != null) {
                if (!printing && !state.isRelatedFoundSetLoaded(relationName, null)) {
                    IApplication app = dal.getApplication();
                    ((IDisplayData) renderer).setValueObject(null);
                    // $NON-NLS-1$ //$NON-NLS-2$
                    String key = row + "_" + relationName + "_" + null;
                    if (!rowAndDataprovider.contains(key)) {
                        rowAndDataprovider.add(key);
                        Runnable r = new ASynchonizedCellLoad(app, jtable, foundset, row, jtable.convertColumnIndexToModel(column), relationName, drd.getDefaultSort(), null);
                        app.getScheduledExecutor().execute(r);
                    }
                    return renderer.isVisible() ? renderer : empty;
                }
            }
            drd.setRecord(state, true);
        }
    }
    if (renderer instanceof IDisplayData) {
        if (state != null) {
            Object data = null;
            if (dataProviderID != null) {
                int index = -1;
                if (!printing && (index = dataProviderID.indexOf('.')) > 0) {
                    if (!ScopesUtils.isVariableScope(dataProviderID)) {
                        String partName = dataProviderID.substring(0, index);
                        final String restName = dataProviderID.substring(index + 1);
                        String relationName = partName;
                        if (relationName != null && !state.isRelatedFoundSetLoaded(relationName, restName)) {
                            IApplication app = dal.getApplication();
                            ((IDisplayData) renderer).setValueObject(null);
                            // $NON-NLS-1$ //$NON-NLS-2$
                            String key = row + "_" + relationName + "_" + restName;
                            if (!rowAndDataprovider.contains(key)) {
                                rowAndDataprovider.add(key);
                                List<SortColumn> defaultPKSortColumns = null;
                                try {
                                    defaultPKSortColumns = app.getFoundSetManager().getDefaultPKSortColumns(app.getFlattenedSolution().getRelation(relationName).getForeignDataSource());
                                } catch (ServoyException e) {
                                    Debug.error(e);
                                }
                                Runnable r = new ASynchonizedCellLoad(app, jtable, foundset, row, jtable.convertColumnIndexToModel(column), relationName, defaultPKSortColumns, restName);
                                app.getScheduledExecutor().execute(r);
                            }
                            return renderer.isVisible() ? renderer : empty;
                        }
                        IFoundSetInternal rfs = state.getRelatedFoundSet(relationName);
                        if (rfs != null) {
                            int selected = rfs.getSelectedIndex();
                            // should still go through record 0
                            if (selected == -1 && rfs.getSize() > 0) {
                                selected = 0;
                            }
                            final IRecordInternal relState = rfs.getRecord(selected);
                            if (testCalc(restName, relState, row, jtable.convertColumnIndexToModel(column), foundset))
                                return renderer;
                        }
                    }
                }
                if (!((IDisplayData) renderer).needEntireState() && !printing && testCalc(dataProviderID, state, row, jtable.convertColumnIndexToModel(column), foundset)) {
                    return renderer;
                }
                try {
                    data = dal.getValueObject(state, dataProviderID);
                } catch (IllegalArgumentException iae) {
                    Debug.error(iae);
                    // $NON-NLS-1$
                    data = "<conversion error>";
                }
            }
            ((IDisplayData) renderer).setTagResolver(new ITagResolver() {

                public String getStringValue(String nm) {
                    return TagResolver.formatObject(dal.getValueObject(state, nm), dal.getApplication());
                }
            });
            if (data instanceof DbIdentValue) {
                data = ((DbIdentValue) data).getPkValue();
            }
            convertAndSetValue(((IDisplayData) renderer), data);
        }
    }
    if (renderer instanceof IServoyAwareBean && state != null) {
        ((IServoyAwareBean) renderer).setSelectedRecord(new ServoyBeanState(state, dal.getFormScope()));
    }
    if (!(renderer instanceof IDisplayData) && !(renderer instanceof IDisplayRelatedData) && renderEventExecutor != null && renderEventExecutor.hasRenderCallback()) {
        renderEventExecutor.fireOnRender(false);
    }
    // if the bgcolor is not changed during onRender
    if (isRenderWithOnRender && renderBgColor != null && ((RenderableWrapper) renderable).getProperty(RenderableWrapper.PROPERTY_BGCOLOR) == null) {
        renderer.setBackground(renderBgColor);
    }
    return renderer.isVisible() ? renderer : empty;
}
Also used : IFoundSetInternal(com.servoy.j2db.dataprocessing.IFoundSetInternal) Rectangle(java.awt.Rectangle) ISupportOnRenderCallback(com.servoy.j2db.ui.ISupportOnRenderCallback) SortColumn(com.servoy.j2db.dataprocessing.SortColumn) Font(java.awt.Font) ServoyException(com.servoy.j2db.util.ServoyException) IScriptRenderMethods(com.servoy.j2db.ui.IScriptRenderMethods) IDisplayRelatedData(com.servoy.j2db.dataprocessing.IDisplayRelatedData) IServoyAwareBean(com.servoy.j2db.dataui.IServoyAwareBean) DbIdentValue(com.servoy.j2db.dataprocessing.ValueFactory.DbIdentValue) RenderableWrapper(com.servoy.j2db.ui.RenderableWrapper) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider) IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) ITagResolver(com.servoy.base.util.ITagResolver) Color(java.awt.Color) JComponent(javax.swing.JComponent) ISwingFoundSet(com.servoy.j2db.dataprocessing.ISwingFoundSet) IScriptable(com.servoy.j2db.scripting.IScriptable) Point(java.awt.Point) IApplication(com.servoy.j2db.IApplication) ServoyBeanState(com.servoy.j2db.component.ServoyBeanState) RenderEventExecutor(com.servoy.j2db.ui.RenderEventExecutor) IDisplayData(com.servoy.j2db.dataprocessing.IDisplayData) EventObject(java.util.EventObject)

Example 3 with ServoyBeanState

use of com.servoy.j2db.component.ServoyBeanState 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 4 with ServoyBeanState

use of com.servoy.j2db.component.ServoyBeanState in project servoy-client by Servoy.

the class DataAdapterList method setRecord.

/**
 * Inform all dataAdapters about the new state. <br><br>
 *
 * Note on param: stopAnyEdit, the Renderer paints state 6 (record 6) after that the editor comes in and edits
 * that state 6, then another row must be repainted so State 7 and it calls stop editing on 6, but the editor is
 * still editing that state 6
 *
 * @param state the new state (can be null to delete old state)
 */
public void setRecord(IRecordInternal state, boolean stopAnyEdit) {
    if (destroyed) {
        Debug.error("calling setRecord on a destroyed DataAdapterList, formcontroller: " + formController + ", currentRecord: " + currentRecord, new RuntimeException());
        return;
    }
    if (undoManager != null)
        undoManager.setIgnoreEdits(true);
    if (currentRecord != null) {
        // NEVER enable this ,values in the state could be changed: if (currentState.equals(state)) return;//same
        if (!currentRecord.equals(state)) {
            stopUIEditing(false);
        }
        if (state != currentRecord) {
            // unregister
            currentRecord.removeModificationListener(this);
        }
    }
    if (state != null && state != currentRecord) {
        // register so we are notified about javascript changes on non global vars from here
        state.addModificationListener(this);
    }
    currentRecord = state;
    // 1) handle first related data (needed for comboboxes)
    for (IDisplayRelatedData drd : relatedDataAdapters) {
        if (// && !(state instanceof PrototypeState))
        state != null) {
            if (// performance enhancement
            !(drd instanceof RelatedFieldHolder)) {
                drd.setRecord(state, stopAnyEdit);
            }
        } else {
            // clear
            drd.setRecord(null, true);
        }
    }
    // check if destroyed.
    if (dataAdapters == null)
        return;
    // 2) handle all fields, make sure all the events are collected and fired later (calculations that are triggering data change events)
    FireCollector collector = FireCollector.getFireCollector();
    try {
        Iterator<IDataAdapter> it = dataAdapters.values().iterator();
        while (it.hasNext()) {
            IDataAdapter da = it.next();
            da.setRecord(state);
        }
        if (currentRecord != null && servoyAwareBeans.size() > 0) {
            ServoyBeanState sbr = new ServoyBeanState(state, getFormScope());
            for (IServoyAwareBean da : servoyAwareBeans) {
                try {
                    da.setSelectedRecord(sbr);
                } catch (RuntimeException e) {
                    // never make the app break on faulty beans
                    Debug.error(e);
                }
            }
        }
    } finally {
        collector.done();
    }
    if (undoManager != null)
        undoManager.setIgnoreEdits(false);
}
Also used : ServoyBeanState(com.servoy.j2db.component.ServoyBeanState) IServoyAwareBean(com.servoy.j2db.dataui.IServoyAwareBean)

Aggregations

ServoyBeanState (com.servoy.j2db.component.ServoyBeanState)4 IServoyAwareBean (com.servoy.j2db.dataui.IServoyAwareBean)4 ISupportOnRenderCallback (com.servoy.j2db.ui.ISupportOnRenderCallback)3 IDisplayData (com.servoy.j2db.dataprocessing.IDisplayData)2 IDisplayRelatedData (com.servoy.j2db.dataprocessing.IDisplayRelatedData)2 IFoundSetInternal (com.servoy.j2db.dataprocessing.IFoundSetInternal)2 IRecordInternal (com.servoy.j2db.dataprocessing.IRecordInternal)2 DbIdentValue (com.servoy.j2db.dataprocessing.ValueFactory.DbIdentValue)2 IScriptable (com.servoy.j2db.scripting.IScriptable)2 IScriptableProvider (com.servoy.j2db.scripting.IScriptableProvider)2 RenderEventExecutor (com.servoy.j2db.ui.RenderEventExecutor)2 Color (java.awt.Color)2 Font (java.awt.Font)2 EventObject (java.util.EventObject)2 JComponent (javax.swing.JComponent)2 ITagResolver (com.servoy.base.util.ITagResolver)1 IApplication (com.servoy.j2db.IApplication)1 IDisplay (com.servoy.j2db.dataprocessing.IDisplay)1 IRecord (com.servoy.j2db.dataprocessing.IRecord)1 ISwingFoundSet (com.servoy.j2db.dataprocessing.ISwingFoundSet)1