Example usage for org.apache.wicket Component findParent

List of usage examples for org.apache.wicket Component findParent

Introduction

In this page you can find the example usage for org.apache.wicket Component findParent.

Prototype

public final <Z> Z findParent(final Class<Z> c) 

Source Link

Document

Finds the first container parent of this component of the given class.

Usage

From source file:com.googlecode.wicketwebbeans.containers.BeanForm.java

License:Apache License

/**
 * Construct a new BeanForm.//from  www .  j a v  a2  s .  co m
 *
 * @param id the Wicket id for the panel.
 * @param bean the bean to be displayed. This may be an IModel or regular bean object.
 *  The bean may be a List or, if an IModel, a model that returns a List. If so, the bean is display is
 *  displayed using BeanTablePanel. Otherwise BeanGridPanel is used.
 * @param beanMetaData the meta data for the bean. If bean is a List or model of a List, then this must be
 *  the BeanMetaData for a single element (row) of the List.
 * @param container an optional container to use in place of the default BeanGridPanel or BeanTablePanel. This container must must be a Panel and
 *   implement a constructor of the form: <p>
 *   <code>public Constructor(String id, final Object bean, BeanMetaData beanMetaData, TabMetaData tabMetaData)</code>
 *   <p>
 *   where id = Wicket component ID<br>
 *   bean = the bean, or IModel containing the bean<br>
 *   beanMetaData = the BeanMetaData for bean<br>
 *   tabMetaData = the tab metadata<p>
 *   May be null.
 */
@SuppressWarnings("serial")
public BeanForm(String id, final Object bean, final BeanMetaData beanMetaData,
        final Class<? extends Panel> container) {
    super(id);

    this.bean = bean;
    this.beanMetaData = beanMetaData;
    this.container = container;

    form = new Form("f") {
        // Track whether the form is in submit processing.
        @Override
        public boolean process() {
            ++submitCnt;
            try {
                return super.process();
            } finally {
                --submitCnt;
            }
        }
    };

    form.setOutputMarkupId(true);
    add(form);

    String title = beanMetaData.getLabel();
    form.add(new Label("title", title));

    form.add(new Label("beanFormIndicatorErrorLabel", new ResourceModel("beanFormError.msg",
            "An error occurred on the server. Your session may have timed out.")));

    beanMetaData.consumeParameter(PARAM_ROWS);

    final HiddenField hiddenFocusField = new HiddenField<String>("focusField",
            new PropertyModel<String>(this, "focusField"));
    hiddenFocusField.add(new AbstractBehavior() {
        @Override
        public void onComponentTag(Component component, ComponentTag tag) {
            tag.put("id", "bfFocusField");
            super.onComponentTag(component, tag);
        }
    });

    form.add(hiddenFocusField);

    formVisitor = new FormVisitor();

    createTabs(bean, beanMetaData, container);

    // Use a FeedbackMessageFilter to handle messages for multiple BeanForms on a page. This is because messages are stored on the session.
    IFeedbackMessageFilter feedbackFilter = new IFeedbackMessageFilter() {
        public boolean accept(FeedbackMessage message) {
            // If the reporter is a field and this is refreshing because of a non-Ajax form submit, it's very likely that the field has been detached
            // from its parent because it is in a list view. As a result, findParent doesn't return the BeanForm.
            Component reporter = message.getReporter();
            AbstractField reporterField = (AbstractField) (reporter instanceof AbstractField ? reporter
                    : reporter.findParent(AbstractField.class));
            if (reporterField != null) {
                return reporterField.getBeanForm().getId().equals(BeanForm.this.getId());
            }

            Component parent = (reporter instanceof BeanForm ? reporter : reporter.findParent(BeanForm.class));
            return reporter == BeanForm.this || parent == null || parent == BeanForm.this;
        }
    };

    feedback = new FeedbackPanel("feedback", feedbackFilter);
    feedback.setOutputMarkupId(true);
    form.add(feedback);

    createGlobalActions();
}

From source file:com.googlecode.wicketwebbeans.containers.BeanForm.java

License:Apache License

/**
 * Finds the BeanForm that is the parent of the given childComponent.
 *
 * @param childComponent the child, may be null.
 * /*from   w ww. j a v a 2  s  . co  m*/
 * @return the parent BeanForm, or null if childComponent is not part of a BeanForm.
 */
public static BeanForm findBeanFormParent(Component childComponent) {
    if (childComponent == null) {
        return null;
    }

    return childComponent.findParent(BeanForm.class);
}

From source file:com.googlecode.wicketwebbeans.containers.BeanForm.java

