Search in sources :

Example 1 with JSEvent

use of com.servoy.j2db.scripting.JSEvent in project servoy-client by Servoy.

the class DesignModeBehavior method getJSEvent.

private JSEvent getJSEvent(EventType type, int modifiers, Point point, IComponent[] selected) {
    JSEvent event = new JSEvent();
    event.setFormName(controller.getName());
    event.setType(type);
    event.setModifiers(modifiers);
    event.setLocation(point);
    List<Object> selection = new ArrayList<Object>();
    if (selected != null) {
        for (IComponent component : selected) {
            if (component instanceof IScriptableProvider) {
                selection.add(0, ((IScriptableProvider) component).getScriptObject());
            } else {
                selection.add(0, component);
            }
        }
    }
    event.setData(selection.toArray());
    // event.setSource(e)
    return event;
}
Also used : JSEvent(com.servoy.j2db.scripting.JSEvent) IComponent(com.servoy.j2db.ui.IComponent) ArrayList(java.util.ArrayList) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider)

Example 2 with JSEvent

use of com.servoy.j2db.scripting.JSEvent in project servoy-client by Servoy.

the class BasicFormController method executeFunction.

@SuppressWarnings("nls")
protected Object executeFunction(Function f, Object[] args, Scriptable scope, Scriptable thisObject, boolean saveData, Object src, boolean testFindMode, boolean focusEvent, String methodKey, boolean executeWhenFieldValidationFailed, boolean useFormAsEventSourceEventually, boolean throwException) throws Exception {
    if (// only run certain methods in find
    !(testFindMode && isInFindMode())) {
        // this is a semi saveData , we do NOT want the record go out of edit(!) and is updated in db
        if (saveData) {
            application.getFoundSetManager().getEditRecordList().prepareForSave(false);
        }
        if (f != null) {
            if (!executeWhenFieldValidationFailed && Boolean.TRUE.equals(application.getRuntimeProperties().get(IServiceProvider.RT_LASTFIELDVALIDATIONFAILED_FLAG))) {
                if (Debug.tracing()) {
                    Debug.trace("Function not executed because a field is marked invalid");
                }
                return null;
            }
            FormAndComponent formAndComponent = getJSApplicationNames(src, f, useFormAsEventSourceEventually);
            try {
                currentFormExecutingFunctionCount.incrementAndGet();
                Object[] newArgs = args;
                if (formAndComponent != null) {
                    // for use of deprecated aplication.getMethodTriggerElementName() and aplication.getMethodTriggerFormName()
                    IExecutingEnviroment scriptEngine = application.getScriptEngine();
                    if (scriptEngine instanceof ScriptEngine) {
                        ((ScriptEngine) scriptEngine).getJSApplication().pushLastNames(formAndComponent);
                    }
                    if (methodKey != null) {
                        // add form event if needed
                        MethodTemplate methodTemplate = MethodTemplate.getTemplate(null, methodKey);
                        if (methodTemplate != null) {
                            MethodArgument[] methodArguments = methodTemplate.getArguments();
                            for (int i = 0; methodArguments != null && i < methodArguments.length; i++) {
                                if (methodArguments[i].getType() == ArgumentType.JSEvent) {
                                    // method template declares an event argument
                                    if (args == null || args.length <= i || args[i] == null) {
                                        // no event argument there yet, insert a form event
                                        JSEvent event = getJSEvent(formAndComponent.src, methodKey);
                                        if (args == null || args.length <= i) {
                                            newArgs = new Object[i + 1];
                                            if (args != null) {
                                                System.arraycopy(args, 0, newArgs, 0, args.length);
                                            }
                                        }
                                        newArgs[i] = event;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                if (newArgs != null && newArgs.length > 0) {
                    for (Object newArg : newArgs) {
                        if (newArg instanceof JSEvent) {
                            JSEvent event = (JSEvent) newArg;
                            if (formScope != null && event.getSource() instanceof IComponent && ((IComponent) event.getSource()).getName() != null) {
                                Object elementScope = formScope.get("elements");
                                if (elementScope instanceof Scriptable) {
                                    Object elementSrc = ((Scriptable) elementScope).get(((IComponent) event.getSource()).getName(), (Scriptable) elementScope);
                                    if (elementSrc != null) {
                                        if (elementSrc instanceof ITwoNativeJavaObject) {
                                            Object scriptable = event.getSource();
                                            if (scriptable instanceof IScriptableProvider) {
                                                scriptable = ((IScriptableProvider) scriptable).getScriptObject();
                                            }
                                            ((ITwoNativeJavaObject) elementSrc).setRealObject(scriptable);
                                        }
                                        event.setSource(elementSrc);
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                return application.getScriptEngine().executeFunction(f, scope, thisObject, newArgs, focusEvent, throwException);
            } finally {
                currentFormExecutingFunctionCount.decrementAndGet();
                if (formAndComponent != null) {
                    IExecutingEnviroment scriptEngine = application.getScriptEngine();
                    if (scriptEngine instanceof ScriptEngine) {
                        ((ScriptEngine) scriptEngine).getJSApplication().popLastStackNames(formAndComponent);
                    }
                }
                // after a script clear the unchanged records so that no records keep hanging around.
                if (!focusEvent && !"onRecordEditStopMethodID".equals(methodKey) && !"onRenderMethodID".equals(methodKey) && application.getFoundSetManager() != null) {
                    application.getFoundSetManager().getEditRecordList().removeUnChangedRecords(false, false);
                }
            }
        }
    }
    return null;
}
Also used : IExecutingEnviroment(com.servoy.j2db.scripting.IExecutingEnviroment) JSEvent(com.servoy.j2db.scripting.JSEvent) MethodArgument(com.servoy.j2db.persistence.MethodArgument) IComponent(com.servoy.j2db.ui.IComponent) MethodTemplate(com.servoy.j2db.persistence.MethodTemplate) Scriptable(org.mozilla.javascript.Scriptable) FormAndComponent(com.servoy.j2db.scripting.JSApplication.FormAndComponent) ScriptEngine(com.servoy.j2db.scripting.ScriptEngine) ITwoNativeJavaObject(com.servoy.j2db.scripting.ITwoNativeJavaObject) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) ITwoNativeJavaObject(com.servoy.j2db.scripting.ITwoNativeJavaObject) IScriptableProvider(com.servoy.j2db.scripting.IScriptableProvider)

Example 3 with JSEvent

use of com.servoy.j2db.scripting.JSEvent in project servoy-client by Servoy.

the class ColumnSortListener method getJavaScriptEvent.

public JSEvent getJavaScriptEvent(MouseEvent e, JSEvent.EventType type, String sourceName) {
    JSEvent event = new JSEvent();
    event.setType(type);
    if (fc != null)
        event.setFormName(fc.getName());
    event.setElementName(sourceName);
    event.setModifiers(e.getModifiers() == IEventExecutor.MODIFIERS_UNSPECIFIED ? 0 : e.getModifiers());
    return event;
}
Also used : JSEvent(com.servoy.j2db.scripting.JSEvent)

Example 4 with JSEvent

use of com.servoy.j2db.scripting.JSEvent in project servoy-client by Servoy.

the class FoundsetTypeSabloValue method browserUpdatesReceived.

public void browserUpdatesReceived(Object jsonValue, PropertyDescription pd, IBrowserConverterContext dataConverterContext) {
    PushToServerEnum pushToServer = BrowserConverterContext.getPushToServerValue(dataConverterContext);
    if (getFoundset() == null)
        return;
    try {
        if (jsonValue instanceof JSONArray) {
            JSONArray arr = (JSONArray) jsonValue;
            for (int i = 0; i < arr.length(); i++) {
                JSONObject update = (JSONObject) arr.get(i);
                // {newViewPort: {startIndex : startIndex, size : size}}
                if (update.has("newViewPort")) {
                    JSONObject newViewport = update.getJSONObject("newViewPort");
                    int requestID = update.getInt(ID_KEY);
                    viewPort.clearSendingInitialPreferredViewport();
                    viewPort.setBounds(newViewport.getInt(START_INDEX), newViewport.getInt(SIZE));
                    changeMonitor.requestIdHandled(requestID, true);
                }
                if (update.has(PREFERRED_VIEWPORT_SIZE)) {
                    viewPort.setPreferredViewportSize(update.getInt(PREFERRED_VIEWPORT_SIZE));
                    if (update.has(FoundsetPropertyTypeConfig.SEND_SELECTION_VIEWPORT_INITIALLY))
                        viewPort.setSendSelectionViewportInitially(update.getBoolean(FoundsetPropertyTypeConfig.SEND_SELECTION_VIEWPORT_INITIALLY));
                    if (update.has(INITIAL_SELECTION_VIEWPORT_CENTERED))
                        viewPort.setInitialSelectionViewportCentered(update.getBoolean(INITIAL_SELECTION_VIEWPORT_CENTERED));
                } else // {loadExtraRecords: negativeOrPositiveCount}
                if (update.has("loadExtraRecords")) {
                    int requestID = update.getInt(ID_KEY);
                    viewPort.clearSendingInitialPreferredViewport();
                    viewPort.loadExtraRecords(update.getInt("loadExtraRecords"));
                    changeMonitor.requestIdHandled(requestID, true);
                } else // {loadLessRecords: negativeOrPositiveCount}
                if (update.has("loadLessRecords")) {
                    int requestID = update.getInt(ID_KEY);
                    viewPort.clearSendingInitialPreferredViewport();
                    viewPort.loadLessRecords(update.getInt("loadLessRecords"));
                    changeMonitor.requestIdHandled(requestID, true);
                } else if (update.has("sort")) {
                    int requestID = update.getInt(ID_KEY);
                    JSONArray columns = update.getJSONArray("sort");
                    StringBuilder sort = new StringBuilder();
                    Map<String, String> dp = dataproviders.size() > 0 ? dataproviders : recordDataLinkedPropertyIDToColumnDP;
                    String dataProviderID = null;
                    boolean sortAscending = true;
                    for (int j = 0; j < columns.length(); j++) {
                        JSONObject sortColumn = columns.getJSONObject(j);
                        String name = sortColumn.getString("name");
                        if (dp.containsKey(name)) {
                            sort.append(dp.get(name));
                            sort.append(" " + sortColumn.getString("direction"));
                            if (dataProviderID == null) {
                                dataProviderID = dp.get(name);
                                sortAscending = "asc".equalsIgnoreCase(sortColumn.getString("direction"));
                            }
                            if (j < columns.length() - 1)
                                sort.append(",");
                        }
                    }
                    IWebFormUI formUI = getFormUI();
                    IWebFormController fc = (formUI != null ? formUI.getController() : null);
                    if (fc != null && fc.getForm().getOnSortCmdMethodID() > 0 && dataProviderID != null) {
                        // our api only supports one dataproviderid sort at a time
                        JSEvent event = new JSEvent();
                        event.setFormName(fc.getName());
                        fc.executeFunction(String.valueOf(fc.getForm().getOnSortCmdMethodID()), Utils.arrayMerge((new Object[] { dataProviderID, Boolean.valueOf(sortAscending), event }), // $NON-NLS-1$
                        Utils.parseJSExpressions(fc.getForm().getFlattenedMethodArguments("onSortCmdMethodID"))), true, null, false, // $NON-NLS-1$
                        "onSortCmdMethodID");
                    } else {
                        try {
                            String currentSort = foundset.getSort();
                            String newSort = sort.toString();
                            foundset.setSort(newSort);
                            if (// really a new sort
                            !Utils.equalObjects(currentSort, newSort) || // not sorted, send back to client
                            !Utils.equalObjects(foundset.getSort(), newSort)) {
                                changeMonitor.foundsetSortChanged();
                            }
                        } catch (ServoyException e) {
                            Debug.error("Cannot sort foundset by " + sort.toString(), e);
                        }
                    }
                    changeMonitor.requestIdHandled(requestID, true);
                } else // {newClientSelection: newSelectedIndexesArray}
                if (update.has("newClientSelection")) {
                    JSONArray jsonSelectedIndexes = update.getJSONArray("newClientSelection");
                    int[] newSelectedIndexes = new int[jsonSelectedIndexes.length()];
                    for (int j = newSelectedIndexes.length - 1; j >= 0; j--) {
                        newSelectedIndexes[j] = jsonSelectedIndexes.getInt(j);
                    }
                    // this !Arrays.equals check in conjunction with pause()/resume() is needed to avoid an effect on the client that server always sends back changed selection in which case
                    // if the user quickly changes selection multiple times and the connection is slow, selection will jump all over
                    // the place until it stabilizes correctly
                    getListSelectionListener().pause();
                    try {
                        if (newSelectedIndexes.length == 1) {
                            foundset.setSelectedIndex(newSelectedIndexes[0]);
                        } else {
                            foundset.setSelectedIndexes(newSelectedIndexes);
                        }
                    } finally {
                        getListSelectionListener().resume();
                        // if server denies the new selection as invalid and doesn't change selection, send it to the client so that it doesn't keep invalid selection
                        if (!Arrays.equals(foundset.getSelectedIndexes(), newSelectedIndexes)) {
                            changeMonitor.selectionChanged(false);
                        }
                    }
                } else // {newClientSelectionRequest: newSelectedIndexesArray}
                if (update.has("newClientSelectionRequest")) {
                    int requestID = update.getInt(ID_KEY);
                    JSONArray jsonSelectedIndexes = update.getJSONArray("newClientSelectionRequest");
                    int[] newSelectedIndexes = new int[jsonSelectedIndexes.length()];
                    for (int j = newSelectedIndexes.length - 1; j >= 0; j--) {
                        newSelectedIndexes[j] = jsonSelectedIndexes.getInt(j);
                    }
                    int[] oldSelection = foundset.getSelectedIndexes();
                    // this !Arrays.equals check in conjunction with pause()/resume() is needed to avoid an effect on the client that server always sends back changed selection in which case
                    // if the user quickly changes selection multiple times and the connection is slow, selection will jump all over
                    // the place until it stabilizes correctly
                    getListSelectionListener().pause();
                    try {
                        if (newSelectedIndexes.length == 1) {
                            foundset.setSelectedIndex(newSelectedIndexes[0]);
                        } else {
                            foundset.setSelectedIndexes(newSelectedIndexes);
                        }
                    } finally {
                        getListSelectionListener().resume();
                        if (!Arrays.equals(oldSelection, foundset.getSelectedIndexes())) {
                            // if the selection is changed, send it back to the client so that its model is also updated
                            changeMonitor.selectionChanged(false);
                            changeMonitor.requestIdHandled(requestID, true);
                        } else {
                            if (!Arrays.equals(oldSelection, newSelectedIndexes)) {
                                // it was supposed to change but the server did not allow it
                                changeMonitor.requestIdHandled(requestID, false);
                            } else
                                changeMonitor.requestIdHandled(requestID, true);
                        }
                    }
                } else if (update.has(ViewportDataChangeMonitor.VIEWPORT_CHANGED)) {
                    if (PushToServerEnum.allow.compareTo(pushToServer) <= 0) {
                        // {dataChanged: { ROW_ID_COL_KEY: rowIDValue, dataproviderName: value }}
                        JSONObject dataChangeJSON = (JSONObject) update.get(ViewportDataChangeMonitor.VIEWPORT_CHANGED);
                        String rowIDValue = dataChangeJSON.getString(ROW_ID_COL_KEY);
                        String dpKey = dataChangeJSON.getString(DATAPROVIDER_KEY);
                        String dataProviderName;
                        if (dataproviders.containsKey(dpKey)) {
                            dataProviderName = dataproviders.get(dpKey);
                        } else {
                            dataProviderName = recordDataLinkedPropertyIDToColumnDP.get(dpKey);
                        }
                        Object value = dataChangeJSON.get(VALUE_KEY);
                        if (foundset != null) {
                            Pair<String, Integer> splitHashAndIndex = splitPKHashAndIndex(rowIDValue);
                            int recordIndex = foundset.getRecordIndex(splitHashAndIndex.getLeft(), splitHashAndIndex.getRight().intValue());
                            if (recordIndex != -1) {
                                IRecordInternal record = foundset.getRecord(recordIndex);
                                // convert Dates where it's needed
                                // this should be enough for when only foundset dataproviders are used
                                PropertyDescription dataProviderPropDesc = getDataProviderPropertyDescription(dataProviderName);
                                ValueReference<Boolean> returnValueAdjustedIncommingValueForRow = new ValueReference<Boolean>(Boolean.FALSE);
                                value = JSONUtils.fromJSONUnwrapped(null, value, dataProviderPropDesc, dataConverterContext, returnValueAdjustedIncommingValueForRow);
                                try {
                                    if (record.startEditing()) {
                                        try {
                                            record.setValue(dataProviderName, value);
                                        } catch (IllegalArgumentException e) {
                                            // TODO handle the validaton errors.
                                            IWebFormUI formUI = getFormUI();
                                            formUI.getController().getApplication().reportError("Validation for " + dataProviderName + " for value: " + value + " failed.", e);
                                        }
                                    }
                                // else cannot start editing; finally block will deal with it (send old value back to client as new one can't be pushed)
                                } finally {
                                    // if server denies the new value as invalid and doesn't change it, send it to the client so that it doesn't keep invalid value; the same if for example a double was rounded to an int
                                    if (!Utils.equalObjects(record.getValue(dataProviderName), value) || returnValueAdjustedIncommingValueForRow.value.booleanValue()) {
                                        changeMonitor.recordsUpdated(recordIndex, recordIndex, foundset.getSize(), viewPort, Arrays.asList(new String[] { dataProviderName }));
                                    }
                                }
                            } else {
                                Debug.error("Cannot set foundset record (" + rowIDValue + ") dataprovider '" + dataProviderName + "' to value '" + value + ". Record not found.");
                            }
                        }
                    } else {
                        log.error("Property (" + pd + ") that doesn't define a suitable pushToServer value (allow/shallow/deep) tried to modify foundset dataprovider value serverside. Denying and sending back full viewport!");
                        changeMonitor.viewPortCompletelyChanged();
                    }
                }
            }
        }
    } catch (JSONException e) {
        Debug.error("Error when getting browser updates for property (" + this.toString() + ") for " + jsonValue, e);
    }
}
Also used : JSEvent(com.servoy.j2db.scripting.JSEvent) IRecordInternal(com.servoy.j2db.dataprocessing.IRecordInternal) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IWebFormController(com.servoy.j2db.server.ngclient.IWebFormController) ServoyException(com.servoy.j2db.util.ServoyException) PropertyDescription(org.sablo.specification.PropertyDescription) IWebFormUI(com.servoy.j2db.server.ngclient.IWebFormUI) JSONObject(org.json.JSONObject) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) JSONObject(org.json.JSONObject) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) PushToServerEnum(org.sablo.specification.WebObjectSpecification.PushToServerEnum) Map(java.util.Map) HashMap(java.util.HashMap) ValueReference(org.sablo.util.ValueReference)

Example 5 with JSEvent

use of com.servoy.j2db.scripting.JSEvent in project servoy-client by Servoy.

the class WebFormController method getJSEvent.

@Override
protected JSEvent getJSEvent(Object src, String eventName) {
    JSEvent event = new JSEvent();
    event.setType(JSEvent.EventType.form);
    if (eventName != null)
        event.setName(RepositoryHelper.getDisplayName(eventName, Form.class));
    event.setFormName(getName());
    event.setSource(src);
    if (src instanceof WebFormComponent)
        event.setElementName(((WebFormComponent) src).getFormElement().getRawName());
    else
        event.setElementName(src instanceof WebComponent ? ((WebComponent) src).getName() : null);
    return event;
}
Also used : WebComponent(org.sablo.WebComponent) JSEvent(com.servoy.j2db.scripting.JSEvent) WebFormComponent(com.servoy.j2db.server.ngclient.WebFormComponent)

Aggregations

JSEvent (com.servoy.j2db.scripting.JSEvent)11 JSONObject (org.json.JSONObject)4 IComponent (com.servoy.j2db.ui.IComponent)3 IJSEvent (com.servoy.base.scripting.api.IJSEvent)2 FormController (com.servoy.j2db.FormController)2 Form (com.servoy.j2db.persistence.Form)2 IPersist (com.servoy.j2db.persistence.IPersist)2 IScriptableProvider (com.servoy.j2db.scripting.IScriptableProvider)2 WebFormComponent (com.servoy.j2db.server.ngclient.WebFormComponent)2 ServoyException (com.servoy.j2db.util.ServoyException)2 ArrayList (java.util.ArrayList)2 JSONException (org.json.JSONException)2 Scriptable (org.mozilla.javascript.Scriptable)2 PropertyDescription (org.sablo.specification.PropertyDescription)2 FoundSetListWrapper (com.servoy.j2db.dataprocessing.FoundSetListWrapper)1 FoundSetManager (com.servoy.j2db.dataprocessing.FoundSetManager)1 IFoundSetInternal (com.servoy.j2db.dataprocessing.IFoundSetInternal)1 IRecord (com.servoy.j2db.dataprocessing.IRecord)1 IRecordInternal (com.servoy.j2db.dataprocessing.IRecordInternal)1 SortColumn (com.servoy.j2db.dataprocessing.SortColumn)1