List of usage examples for org.apache.wicket Component getMarkupId
public String getMarkupId()
From source file:com.servoy.extensions.beans.dbtreeview.WicketDBTreeView.java
License:Open Source License
public void renderHead(IHeaderResponse response) { Iterator selectedNodesIte = getTreeState().getSelectedNodes().iterator(); if (selectedNodesIte.hasNext()) { TreeNode firstSelectedNode = (TreeNode) selectedNodesIte.next(); Component nodeComponent = getNodeComponent(firstSelectedNode); if (nodeComponent != null) { String treeId = getMarkupId(); String nodeId = nodeComponent.getMarkupId(); response.renderOnDomReadyJavascript("document.getElementById('" + treeId + "').scrollTop = document.getElementById('" + nodeId + "').offsetTop;\n"); }//from w w w.jav a 2 s .c o m } }
From source file:com.servoy.j2db.server.headlessclient.dataui.StripHTMLTagsConverter.java
License:Open Source License
/** * @param bodyText//ww w. ja v a 2 s . c o m * @param solution * @return */ @SuppressWarnings("nls") public static StrippedText convertBodyText(Component component, CharSequence bodyText, FlattenedSolution solutionRoot) { StrippedText st = new StrippedText(); if (RequestCycle.get() == null) { st.setBodyTxt(bodyText); return st; } ResourceReference rr = new ResourceReference("media"); //$NON-NLS-1$ String solutionName = solutionRoot.getSolution().getName(); StringBuffer bodyTxt = new StringBuffer(bodyText.length()); XmlPullParser parser = new XmlPullParser(); ICrypt urlCrypt = null; if (Application.exists()) urlCrypt = Application.get().getSecuritySettings().getCryptFactory().newCrypt(); try { parser.parse(new ByteArrayInputStream(bodyText.toString().getBytes("UTF8")), "UTF8"); //$NON-NLS-1$ //$NON-NLS-2$ XmlTag me = (XmlTag) parser.nextTag(); while (me != null) { CharSequence tmp = parser.getInputFromPositionMarker(me.getPos()); if (tmp.toString().trim().length() > 0) bodyTxt.append(tmp); parser.setPositionMarker(); String currentTagName = me.getName().toLowerCase(); if (currentTagName.equals("script")) //$NON-NLS-1$ { if (!me.isClose()) { String srcUrl = (String) me.getAttributes().get("src"); //$NON-NLS-1$ if (srcUrl == null) srcUrl = (String) me.getAttributes().get("SRC"); //$NON-NLS-1$ me = (XmlTag) parser.nextTag(); if (srcUrl != null) { st.getJavascriptUrls() .add(convertMediaReferences(srcUrl, solutionName, rr, "", true).toString()); } else { if (me != null) { st.getJavascriptScripts().add(parser.getInputFromPositionMarker(me.getPos())); parser.setPositionMarker(); } } } else { me = (XmlTag) parser.nextTag(); } continue; } else if (currentTagName.equals("style")) { if (me.isOpen()) { me = (XmlTag) parser.nextTag(); List<CharSequence> styles = st.getStyles(); String style = parser.getInputFromPositionMarker(me.getPos()).toString().trim(); if (!"".equals(style) && !styles.contains(style)) { styles.add(convertMediaReferences(style, solutionName, rr, "", false)); } parser.setPositionMarker(); } else { me = (XmlTag) parser.nextTag(); } continue; } else if (currentTagName.equals("link")) { if (me.isOpen() || me.isOpenClose()) { String end = "\n"; if (me.isOpen()) end = "</link>\n"; st.getLinkTags().add( convertMediaReferences(me.toXmlString(null) + end, solutionName, rr, "", false)); } me = (XmlTag) parser.nextTag(); continue; } if (ignoreTags.contains(currentTagName)) { if (currentTagName.equals("body") && (me.isOpen() || me.isOpenClose())) { if (me.getAttributes().size() > 0) { st.addBodyAttributes(me.getAttributes()); } me = (XmlTag) parser.nextTag(); } else { me = (XmlTag) parser.nextTag(); } continue; } if (currentTagName.equals("img") && component instanceof ILabel) { ILabel label = (ILabel) component; String onload = "Servoy.Utils.setLabelChildHeight('" + component.getMarkupId() + "', " + label.getVerticalAlignment() + ");"; onload = me.getAttributes().containsKey("onload") ? me.getAttributes().getString("onload") + ";" + onload : onload; me.getAttributes().put("onload", onload); } boolean ignoreOnclick = false; IValueMap attributeMap = me.getAttributes(); // first transfer over the tabindex to anchor tags if (currentTagName.equals("a")) { int tabIndex = TabIndexHelper.getTabIndex(component); if (tabIndex != -1) attributeMap.put("tabindex", Integer.valueOf(tabIndex)); } // TODO attributes with casing? // now they have to be lowercase. (that is a xhtml requirement) for (String attribute : scanTags) { if (ignoreOnclick && attribute.equals("onclick")) //$NON-NLS-1$ continue; String src = attributeMap.getString(attribute); if (src == null) { continue; } String lowercase = src.toLowerCase(); if (lowercase.startsWith(MediaURLStreamHandler.MEDIA_URL_DEF)) { String name = src.substring(MediaURLStreamHandler.MEDIA_URL_DEF.length()); if (name.startsWith(MediaURLStreamHandler.MEDIA_URL_BLOBLOADER)) { String url = generateBlobloaderUrl(component, urlCrypt, name); me.getAttributes().put(attribute, url); } else { String translatedUrl = MediaURLStreamHandler.getTranslatedMediaURL(solutionRoot, lowercase); if (translatedUrl != null) { me.getAttributes().put(attribute, translatedUrl); } } } else if (component instanceof ISupportScriptCallback && lowercase.startsWith("javascript:")) { String script = src; if (script.length() > 13) { String scriptName = script.substring(11); if ("href".equals(attribute)) { if (attributeMap.containsKey("externalcall")) { attributeMap.remove("externalcall"); } else { me.getAttributes().put("href", "#"); me.getAttributes().put("onclick", ((ISupportScriptCallback) component).getCallBackUrl(scriptName, true)); ignoreOnclick = true; } } else { me.getAttributes().put(attribute, ((ISupportScriptCallback) component) .getCallBackUrl(scriptName, "onclick".equals(attribute))); } } } else if (component instanceof FormComponent<?> && lowercase.startsWith("javascript:")) { String script = src; if (script.length() > 13) { String scriptName = script.substring(11); if ("href".equals(attribute)) { me.getAttributes().put("href", "#"); me.getAttributes().put("onclick", getTriggerJavaScript((FormComponent<?>) component, scriptName)); ignoreOnclick = true; } else { me.getAttributes().put(attribute, getTriggerJavaScript((FormComponent<?>) component, scriptName)); } } } } bodyTxt.append(me.toString()); me = (XmlTag) parser.nextTag(); } bodyTxt.append(parser.getInputFromPositionMarker(-1)); st.setBodyTxt(convertMediaReferences(convertBlobLoaderReferences(bodyTxt, component), solutionName, rr, "", false)); //$NON-NLS-1$ } catch (ParseException ex) { Debug.error(ex); bodyTxt.append("<span style=\"color : #ff0000;\">"); //$NON-NLS-1$ bodyTxt.append(ex.getMessage()); bodyTxt.append(bodyText.subSequence(ex.getErrorOffset(), Math.min(ex.getErrorOffset() + 100, bodyText.length()))); bodyTxt.append("</span></body></html>"); //$NON-NLS-1$ st.setBodyTxt(bodyTxt); } catch (Exception ex) { Debug.error(ex); bodyTxt.append("<span style=\"color : #ff0000;\">"); //$NON-NLS-1$ bodyTxt.append(ex.getMessage()); bodyTxt.append("</span></body></html>"); //$NON-NLS-1$ st.setBodyTxt(bodyTxt); } return st; }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebBaseButton.java
License:Open Source License
protected static AttributeModifier getImageDisplayRolloverBehavior(final IImageDisplay imageDisplay) { if (imageDisplay instanceof Component) { final Component imageDisplayComponent = (Component) imageDisplay; return new AttributeModifier("onmouseover", true, new Model<String>() { private static final long serialVersionUID = 1L; @Override//from w ww. j a va2 s.c o m public String getObject() { String solutionName = J2DBGlobals.getServiceProvider().getSolution().getName(); String url = ""; //$NON-NLS-1$ if (imageDisplay.getRolloverIconReference() != null && imageDisplay.getRolloverMedia() != null) { if (imageDisplay.getMediaOptions() != 0 && imageDisplay.getMediaOptions() != 1) { url = imageDisplayComponent.urlFor(imageDisplay.getRolloverIconReference()) + "?id=" //$NON-NLS-1$ + imageDisplay.getRolloverMedia().getName() + "&s=" + solutionName + "&option=" + //$NON-NLS-2$ imageDisplay.getMediaOptions() + "&w=" + imageDisplay.getWebBounds().width + "&h=" //$NON-NLS-1$//$NON-NLS-2$ + imageDisplay.getWebBounds().height + "&l=" + (imageDisplay.getRolloverMedia().getMediaData() != null ? +imageDisplay.getRolloverMedia().getMediaData().hashCode() : 0); } else { url = imageDisplayComponent.urlFor(imageDisplay.getRolloverIconReference()) + "?id=" //$NON-NLS-1$ + imageDisplay.getRolloverMedia().getName() + "&s=" + solutionName + "&l=" + //$NON-NLS-2$ (imageDisplay.getRolloverMedia().getMediaData() != null ? +imageDisplay.getRolloverMedia().getMediaData().hashCode() : 0); } } else if (imageDisplay.getRolloverUrl() != null) { if (imageDisplay.getRolloverUrl().startsWith(MediaURLStreamHandler.MEDIA_URL_DEF)) { String mediaName = imageDisplay.getRolloverUrl() .substring(MediaURLStreamHandler.MEDIA_URL_DEF.length()); if (mediaName.startsWith(MediaURLStreamHandler.MEDIA_URL_BLOBLOADER)) { ICrypt urlCrypt = null; if (Application.exists()) urlCrypt = Application.get().getSecuritySettings().getCryptFactory().newCrypt(); url = StripHTMLTagsConverter.generateBlobloaderUrl(imageDisplayComponent, urlCrypt, mediaName); } } else url = imageDisplay.getRolloverUrl(); } return "Servoy.Rollover.onMouseOver('" + imageDisplayComponent.getMarkupId() + "_img','" + url //$NON-NLS-1$//$NON-NLS-2$ + "')"; //$NON-NLS-1$ } }) { @Override protected String newValue(final String currentValue, final String replacementValue) { return replacementValue + ";" + currentValue; } }; } return null; }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebBaseButton.java
License:Open Source License
protected static AttributeModifier getImageDisplayRolloutBehavior(IImageDisplay imageDisplay) { if (imageDisplay instanceof Component) { final Component imageDisplayComponent = (Component) imageDisplay; return new AttributeModifier("onmouseout", true, new Model<String>() { private static final long serialVersionUID = 1L; @Override//from w ww.j ava 2 s . c om public String getObject() { return "Servoy.Rollover.onMouseOut('" + imageDisplayComponent.getMarkupId() + "_img')"; //$NON-NLS-1$ //$NON-NLS-2$ } }) { @Override protected String newValue(final String currentValue, final String replacementValue) { return currentValue + ";" + replacementValue; } }; } return null; }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebCellBasedView.java
License:Open Source License
@SuppressWarnings("nls") private void initializeComponent(final Component c, AbstractBase view, Object element) { if (dal != null && dal.isDestroyed()) { Debug.error("Trying to initialize a component: " + c + " of " + view + " element: " + element + " that is in a destroyed tableview", new RuntimeException()); return;// ww w.jav a 2s.c o m } if (view instanceof Portal && c instanceof IDisplayData) // Don't know any other place for this { String id = ((IDisplayData) c).getDataProviderID(); if (id != null && !ScopesUtils.isVariableScope(id) && id.startsWith(((Portal) view).getRelationName() + '.')) { ((IDisplayData) c) .setDataProviderID(id.substring(((Portal) cellview).getRelationName().length() + 1)); } } if (!isListViewMode() && c instanceof WebDataCheckBox) { ((WebDataCheckBox) c).setText(""); //$NON-NLS-1$ } if (element != null) { // apply to this cell the state of the columnIdentifier IComponent, do keep the location that is set by the tableview when creating these components the first time. // for listview this is the location to use. Point loc = ((IComponent) c).getLocation(); int height = ((IComponent) c).getSize().height; PropertyCopy.copyElementProps((IComponent) elementToColumnIdentifierComponent.get(element), (IComponent) c); if (!isListViewMode()) { ((IComponent) c).setLocation(loc); //it shouldn't be possible to change the height if (c instanceof IScriptableProvider) { IScriptable so = ((IScriptableProvider) c).getScriptObject(); if (so instanceof IRuntimeComponent) { IRuntimeComponent ic = (IRuntimeComponent) so; if (ic.getHeight() != height) { ic.setSize(ic.getWidth(), height); } } } } } else { Debug.log("Cannot find the IPersist element for cell " + c.getMarkupId()); //$NON-NLS-1$ } if (c instanceof IDisplayData) { IDisplayData cdd = (IDisplayData) c; if (!(dal != null && dal.getFormScope() != null && cdd.getDataProviderID() != null && dal.getFormScope().get(cdd.getDataProviderID()) != Scriptable.NOT_FOUND)) // skip for form variables { cdd.setValidationEnabled(validationEnabled); } } else if (c instanceof IDisplayRelatedData) { ((IDisplayRelatedData) c).setValidationEnabled(validationEnabled); } else if (c instanceof IServoyAwareBean) { ((IServoyAwareBean) c).setValidationEnabled(validationEnabled); } addClassToCellComponent(c); if (c instanceof WebDataCompositeTextField) // the check could be extended against IDelegate<?> { Object delegate = ((WebDataCompositeTextField) c).getDelegate(); if (delegate instanceof Component) { addClassToCellComponent((Component) delegate); // make sure that this class is added accordingly in TemplateGenerator as a style selector containing relevant properties } } if (c instanceof ISupportValueList) { ISupportValueList idVl = (ISupportValueList) elementToColumnIdentifierComponent.get(element); IValueList list; if (idVl != null && (list = idVl.getValueList()) != null) { ValueList valuelist = application.getFlattenedSolution().getValueList(list.getName()); if (valuelist != null && valuelist.getValueListType() == IValueListConstants.CUSTOM_VALUES) { ((ISupportValueList) c).setValueList(list); } } } }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataCalendar.java
License:Open Source License
public WebDataCalendar(IApplication application, RuntimeDataCalendar scriptable, String id) { super(application, scriptable, id); boolean useAJAX = Utils.getAsBoolean(application.getRuntimeProperties().get("useAJAX")); //$NON-NLS-1$ if (useAJAX) { final FeedSimpleDateFormatToChooserBehavior feedSimpleDateToJS; field.add(feedSimpleDateToJS = new FeedSimpleDateFormatToChooserBehavior()); field.add(new DatePicker() { private static final long serialVersionUID = 1L; @Override/* w ww . j a v a2 s .co m*/ public void onRendered(Component component) { Response response = component.getResponse(); response.write( "</td><td style = \"margin: 0px; padding: 0px; width: 5px;\"> </td><td style = \"margin: 0px; padding: 0px; width: 16px;\">"); response.write("\n<img style=\""); response.write(getIconStyle()); response.write("\" id=\""); response.write(getIconId()); response.write("\" src=\""); CharSequence iconUrl = getIconUrl(); response.write(Strings.escapeMarkup(iconUrl == null ? "" : iconUrl.toString())); response.write("\" onclick=\"if (!isValidationFailed('" + WebDataCalendar.this.getMarkupId() + "')) wicketAjaxGet('" + feedSimpleDateToJS.getCallbackUrl() + "¤tDateValue='+wicketEncode(document.getElementById('"); response.write(component.getMarkupId()); response.write( "').value), null, function() { onAjaxError(); }.bind(this), function() { return Wicket.$(this.id) != null; }.bind(this));\"/>"); } @Override public boolean isEnabled(Component component) { return shouldShowExtraComponents(); } }); } else { field.add(new DatePicker() { private static final long serialVersionUID = 1L; @Override public void onRendered(Component component) { Response response = component.getResponse(); response.write( "</td><td style = \"margin: 0px; padding: 0px; width: 5px;\"> </td><td style = \"margin: 0px; padding: 0px; width: 16px;\">"); response.write("\n<img style=\""); response.write(getIconStyle()); response.write("\" id=\""); response.write(getIconId()); response.write("\" src=\""); CharSequence iconUrl = getIconUrl(); response.write(Strings.escapeMarkup(iconUrl == null ? "" : iconUrl.toString())); response.write("\" onclick=\"if (!isValidationFailed('" + WebDataCalendar.this.getMarkupId() + "'))displayCalendar(document.getElementById('"); response.write(component.getMarkupId()); response.write("'),'"); String datePattern = getDatePattern().replaceAll("mm", "ii").toLowerCase(); datePattern = datePattern.replace('s', '0'); response.write(datePattern); if (datePattern.indexOf("h") == -1) response.write("',this,false,'" + component.getMarkupId() + "',true)\""); else response.write("',this,true,null,true)\""); response.write(" />"); } @Override public boolean isEnabled(Component component) { return shouldShowExtraComponents(); } }); } }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebEventExecutor.java
License:Open Source License
/** * @param component/*from w w w.j av a 2 s . com*/ */ @SuppressWarnings("nls") public static boolean setSelectedIndex(Component component, AjaxRequestTarget target, int modifiers, boolean bHandleMultiselect) { WebForm parentForm = component.findParent(WebForm.class); WebCellBasedView tableView = null; if (parentForm != null) { int parentFormViewType = parentForm.getController().getForm().getView(); if (parentFormViewType == FormController.TABLE_VIEW || parentFormViewType == FormController.LOCKED_TABLE_VIEW || parentFormViewType == IForm.LIST_VIEW || parentFormViewType == FormController.LOCKED_LIST_VIEW) { tableView = component.findParent(WebCellBasedView.class); if (tableView == null) { // the component is not part of the table view (it is on other form part), so ignore selection change return true; } else tableView.setSelectionMadeByCellAction(); if (parentFormViewType == IForm.LIST_VIEW || parentFormViewType == FormController.LOCKED_LIST_VIEW) { if (component instanceof WebCellBasedViewListViewItem) { ((WebCellBasedViewListViewItem) component).markSelected(target); } else { WebCellBasedViewListViewItem listViewItem = component .findParent(WebCellBasedView.WebCellBasedViewListViewItem.class); if (listViewItem != null) { listViewItem.markSelected(target); } } } } } //search for recordItem model Component recordItemModelComponent = component; IModel<?> someModel = recordItemModelComponent.getDefaultModel(); while (!(someModel instanceof RecordItemModel)) { recordItemModelComponent = recordItemModelComponent.getParent(); if (recordItemModelComponent == null) break; someModel = recordItemModelComponent.getDefaultModel(); } if (someModel instanceof RecordItemModel) { if (!(component instanceof WebCellBasedViewListViewItem)) { // update the last rendered value for the events component (if updated) ((RecordItemModel) someModel).updateRenderedValue(component); } IRecordInternal rec = (IRecordInternal) someModel.getObject(); if (rec != null) { int index; IFoundSetInternal fs = rec.getParentFoundSet(); if (someModel instanceof FoundsetRecordItemModel) { index = ((FoundsetRecordItemModel) someModel).getRowIndex(); } else { index = fs.getRecordIndex(rec); // this is used only on "else", because a "plugins.rawSQL.flushAllClientsCache" could result in index = -1 although the record has not changed (but record & underlying row instances changed) } if (fs instanceof FoundSet && ((FoundSet) fs).isMultiSelect()) { //set the selected record ClientProperties clp = ((WebClientInfo) Session.get().getClientInfo()).getProperties(); String navPlatform = clp.getNavigatorPlatform(); int controlMask = (navPlatform != null && navPlatform.toLowerCase().indexOf("mac") != -1) ? Event.META_MASK : Event.CTRL_MASK; boolean toggle = (modifiers != MODIFIERS_UNSPECIFIED) && ((modifiers & controlMask) != 0); boolean extend = (modifiers != MODIFIERS_UNSPECIFIED) && ((modifiers & Event.SHIFT_MASK) != 0); boolean isRightClick = (modifiers != MODIFIERS_UNSPECIFIED) && ((modifiers & Event.ALT_MASK) != 0); if (!isRightClick) { if (!toggle && !extend && tableView != null && tableView.getDragNDropController() != null && Arrays.binarySearch(((FoundSet) fs).getSelectedIndexes(), index) > -1) { return true; } if (toggle || extend) { if (bHandleMultiselect) { if (toggle) { int[] selectedIndexes = ((FoundSet) fs).getSelectedIndexes(); ArrayList<Integer> selectedIndexesA = new ArrayList<Integer>(); Integer selectedIndex = new Integer(index); for (int selected : selectedIndexes) selectedIndexesA.add(new Integer(selected)); if (selectedIndexesA.indexOf(selectedIndex) != -1) { if (selectedIndexesA.size() > 1) selectedIndexesA.remove(selectedIndex); } else selectedIndexesA.add(selectedIndex); selectedIndexes = new int[selectedIndexesA.size()]; for (int i = 0; i < selectedIndexesA.size(); i++) selectedIndexes[i] = selectedIndexesA.get(i).intValue(); ((FoundSet) fs).setSelectedIndexes(selectedIndexes); } else if (extend) { int anchor = ((FoundSet) fs).getSelectedIndex(); int min = Math.min(anchor, index); int max = Math.max(anchor, index); int[] newSelectedIndexes = new int[max - min + 1]; for (int i = min; i <= max; i++) newSelectedIndexes[i - min] = i; ((FoundSet) fs).setSelectedIndexes(newSelectedIndexes); } } } else if (index != -1 || fs.getSize() == 0) { fs.setSelectedIndex(index); } } } else if (!isIndexSelected(fs, index)) fs.setSelectedIndex(index); if (!isIndexSelected(fs, index) && !(fs instanceof FoundSet && ((FoundSet) fs).isMultiSelect())) { // setSelectedIndex failed, probably due to validation failed, do a blur() if (target != null) target.appendJavascript("var toBlur = document.getElementById(\"" + component.getMarkupId() + "\");if (toBlur) toBlur.blur();"); return false; } } } return true; }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebEventExecutor.java
License:Open Source License
@SuppressWarnings("nls") public static void generateResponse(final AjaxRequestTarget target, Page page) { WebClientSession webClientSession = WebClientSession.get(); if (target != null && page instanceof MainPage && webClientSession != null && webClientSession.getWebClient() != null && webClientSession.getWebClient().getSolution() != null) { if (target instanceof CloseableAjaxRequestTarget && ((CloseableAjaxRequestTarget) target).isClosed()) { return; }/* www . j a v a 2 s. com*/ // do executed the events for before generating the response. webClientSession.getWebClient().executeEvents(); if (webClientSession.getWebClient() == null || webClientSession.getWebClient().getSolution() == null) { // how can web client be null here ? return; } final MainPage mainPage = ((MainPage) page); if (mainPage.getPageMap() instanceof ModifiedAccessStackPageMap) { // at every request mark the pagemap as dirty so lru eviction really works ((ModifiedAccessStackPageMap) mainPage.getPageMap()).flagDirty(); } // If the main form is switched then do a normal redirect. if (mainPage.isMainFormSwitched()) { mainPage.versionPush(); RequestCycle.get().setResponsePage(page); } else { page.visitChildren(WebTabPanel.class, new Component.IVisitor<WebTabPanel>() { public Object component(WebTabPanel component) { component.initalizeFirstTab(); return IVisitor.CONTINUE_TRAVERSAL; } }); mainPage.addWebAnchoringInfoIfNeeded(); final Set<WebCellBasedView> tableViewsToRender = new HashSet<WebCellBasedView>(); final List<String> valueChangedIds = new ArrayList<String>(); final List<String> invalidValueIds = new ArrayList<String>(); final Map<WebCellBasedView, List<Integer>> tableViewsWithChangedRowIds = new HashMap<WebCellBasedView, List<Integer>>(); // first, get all invalidValue & valueChanged components page.visitChildren(IProviderStylePropertyChanges.class, new Component.IVisitor<Component>() { public Object component(Component component) { if (component instanceof IDisplayData && !((IDisplayData) component).isValueValid()) { invalidValueIds.add(component.getMarkupId()); } if (((IProviderStylePropertyChanges) component).getStylePropertyChanges() .isValueChanged()) { if (component.getParent().isVisibleInHierarchy()) { // the component will get added to the target & rendered only if it's parent is visible in hierarchy because changed flag is also set (see the visitor below) // so we will only list these components if they are visible otherwise ajax timer could end up sending hundreds of id's that don't actually render every 5 seconds // because the valueChanged flag is cleared only by onRender valueChangedIds.add(component.getMarkupId()); if (component instanceof MarkupContainer) { ((MarkupContainer) component).visitChildren(IDisplayData.class, new IVisitor<Component>() { public Object component(Component comp) { // labels/buttons that don't display data are not changed if (!(comp instanceof ILabel)) { valueChangedIds.add(comp.getMarkupId()); } return CONTINUE_TRAVERSAL; } }); } } } return CONTINUE_TRAVERSAL; } }); // add changed components to target; if a component is changed, the change check won't go deeper in hierarchy page.visitChildren(IProviderStylePropertyChanges.class, new Component.IVisitor<Component>() { public Object component(Component component) { if (((IProviderStylePropertyChanges) component).getStylePropertyChanges().isChanged()) { if (component.getParent().isVisibleInHierarchy()) { target.addComponent(component); generateDragAttach(component, target.getHeaderResponse()); WebForm parentForm = component.findParent(WebForm.class); boolean isDesignMode = parentForm != null && parentForm.isDesignMode(); if (!component.isVisible() || (component instanceof WrapperContainer && !((WrapperContainer) component).getDelegate().isVisible())) { ((IProviderStylePropertyChanges) component).getStylePropertyChanges() .setRendered(); if (isDesignMode) { target.appendJavascript("Servoy.ClientDesign.hideSelected('" + component.getMarkupId() + "')"); } } else { if (isDesignMode) { target.appendJavascript("Servoy.ClientDesign.refreshSelected('" + component.getMarkupId() + "')"); } // some components need to perform js layout tasks when their markup is replaced when using anchored layout mainPage.getPageContributor().markComponentForAnchorLayoutIfNeeded(component); } ListItem<IRecordInternal> row = component.findParent(ListItem.class); if (row != null) { WebCellBasedView wcbv = row.findParent(WebCellBasedView.class); if (wcbv != null) { if (tableViewsWithChangedRowIds.get(wcbv) == null) { tableViewsWithChangedRowIds.put(wcbv, new ArrayList<Integer>()); } List<Integer> ids = tableViewsWithChangedRowIds.get(wcbv); int changedRowIdx = wcbv.indexOf(row); if (changedRowIdx >= 0 && !ids.contains(changedRowIdx)) { ids.add(changedRowIdx); } } } } return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER; } else if (component instanceof WebCellBasedView) tableViewsToRender.add((WebCellBasedView) component); return component.isVisible() ? IVisitor.CONTINUE_TRAVERSAL : IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER; } }); page.visitChildren(IComponentToRequestAttacher.class, new Component.IVisitor<Component>() { public Object component(Component component) { ((IComponentToRequestAttacher) component).attachComponents(target); return IVisitor.CONTINUE_TRAVERSAL; } }); final List<String> visibleEditors = new ArrayList<String>(); page.visitChildren(WebDataHtmlArea.class, new Component.IVisitor<Component>() { public Object component(Component component) { visibleEditors.add(((WebDataHtmlArea) component).getEditorID()); return IVisitor.CONTINUE_TRAVERSAL; } }); StringBuffer argument = new StringBuffer(); for (String id : visibleEditors) { argument.append("\""); argument.append(id); argument.append("\""); if (visibleEditors.indexOf(id) != visibleEditors.size() - 1) { argument.append(","); } } target.prependJavascript("Servoy.HTMLEdit.removeInvalidEditors(" + argument + ");"); String rowSelectionScript, columnResizeScript; for (final WebCellBasedView wcbv : tableViewsToRender) { if (wcbv.isScrollMode()) wcbv.scrollViewPort(target, true); wcbv.updateRowSelection(target); List<Integer> changedIds = tableViewsWithChangedRowIds.get(wcbv); List<Integer> selectedIndexesChanged = wcbv.getIndexToUpdate(false); List<Integer> mergedIds = selectedIndexesChanged != null ? selectedIndexesChanged : new ArrayList<Integer>(); if (changedIds != null) { for (Integer id : changedIds) { if (!mergedIds.contains(id)) { mergedIds.add(id); } } } rowSelectionScript = wcbv.getRowSelectionScript(mergedIds); wcbv.clearSelectionByCellActionFlag(); if (rowSelectionScript != null) target.appendJavascript(rowSelectionScript); columnResizeScript = wcbv.getColumnResizeScript(); if (columnResizeScript != null) target.appendJavascript(columnResizeScript); } // double check if the page contributor is changed, because the above IStylePropertyChanges ischanged could have altered it. if (mainPage.getPageContributor().getStylePropertyChanges().isChanged()) { target.addComponent((Component) mainPage.getPageContributor()); } if (invalidValueIds.size() == 0) { target.appendJavascript("setValidationFailed(null);"); //$NON-NLS-1$ } else { target.appendJavascript("setValidationFailed('" + invalidValueIds.get(0) + "');"); //$NON-NLS-1$ } Component comp = mainPage.getAndResetToFocusComponent(); if (comp != null) { if (comp instanceof WebDataHtmlArea) { target.appendJavascript("tinyMCE.activeEditor.focus()"); } else { target.focusComponent(comp); } } else if (mainPage.getAndResetMustFocusNull()) { // This is needed for example when showing a non-modal dialog in IE7 (or otherwise // the new window would be displayed in the background). target.focusComponent(null); } if (valueChangedIds.size() > 0) { argument = new StringBuffer(); for (String id : valueChangedIds) { argument.append("\""); argument.append(id); argument.append("\""); if (valueChangedIds.indexOf(id) != valueChangedIds.size() - 1) { argument.append(","); } } target.prependJavascript("storeValueAndCursorBeforeUpdate(" + argument + ");"); target.appendJavascript("restoreValueAndCursorAfterUpdate();"); } //if we have admin info, show it String adminInfo = mainPage.getAdminInfo(); if (adminInfo != null) { adminInfo = Utils.stringReplace(adminInfo, "\r", ""); adminInfo = Utils.stringReplace(adminInfo, "\n", "\\n"); target.appendJavascript("alert('Servoy admin info : " + adminInfo + "');"); } // If we have a status text, set it. String statusText = mainPage.getStatusText(); if (statusText != null) { target.appendJavascript("setStatusText('" + statusText + "');"); } String show = mainPage.getShowUrlScript(); if (show != null) { target.appendJavascript(show); } mainPage.renderJavascriptChanges(target); if (((WebClientInfo) webClientSession.getClientInfo()).getProperties().isBrowserInternetExplorer() && ((WebClientInfo) webClientSession.getClientInfo()).getProperties() .getBrowserVersionMajor() < 9) { target.appendJavascript("Servoy.Utils.checkWebFormHeights();"); } try { if (isStyleSheetLimitForIE(page.getSession())) { target.appendJavascript("testStyleSheets();"); } } catch (Exception e) { Debug.error(e);//cannot retrieve session/clientinfo/properties? target.appendJavascript("testStyleSheets();"); } } } }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebEventExecutor.java
License:Open Source License
/** * @param component2//from w ww. ja v a 2s. c om * @param response */ @SuppressWarnings("nls") public static void generateDragAttach(Component component, IHeaderResponse response) { DraggableBehavior draggableBehavior = null; Component behaviorComponent = component; if ((behaviorComponent instanceof IComponent) && !(behaviorComponent instanceof IFormDataDragNDrop)) { behaviorComponent = (Component) component.findParent(IFormDataDragNDrop.class); } if (behaviorComponent != null) { Iterator<IBehavior> behaviors = behaviorComponent.getBehaviors().iterator(); Object behavior; while (behaviors.hasNext()) { behavior = behaviors.next(); if (behavior instanceof DraggableBehavior) { draggableBehavior = (DraggableBehavior) behavior; break; } } } if (draggableBehavior == null) return; boolean bUseProxy = draggableBehavior.isUseProxy(); boolean bResizeProxyFrame = draggableBehavior.isResizeProxyFrame(); boolean bXConstraint = draggableBehavior.isXConstraint(); boolean bYConstraint = draggableBehavior.isYConstraint(); CharSequence dragUrl = draggableBehavior.getCallbackUrl(); String jsCode = null; if (behaviorComponent instanceof IFormDataDragNDrop) { final StringBuilder sbAttachDrag = new StringBuilder(100); sbAttachDrag.append("Servoy.DD.attachDrag(["); final StringBuilder sbAttachDrop = new StringBuilder(100); sbAttachDrop.append("Servoy.DD.attachDrop(["); final boolean hasDragEvent = ((IFormDataDragNDrop) behaviorComponent).getDragNDropController().getForm() .getOnDragMethodID() > 0 || ((IFormDataDragNDrop) behaviorComponent).getDragNDropController().getForm() .getOnDragOverMethodID() > 0; final boolean hasDropEvent = ((IFormDataDragNDrop) behaviorComponent).getDragNDropController().getForm() .getOnDropMethodID() > 0; if (component instanceof WebDataRenderer || component instanceof WebCellBasedView) { if (hasDragEvent) sbAttachDrag.append('\'').append(component.getMarkupId()).append("',"); if (hasDropEvent) sbAttachDrop.append('\'').append(component.getMarkupId()).append("',"); if (component instanceof WebDataRenderer) { Iterator<? extends Component> dataRendererIte = ((WebDataRenderer) component).iterator(); Object dataRendererChild; while (dataRendererIte.hasNext()) { dataRendererChild = dataRendererIte.next(); if (dataRendererChild instanceof IWebFormContainer) continue; if (dataRendererChild instanceof WrapperContainer) dataRendererChild = ((WrapperContainer) dataRendererChild).getDelegate(); if (dataRendererChild instanceof IComponent && ((IComponent) dataRendererChild).isEnabled()) { updateDragAttachOutput(dataRendererChild, sbAttachDrag, sbAttachDrop, hasDragEvent, hasDropEvent); } } } else if (component instanceof WebCellBasedView) { ListView<IRecordInternal> table = ((WebCellBasedView) component).getTable(); table.visitChildren(new IVisitor<Component>() { public Object component(Component comp) { if (comp instanceof IComponent && comp.isEnabled()) { updateDragAttachOutput(comp, sbAttachDrag, sbAttachDrop, hasDragEvent, hasDropEvent); } return null; } }); } } else if (component != null && component.isEnabled()) { updateDragAttachOutput(component, sbAttachDrag, sbAttachDrop, hasDragEvent, hasDropEvent); } if (sbAttachDrag.length() > 25) { sbAttachDrag.setLength(sbAttachDrag.length() - 1); sbAttachDrag.append("],'"); sbAttachDrag.append(dragUrl); sbAttachDrag.append("', "); sbAttachDrag.append(bUseProxy); sbAttachDrag.append(", "); sbAttachDrag.append(bResizeProxyFrame); sbAttachDrag.append(", "); sbAttachDrag.append(bXConstraint); sbAttachDrag.append(", "); sbAttachDrag.append(bYConstraint); sbAttachDrag.append(");"); jsCode = sbAttachDrag.toString(); } if (sbAttachDrop.length() > 25) { sbAttachDrop.setLength(sbAttachDrop.length() - 1); sbAttachDrop.append("],'"); sbAttachDrop.append(dragUrl); sbAttachDrop.append("');"); if (jsCode != null) jsCode += '\n' + sbAttachDrop.toString(); else jsCode = sbAttachDrop.toString(); } if (jsCode != null) { if (response == null) { jsCode = (new StringBuilder().append("\n<script type=\"text/javascript\">\n").append(jsCode) .append("</script>\n")).toString(); Response cyleResponse = RequestCycle.get().getResponse(); cyleResponse.write(jsCode); } else response.renderOnDomReadyJavascript(jsCode); } } else //default handling { jsCode = "Servoy.DD.attachDrag(['" + component.getMarkupId() + "'],'" + dragUrl + "', " + bUseProxy + ", " + bResizeProxyFrame + ", " + bXConstraint + ", " + bYConstraint + ")"; if (response == null) { jsCode = (new StringBuilder().append("\n<script type=\"text/javascript\">\n").append(jsCode) .append("</script>\n")).toString(); Response cyleResponse = RequestCycle.get().getResponse(); cyleResponse.write(jsCode); } else response.renderOnDomReadyJavascript(jsCode); } }
From source file:com.servoy.j2db.server.headlessclient.DesignModeBehavior.java
License:Open Source License
/** * @see org.apache.wicket.ajax.AbstractDefaultAjaxBehavior#renderHead(org.apache.wicket.markup.html.IHeaderResponse) *//* www. j a va 2s .co m*/ @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); YUILoader.renderResize(response); final ArrayList<Component> markupIds = new ArrayList<Component>(); final ArrayList<Component> dropMarkupIds = new ArrayList<Component>(); ((MarkupContainer) getComponent()).visitChildren(IComponent.class, new IVisitor<Component>() { public Object component(Component component) { if (!(component instanceof WebDataRenderer)) { markupIds.add(component); if (component instanceof ITabPanel || component instanceof WebDataCalendar) { return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER; } } else if (component instanceof WebDataRenderer) { dropMarkupIds.add(component); } return IVisitor.CONTINUE_TRAVERSAL; } }); if (markupIds.size() > 0) { boolean webAnchorsEnabled = Utils.getAsBoolean( ((WebClientSession) Session.get()).getWebClient().getRuntimeProperties().get("enableAnchors")); //WebClientSession webClientSession = (WebClientSession)getSession(); //WebClient webClient = webClientSession.getWebClient(); ArrayList<String> selectedComponentsId = new ArrayList<String>(); StringBuilder sb = new StringBuilder(markupIds.size() * 10); sb.append("Servoy.ClientDesign.attach({"); for (int i = 0; i < markupIds.size(); i++) { Component component = markupIds.get(i); Object clientdesign_handles = null; if (component instanceof IScriptableProvider && ((IScriptableProvider) component).getScriptObject() instanceof IRuntimeComponent) { IRuntimeComponent sbmc = (IRuntimeComponent) ((IScriptableProvider) component) .getScriptObject(); if (sbmc.getName() == null) continue; //skip, elements with no name are not usable in CD clientdesign_handles = sbmc.getClientProperty(CLIENTDESIGN.HANDLES); Object clientdesign_selectable = sbmc.getClientProperty(CLIENTDESIGN.SELECTABLE); if (clientdesign_selectable != null && !Utils.getAsBoolean(clientdesign_selectable)) continue; //skip } String padding = "0px 0px 0px 0px"; //$NON-NLS-1$ if (component instanceof ISupportWebBounds) { Insets p = ((ISupportWebBounds) component).getPaddingAndBorder(); if (p != null) padding = "0px " + (p.left + p.right) + "px " + (p.bottom + p.top) + "px 0px"; } boolean editable = false; if (component instanceof IScriptableProvider && ((IScriptableProvider) component).getScriptObject() instanceof IRuntimeInputComponent) { editable = ((IRuntimeInputComponent) ((IScriptableProvider) component).getScriptObject()) .isEditable(); } String compId; if (webAnchorsEnabled && component instanceof IScriptableProvider && ((IScriptableProvider) component).getScriptObject() instanceof IRuntimeComponent && needsWrapperDivForAnchoring( ((IRuntimeComponent) ((IScriptableProvider) component).getScriptObject()) .getElementType(), editable)) { compId = component.getMarkupId() + TemplateGenerator.WRAPPER_SUFFIX; } else { compId = component.getMarkupId(); } sb.append(compId); if (component instanceof IComponent) { Iterator<IComponent> selectedComponentsIte = onSelectComponents.keySet().iterator(); IComponent c; while (selectedComponentsIte.hasNext()) { c = selectedComponentsIte.next(); if (c.getName().equals(((IComponent) component).getName())) { onSelectComponents.put(c, compId); selectedComponentsId.add(compId); break; } } } sb.append(":['"); sb.append(padding); sb.append("'"); if (clientdesign_handles instanceof Object[]) { sb.append(",["); Object[] array = (Object[]) clientdesign_handles; for (Object element : array) { sb.append('\''); sb.append(ScriptRuntime.escapeString(element.toString())); sb.append("',"); } sb.setLength(sb.length() - 1); //rollback last comma sb.append("]"); } sb.append("],"); } sb.setLength(sb.length() - 1); //rollback last comma sb.append("},'" + getCallbackUrl() + "')"); if (selectedComponentsId.size() > 0) { for (int i = 0; i < selectedComponentsId.size(); i++) { sb.append(";Servoy.ClientDesign.selectedElementId[").append(i).append("]='") .append(selectedComponentsId.get(i)).append("';"); } sb.append("Servoy.ClientDesign.reattach();"); } response.renderOnDomReadyJavascript(sb.toString()); // if (dropMarkupIds.size() > 0) // { // StringBuilder attachDrop = new StringBuilder(); // attachDrop.append("attachDrop(["); // for (int i = 0; i < dropMarkupIds.size(); i++) // { // Component component = dropMarkupIds.get(i); // attachDrop.append("'"); // attachDrop.append(component.getMarkupId()); // attachDrop.append("',"); // } // attachDrop.setLength(attachDrop.length() - 1); // attachDrop.append("])"); // response.renderOnDomReadyJavascript(attachDrop.toString()); // } } }