License:Apache License

private void refreshComponent(final AjaxRequestTarget target, Component targetComponent) {
    // Refresh this field. We have to find the parent Field to do this.
    MarkupContainer field;/*  w  w  w.  j a v a  2s.  c o m*/
    if (targetComponent instanceof Field) {
        field = (MarkupContainer) targetComponent;
    } else {
        field = targetComponent.findParent(AbstractField.class);
    }

    if (field != null) {
        if (!field.getRenderBodyOnly()) {
            target.addComponent(field);
        } else {
            // Field is RenderBodyOnly, have to add children individually
            field.visitChildren(new IVisitor<Component>() {
                public Object component(Component component) {
                    if (!component.getRenderBodyOnly()) {
                        target.addComponent(component);
                    }

                    return IVisitor.CONTINUE_TRAVERSAL;
                }

            });
        }
    } else {
        target.addComponent(targetComponent);
    }
}

From source file:com.locke.library.web.behaviors.update.AjaxFormComponentUpdateBroadcastingBehavior.java

License:Apache License

@Override
protected void onUpdate(AjaxRequestTarget target) {
    final Component component = getComponent();
    final IEventBroadcasterLocator locator = component.findParent(IEventBroadcasterLocator.class);
    if (locator != null) {
        locator.getEventBroadcaster().broadcast(new AjaxUpdateEvent(component, target));
    }//from  w  ww  .j a va  2s.  co m
}

From source file:com.pushinginertia.wicket.core.util.ComponentUtils.java

License:Open Source License

/**
 * A facade for {@link org.apache.wicket.Component#findParent(Class)} that fails if no parent component of the
 * given type exists. This should be called from {@link org.apache.wicket.Component#onInitialize()} and not in the
 * component's constructor.//from  w w w .j av  a2s  .c o  m
 * @param callingComponent component making the call
 * @param parentClass type of the parent class
 * @param <Z> type of the parent class
 * @return never null
 */
public static <Z> Z findParentOrDie(final Component callingComponent, final Class<Z> parentClass) {
    ValidateAs.notNull(callingComponent, "callingComponent");
    ValidateAs.notNull(parentClass, "parentClass");

    final Z parentComponent = callingComponent.findParent(parentClass);
    if (parentComponent == null) {
        throw new IllegalStateException("Failed to find parent of type " + parentClass.getName()
                + " from callingComponent. A common cause is that this method is called from a component's constructor instead of its onInitialize() method. Component: "
                + callingComponent);
    }
    return parentComponent;
}

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

License:Open Source License

/**
 * @param obj//from ww  w .  ja v  a2  s.com
 * @param dataProviderID
 * @param prevValue
 */
public void setValue(Component component, String dataProviderID, Object value) {
    Object obj = value;
    String compDpid = getDataProviderID(component);
    boolean ownComponentsValue = compDpid != null && dataProviderID.endsWith(compDpid);
    Object prevValue = null;
    if (ownComponentsValue && component instanceof IResolveObject) {
        obj = ((IResolveObject) component).resolveRealValue(obj);
    }

    if (component instanceof IDisplayData) {
        obj = Utils.removeJavascripLinkFromDisplay((IDisplayData) component, new Object[] { obj });
    }

    WebForm webForm = component.findParent(WebForm.class);
    IRecordInternal record = (IRecordInternal) RecordItemModel.this.getObject();

    // use UI converter to convert from UI value to record value
    if (!(record instanceof FindState)) {
        obj = ComponentFormat.applyUIConverterFromObject(component, obj, dataProviderID,
                webForm.getController().getApplication().getFoundSetManager());
    }

    FormScope fs = webForm.getController().getFormScope();
    try {
        Pair<String, String> scope = ScopesUtils.getVariableScope(dataProviderID);
        if (scope.getLeft() != null) {
            if (record == null) {
                webForm.getController().getApplication().getScriptEngine().getSolutionScope().getScopesScope()
                        .getGlobalScope(scope.getLeft()).put(scope.getRight(), obj);
            } else {
                //does an additional fire in foundset!
                prevValue = record.getParentFoundSet().setDataProviderValue(dataProviderID, obj);
            }
        } else if (fs.has(dataProviderID, fs)) {
            prevValue = fs.get(dataProviderID);
            fs.put(dataProviderID, obj);
        } else {
            if (record != null && record.startEditing()) {
                try {
                    prevValue = record.getValue(dataProviderID);
                    record.setValue(dataProviderID, obj);
                } catch (IllegalArgumentException e) {
                    Debug.trace(e);
                    ((WebClientSession) Session.get()).getWebClient().handleException(null,
                            new ApplicationException(ServoyException.INVALID_INPUT, e));
                    Object stateValue = record.getValue(dataProviderID);
                    if (!Utils.equalObjects(prevValue, stateValue)) {
                        // reset display to changed value in validator method
                        obj = stateValue;
                    }
                    if (ownComponentsValue) {
                        ((IDisplayData) component).setValueValid(false, prevValue);
                    }
                    return;
                }

                if (ownComponentsValue && record instanceof FindState
                        && component instanceof IScriptableProvider
                        && ((IScriptableProvider) component).getScriptObject() instanceof IFormatScriptComponent
                        && ((IFormatScriptComponent) ((IScriptableProvider) component).getScriptObject())
                                .getComponentFormat() != null) {
                    ((FindState) record).setFormat(dataProviderID,
                            ((IFormatScriptComponent) ((IScriptableProvider) component).getScriptObject())
                                    .getComponentFormat().parsedFormat);
                }
            }
        }
        // this can be called on another dataprovider id then the component (media upload)
        // then dont call notify
        if (ownComponentsValue) {
            ((IDisplayData) component).notifyLastNewValueWasChange(prevValue, obj);
        }
    } finally {
        // this can be called on another dataprovider id then the component (media upload)
        // then touch the lastInvalidValue
        if (ownComponentsValue) {
            if (((IDisplayData) component).isValueValid()) {
                lastInvalidValue = NONE;
            } else {
                lastInvalidValue = obj;
            }
        }
    }
    return;
}

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

License:Open Source License

/**
 * Gets the value for dataProviderID in the context of this record and the form determined using given component. The component is only used for getting the
 * form, otherwise it does not affect the returned value.
 *
 * @param component the component used to determine the form (in case of global or form variables).
 * @param dataProviderID the data provider id pointing to a data provider in the record, a form or a global variable.
 * @return the value.//from  w ww.  j a  v a2  s .  com
 */
public Object getValue(Component component, String dataProviderID) {
    Object value = null;
    WebForm webForm = component.findParent(WebForm.class);
    if (webForm == null) {
        // component.toString() may cause stackoverflow here
        Debug.error("Component " + component.getClass() + " with dp: " + dataProviderID //$NON-NLS-1$//$NON-NLS-2$
                + "  already removed from its parent form.", new RuntimeException()); //$NON-NLS-1$
        return null;
    }
    FormScope fs = webForm.getController().getFormScope();
    IRecord record = (IRecord) RecordItemModel.this.getObject();
    if (ScopesUtils.isVariableScope(dataProviderID)) {
        value = webForm.getController().getApplication().getScriptEngine().getSolutionScope().getScopesScope()
                .get(null, dataProviderID);
    } else if (record != null) {
        value = record.getValue(dataProviderID);
    }
    if (value == Scriptable.NOT_FOUND && fs != null && fs.has(dataProviderID, fs)) {
        value = fs.get(dataProviderID);
    }

    if (value instanceof DbIdentValue) {
        value = ((DbIdentValue) value).getPkValue();
    }

    if (value == Scriptable.NOT_FOUND) {
        value = null;
    } else if (!(record instanceof FindState)) {
        // use UI converter to convert from record value to UI value
        value = ComponentFormat.applyUIConverterToObject(component, value, dataProviderID,
                webForm.getController().getApplication().getFoundSetManager());
    }

    return value;
}

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

License:Open Source License

public WebCellBasedView(final String id, final IApplication application, RuntimePortal scriptable,
        final Form form, final AbstractBase cellview, final IDataProviderLookup dataProviderLookup,
        final IScriptExecuter el, boolean addHeaders, final int startY, final int endY, final int sizeHint,
        int viewType) {
    super(id);/*from ww  w. j  a  va2  s. co  m*/
    this.application = application;
    this.cellview = cellview;
    this.fc = el.getFormController();
    this.addHeaders = addHeaders;
    this.startY = startY;
    this.endY = endY;
    this.formDesignHeight = form.getSize().height;
    this.sizeHint = sizeHint;
    this.isListViewMode = viewType == IForm.LIST_VIEW || viewType == FormController.LOCKED_LIST_VIEW;
    this.bodyWidthHint = form.getWidth();

    double multiplier = Utils.getAsDouble(
            Settings.getInstance().getProperty("servoy.webclient.scrolling.tableview.multiplier", "2"));

    if (multiplier > 1.1) {
        NEW_PAGE_MULITPLIER = multiplier;
    } else {
        NEW_PAGE_MULITPLIER = 1.1;
    }

    useAJAX = Utils.getAsBoolean(application.getRuntimeProperties().get("useAJAX")); //$NON-NLS-1$
    useAnchors = Utils.getAsBoolean(application.getRuntimeProperties().get("enableAnchors")); //$NON-NLS-1$

    // a cell based view should just never version itself if in ajax mode
    // (all things like next page or rerenders are done on the actual page not a version you can go back to (url doesn't change)
    if (useAJAX)
        setVersioned(false);

    setScrollMode(
            Boolean.TRUE.equals(application.getClientProperty(IApplication.TABLEVIEW_WC_DEFAULT_SCROLLABLE)));
    isKeepLoadedRowsInScrollMode = Boolean.TRUE
            .equals(application.getClientProperty(IApplication.TABLEVIEW_WC_SCROLLABLE_KEEP_LOADED_ROWS));

    setOutputMarkupPlaceholderTag(true);

    dataRendererOnRenderWrapper = new DataRendererOnRenderWrapper(this);

    loadingInfo = new Label("info", "Loading ..."); //$NON-NLS-1$
    loadingInfo.setVisible(false);
    add(loadingInfo);

    if (!useAJAX)
        bodyHeightHint = sizeHint;

    String orientation = OrientationApplier.getHTMLContainerOrientation(application.getLocale(),
            application.getSolution().getTextOrientation());
    isLeftToRightOrientation = !OrientationApplier.RTL.equalsIgnoreCase(orientation);

    int tFormHeight = 0;
    Iterator<Part> partIte = form.getParts();
    while (partIte.hasNext()) {
        Part p = partIte.next();
        if (p.getPartType() == Part.BODY) {
            tFormHeight = p.getHeight() - startY;
            break;
        }
    }
    formBodySize = new Dimension(form.getWidth(), tFormHeight);

    ChangesRecorder jsChangeRecorder = new ChangesRecorder(null, null) {
        @Override
        public boolean isChanged() {
            boolean retval = false;
            if (super.isChanged()) {
                retval = true;
                //TODO: change this; we should not do this, but it is not re-rendered otherwise
                return retval;
            }

            if (!retval) {
                Iterator<Component> iterator = elementToColumnIdentifierComponent.values().iterator();
                while (iterator.hasNext()) {
                    Component object = iterator.next();
                    if (object instanceof IProviderStylePropertyChanges) {
                        if (((IProviderStylePropertyChanges) object).getStylePropertyChanges().isChanged()) {
                            retval = true;
                            break;
                        }
                    }
                }
            }
            if (retval) {
                MainPage page = (MainPage) getPage();
                page.getPageContributor().addTableToRender(WebCellBasedView.this);
                setRendered();
            }
            return false;
        }

        @Override
        public void setRendered() {
            super.setRendered();
            Iterator<Component> iterator = elementToColumnIdentifierComponent.values().iterator();
            while (iterator.hasNext()) {
                Component comp = iterator.next();
                if (comp instanceof IProviderStylePropertyChanges) {
                    ((IProviderStylePropertyChanges) comp).getStylePropertyChanges().setRendered();
                }
            }
        }
    };
    this.scriptable = scriptable;
    ((ChangesRecorder) scriptable.getChangesRecorder()).setAdditionalChangesRecorder(jsChangeRecorder);

    add(TooltipAttributeModifier.INSTANCE);

    final int scrollbars = (cellview instanceof ISupportScrollbars)
            ? ((ISupportScrollbars) cellview).getScrollbars()
            : 0;
    add(new StyleAppendingModifier(new Model<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            if (!isScrollMode() && findParent(IWebFormContainer.class) != null) {
                return ""; //$NON-NLS-1$
            }
            return scrollBarDefinitionToOverflowAttribute(scrollbars, isScrollMode(), false,
                    currentData == null || currentData.getSize() == 0);
        }
    }));
    if (cellview instanceof BaseComponent) {
        ComponentFactory.applyBasicComponentProperties(application, this, (BaseComponent) cellview,
                ComponentFactory.getStyleForBasicComponent(application, cellview, form));
    }

    boolean sortable = true;
    String initialSortString = null;
    int onRenderMethodID = 0;
    AbstractBase onRenderPersist = null;
    if (cellview instanceof Portal) {
        Portal p = (Portal) cellview;
        isListViewMode = p.getMultiLine();

        setRowBGColorScript(p.getRowBGColorCalculation(),
                p.getInstanceMethodArguments("rowBGColorCalculation")); //$NON-NLS-1$
        sortable = p.getSortable();
        initialSortString = p.getInitialSort();
        onRenderMethodID = p.getOnRenderMethodID();
        onRenderPersist = p;

        int portalAnchors = p.getAnchors();
        isAnchored = (((portalAnchors & IAnchorConstants.NORTH) > 0)
                && ((portalAnchors & IAnchorConstants.SOUTH) > 0))
                || (((portalAnchors & IAnchorConstants.EAST) > 0)
                        && ((portalAnchors & IAnchorConstants.WEST) > 0));
    } else if (cellview instanceof Form) {
        initialSortString = form.getInitialSort();
        onRenderMethodID = form.getOnRenderMethodID();
        onRenderPersist = form;
        isAnchored = true;
    }

    if (onRenderMethodID > 0) {
        dataRendererOnRenderWrapper.getRenderEventExecutor().setRenderCallback(
                Integer.toString(onRenderMethodID),
                Utils.parseJSExpressions(onRenderPersist.getInstanceMethodArguments("onRenderMethodID")));
        dataRendererOnRenderWrapper.getRenderEventExecutor()
                .setRenderScriptExecuter(fc != null ? fc.getScriptExecuter() : null);
    }

    initDragNDrop(fc, startY);

    if (sortable) {
        if (initialSortString != null) {
            StringTokenizer tokByComma = new StringTokenizer(initialSortString, ","); //$NON-NLS-1$
            while (tokByComma.hasMoreTokens()) {
                String initialSortFirstToken = tokByComma.nextToken();
                StringTokenizer tokBySpace = new StringTokenizer(initialSortFirstToken);
                if (tokBySpace.hasMoreTokens()) {
                    String initialSortColumnName = tokBySpace.nextToken();

                    if (tokBySpace.hasMoreTokens()) {
                        String sortDir = tokBySpace.nextToken();
                        boolean initialSortAsc = true;
                        if (sortDir.equalsIgnoreCase("DESC")) //$NON-NLS-1$
                            initialSortAsc = false;
                        initialSortColumnNames.put(initialSortColumnName, new Boolean(initialSortAsc));
                    }
                }
            }
        }
        // If no initial sort was specified, then default will be the first PK column.
        if (initialSortColumnNames.size() == 0) {
            try {
                String dataSource = null;
                if (cellview instanceof Portal) {
                    Portal p = (Portal) cellview;
                    String relation = p.getRelationName();
                    int lastDot = relation.lastIndexOf("."); //$NON-NLS-1$
                    if (lastDot >= 0) {
                        relation = relation.substring(lastDot + 1);
                    }
                    Relation rel = application.getFlattenedSolution().getRelation(relation);
                    if (rel != null) {
                        dataSource = rel.getForeignDataSource();
                    }
                } else {
                    dataSource = form.getDataSource();
                }
                if (dataSource != null) {
                    Iterator<String> pkColumnNames = application.getFoundSetManager().getTable(dataSource)
                            .getRowIdentColumnNames();
                    while (pkColumnNames.hasNext()) {
                        initialSortColumnNames.put(pkColumnNames.next(), Boolean.TRUE);
                    }
                }
            } catch (RepositoryException e) {
                // We just don't set the initial sort to the PK.
                Debug.log("Failed to get PK columns for table.", e); //$NON-NLS-1$
            }
        }
    }

    maxHeight = 0;
    try {
        if (isListViewMode() && !(cellview instanceof Portal)) {
            int headerHeight = 0;
            int titleHeaderHeight = 0;
            Iterator<Part> pIte = form.getParts();
            while (pIte.hasNext()) {
                Part p = pIte.next();
                if (p.getPartType() == Part.BODY) {
                    maxHeight = p.getHeight();
                } else if (p.getPartType() == Part.HEADER) {
                    headerHeight = p.getHeight();
                } else if (p.getPartType() == Part.TITLE_HEADER) {
                    titleHeaderHeight = p.getHeight();
                }
            }
            if (headerHeight != 0) {
                maxHeight = maxHeight - headerHeight;
            } else {
                maxHeight = maxHeight - titleHeaderHeight;
            }
        } else {
            int minElY = 0;
            boolean isMinElYSet = false;
            int height;
            Iterator<IPersist> components = cellview.getAllObjects(PositionComparator.XY_PERSIST_COMPARATOR);
            while (components.hasNext()) {
                IPersist element = components.next();
                if (element instanceof Field || element instanceof GraphicalComponent) {
                    if (element instanceof GraphicalComponent
                            && ((GraphicalComponent) element).getLabelFor() != null) {
                        if (isInView(cellview, ((GraphicalComponent) element).getLabelFor())) {
                            labelsFor.put(((GraphicalComponent) element).getLabelFor(), element);
                        }
                        continue;
                    }
                    Point l = ((IFormElement) element).getLocation();
                    if (l == null) {
                        continue;// unknown where to add
                    }
                    if (l.y >= startY && l.y < endY) {

                        if (isListViewMode()) {
                            height = l.y + ((IFormElement) element).getSize().height;
                            if (!isMinElYSet || minElY > l.y) {
                                minElY = l.y;
                                isMinElYSet = true;
                            }
                        } else {
                            height = ((IFormElement) element).getSize().height;
                        }
                        if (height > maxHeight)
                            maxHeight = height;
                    }
                }
            }
            maxHeight = maxHeight - minElY;
        }
        if (maxHeight == 0)
            maxHeight = 20;
    } catch (Exception ex1) {
        Debug.error("Error getting max size out of components", ex1); //$NON-NLS-1$
    }

    // Add the table
    tableContainerBody = new WebMarkupContainer("rowsContainerBody"); //$NON-NLS-1$
    tableContainerBody.setOutputMarkupId(true);

    table = new WebCellBasedViewListView("rows", data, 1, cellview, //$NON-NLS-1$
            dataProviderLookup, el, startY, endY, form);
    table.setReuseItems(true);

    tableContainerBody.add(table);
    add(tableContainerBody);

    final LinkedHashMap<String, IDataAdapter> dataadapters = new LinkedHashMap<String, IDataAdapter>();
    final SortedList<IPersist> columnTabSequence = new SortedList<IPersist>(TabSeqComparator.INSTANCE); // in fact ISupportTabSeq persists
    createComponents(application, form, cellview, dataProviderLookup, el, startY, endY, new ItemAdd() {
        public void add(IPersist element, Component comp) {

            if (element instanceof IFormElement && comp instanceof IComponent) {
                ((IComponent) comp).setLocation(((IFormElement) element).getLocation());
                ((IComponent) comp).setSize(((IFormElement) element).getSize());
            }

            elementToColumnIdentifierComponent.put(element, comp);
            if (cellview instanceof Form && element instanceof ISupportTabSeq
                    && ((ISupportTabSeq) element).getTabSeq() >= 0) {
                columnTabSequence.add(element);
            }
            if (comp instanceof IDisplayData) {
                String dataprovider = ((IDisplayData) comp).getDataProviderID();

                WebCellAdapter previous = (WebCellAdapter) dataadapters.get(dataprovider);
                if (previous == null) {
                    WebCellAdapter wca = new WebCellAdapter(dataprovider, WebCellBasedView.this);
                    dataadapters.put(dataprovider, wca);
                }
                if (dataprovider != null) {
                    if (initialSortColumnNames.containsKey(dataprovider))
                        initialSortedColumns.put(comp.getId(), initialSortColumnNames.get(dataprovider));
                }
            }
        }
    });
    for (int i = columnTabSequence.size() - 1; i >= 0; i--) {
        elementTabIndexes.put(columnTabSequence.get(i), Integer.valueOf(i));
    }

    // Add the (sortable) header (and define how to sort the different columns)
    if (addHeaders) {
        // elementToColumnHeader will be filled up by SortableCellViewHeaders when components in it are resolved
        headers = new SortableCellViewHeaders(form, this, "header", table, cellview, application, //$NON-NLS-1$
                initialSortedColumns, new IHeaders() {

                    public void registerHeader(IPersist matchingElement, Component headerComponent) {
                        SortableCellViewHeader sortableHeader = (SortableCellViewHeader) headerComponent;
                        // set headerComponent width
                        Component columnIdentifier = WebCellBasedView.this.elementToColumnIdentifierComponent
                                .get(matchingElement);

                        if (columnIdentifier instanceof IProviderStylePropertyChanges) {
                            String width = ((IProviderStylePropertyChanges) columnIdentifier)
                                    .getStylePropertyChanges().getJSProperty("offsetWidth"); //$NON-NLS-1$
                            if (width != null) {
                                sortableHeader
                                        .setWidth(Integer.parseInt(width.substring(0, width.length() - 2)));
                            } else if (matchingElement instanceof BaseComponent)
                                sortableHeader.setWidth(((BaseComponent) matchingElement).getSize().width);
                        }
                        sortableHeader.setTabSequenceIndex(ISupportWebTabSeq.SKIP);
                        sortableHeader.setScriptExecuter(el);
                        sortableHeader.setResizeClass(columnIdentifier.getId());
                        WebCellBasedView.this.registerHeader(matchingElement, headerComponent);
                    }
                });
        add(headers);
    }

    // Add a table navigator
    if (useAJAX) {
        add(pagingNavigator = new ServoyAjaxPagingNavigator("navigator", table)); //$NON-NLS-1$
        add(tableResizeBehavior = new ServoyTableResizeBehavior(startY, endY, cellview));
        if (isScrollMode())
            add(new HeaderHeightCalculationBehavior());
    } else {
        add(pagingNavigator = new ServoySubmitPagingNavigator("navigator", table)); //$NON-NLS-1$
    }

    //hide all further records (and navigator) if explicitly told that there should be no vertical scrollbar
    showPageNavigator = !((scrollbars
            & ISupportScrollbars.VERTICAL_SCROLLBAR_NEVER) == ISupportScrollbars.VERTICAL_SCROLLBAR_NEVER);

    try {
        if (cellview instanceof Portal) {
            relationName = ((Portal) cellview).getRelationName();
            Relation[] rels = application.getFlattenedSolution()
                    .getRelationSequence(((Portal) cellview).getRelationName());

            if (rels != null) {
                Relation r = rels[rels.length - 1];
                if (r != null) {
                    defaultSort = ((FoundSetManager) application.getFoundSetManager()).getSortColumns(
                            application.getFoundSetManager().getTable(r.getForeignDataSource()),
                            ((Portal) cellview).getInitialSort());
                }
            }
        } else {
            defaultSort = ((FoundSetManager) application.getFoundSetManager())
                    .getSortColumns(((Form) cellview).getDataSource(), ((Form) cellview).getInitialSort());
        }
    } catch (RepositoryException e) {
        Debug.error(e);
        defaultSort = new ArrayList<SortColumn>(1);
    }

    try {
        dal = new DataAdapterList(application, dataProviderLookup, elementToColumnIdentifierComponent,
                el.getFormController(), dataadapters, null);
    } catch (RepositoryException ex) {
        Debug.error(ex);
    }

    table.setPageabeMode(!isScrollMode());
    if (isScrollMode()) {
        tableContainerBody.add(new StyleAppendingModifier(new Model<String>() {
            private static final long serialVersionUID = 1L;

            @Override
            public String getObject() {
                int scrollPadding = 0;
                //ClientInfo info = Session.get().getClientInfo();
                //if (info instanceof WebClientInfo && ((WebClientInfo)info).getProperties().isBrowserInternetExplorer()) scrollPadding = 0;
                //else scrollPadding = SCROLLBAR_SIZE;
                return scrollBarDefinitionToOverflowAttribute(scrollbars, isScrollMode(), true,
                        currentData == null || currentData.getSize() == 0)
                        + "position: absolute; left: 0px; right: 0px; bottom: 0px; border-spacing: 0px; -webkit-overflow-scrolling: touch; top:" //$NON-NLS-1$
                        + scrollableHeaderHeight + "px; padding-right:" + scrollPadding + "px;"; //$NON-NLS-1$ //$NON-NLS-2$
            }
        }));
        tableContainerBody.add(new SimpleAttributeModifier("class", "rowsContainerBody")); //$NON-NLS-1$ //$NON-NLS-2$
        tableContainerBody.add(scrollBehavior = new ScrollBehavior("onscroll")); //$NON-NLS-1$
        tableContainerBody.add(topPlaceholderUpdater = new TopPlaceholderUpdater());
    }

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

        @Override
        public String getObject() {
            WebForm container = findParent(WebForm.class);
            if (container != null && container.getBorder() instanceof TitledBorder) {
                int offset = ComponentFactoryHelper.getTitledBorderHeight(container.getBorder());
                return "top: " + offset + "px;"; //$NON-NLS-1$ //$NON-NLS-2$
            }
            return ""; //$NON-NLS-1$
        }
    }) {
        @Override
        public boolean isEnabled(Component component) {
            WebForm container = component.findParent(WebForm.class);
            if (container != null && container.getBorder() instanceof TitledBorder) {
                return super.isEnabled(component);
            }
            return false;
        }
    });
    if (!Boolean.FALSE.equals(application.getClientProperty(IApplication.TABLEVIEW_WC_USE_KEY_NAVIGATION))) {
        add(new ServoyAjaxEventBehavior("onkeydown", null, true) {
            @Override
            protected void onEvent(AjaxRequestTarget target) {
                int i = fc.getFormModel().getSelectedIndex();
                boolean downArrow = Utils
                        .getAsBoolean(RequestCycle.get().getRequest().getParameter("downArrow"));
                if (downArrow) {
                    i++;
                } else {
                    i--;
                }
                if (i >= 0) {
                    fc.getFormModel().setSelectedIndex(i);
                    WebEventExecutor.generateResponse(target, getPage());
                }
            }

            @Override
            protected CharSequence generateCallbackScript(final CharSequence partialCall) {
                return super.generateCallbackScript(partialCall + "+Servoy.Utils.getArrowParams()"); //$NON-NLS-1$
            }

            @Override
            protected IAjaxCallDecorator getAjaxCallDecorator() {
                return new AjaxCallDecorator() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public CharSequence decorateScript(CharSequence script) {
                        return "return Servoy.Utils.testArrowKey(event, function() {" + script + "},'" //$NON-NLS-1$//$NON-NLS-2$
                                + getMarkupId() + "');";
                    }
                };
            }

            @Override
            protected boolean blockRequest() {
                return false;
            }

        });
    }
    if (!isListViewMode()) {
        add(new ServoyAjaxEventBehavior("onclick", null, true) {
            @Override
            protected void onEvent(AjaxRequestTarget target) {
                if (application.getFoundSetManager().getEditRecordList().isEditing()) {
                    application.getFoundSetManager().getEditRecordList().stopEditing(false);
                    WebEventExecutor.generateResponse(target, getPage());
                }
            }

            @Override
            protected IAjaxCallDecorator getAjaxCallDecorator() {
                return new AjaxCallDecorator() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public CharSequence decorateScript(CharSequence script) {
                        return "if ((event.target || event.srcElement) == this){ " + script + " }"; //$NON-NLS-1$
                    }
                };
            }

        });
    }
}

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

License:Open Source License

/**
 * @param id//from   ww w .  ja  v  a 2s  .c  o m
 */
public WebDataRenderer(String id, String formPartName, final IApplication app) {
    super(id);
    //      application = app;
    add(StyleAttributeModifierModel.INSTANCE);
    add(TooltipAttributeModifier.INSTANCE);
    setOutputMarkupPlaceholderTag(true);
    this.formPartName = formPartName;
    dataRendererOnRenderWrapper = new DataRendererOnRenderWrapper(this);
    add(new StyleAppendingModifier(new Model<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            WebForm container = findParent(WebForm.class);
            if (container != null && container.getBorder() instanceof TitledBorder) {
                int offset = ComponentFactoryHelper.getTitledBorderHeight(container.getBorder());
                return "top: " + offset + "px;";
            }
            return ""; //$NON-NLS-1$
        }
    }) {
        @Override
        public boolean isEnabled(Component component) {
            if (WebDataRenderer.this.getParent().get(0) != WebDataRenderer.this)
                return false;
            WebForm container = component.findParent(WebForm.class);
            if (container != null && container.getBorder() instanceof TitledBorder) {
                return super.isEnabled(component);
            }
            return false;
        }
    });
    add(new ServoyAjaxEventBehavior("onclick", null, true) {
        @Override
        protected void onEvent(AjaxRequestTarget target) {
            if (app.getFoundSetManager().getEditRecordList().isEditing()) {
                app.getFoundSetManager().getEditRecordList().stopEditing(false);
                WebEventExecutor.generateResponse(target, getPage());
            }
        }

        @Override
        protected IAjaxCallDecorator getAjaxCallDecorator() {
            return new AjaxCallDecorator() {
                private static final long serialVersionUID = 1L;

                @Override
                public CharSequence decorateScript(CharSequence script) {
                    return "if ((event.target || event.srcElement) == this){ " + script + " }"; //$NON-NLS-1$ 
                }
            };
        }

    });
}

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

License:Open Source License

public void onEvent(final EventType type, final AjaxRequestTarget target, final Component comp,
        final int webModifiers, final Point mouseLocation, final Point absoluteMouseLocation) {
    ServoyForm form = comp.findParent(ServoyForm.class);
    if (form == null) {
        return;/*  www.  j  a  v  a  2s . c  om*/
    }

    final Page page = form.getPage(); // JS might change the page this form belongs to... so remember it now

    IEventDispatcher<WicketEvent> eventDispatcher = WebClientSession.get().getWebClient().getEventDispatcher();
    if (eventDispatcher != null) {
        eventDispatcher.addEvent(new WicketEvent(WebClientSession.get().getWebClient(), new Runnable() {
            public void run() {
                handleEvent(type, target, comp, webModifiers, mouseLocation, absoluteMouseLocation, page);
            }
        }));
    } else {
        handleEvent(type, target, comp, webModifiers, mouseLocation, absoluteMouseLocation, page);
    }
    if (target != null) {
        generateResponse(target, page);
    }
}