// send a netlogo command asynchronously; receive notice of completion at this callback public void asynchronousCommand(final String cmd, final String callback) { final JSObject window = JSObject.getWindow(this); if (SwingUtilities.isEventDispatchThread()) { Thread t = new Thread("command thread off of EDT") { public void run() { try { panel().command(cmd); window.call(callback, null); } catch (CompilerException e) { e.printStackTrace(); } } }; t.start(); } else { try { panel().command(cmd); window.call(callback, null); } catch (CompilerException e) { e.printStackTrace(); } } }
// evaluate a netlogo report asynchronously; return the result to this callback as the argument public void asynchronousReport(final String cmd, final String callback) { final JSObject window = JSObject.getWindow(this); if (SwingUtilities.isEventDispatchThread()) { Thread t = new Thread("reporter thread off of EDT") { public void run() { Object retval = null; try { retval = panel().report(cmd); Object[] args = {retval}; window.call(callback, args); } catch (CompilerException e) { e.printStackTrace(); } } }; t.start(); } else { Object retval = null; try { retval = panel().report(cmd); Object[] args = {retval}; window.call(callback, args); } catch (CompilerException e) { e.printStackTrace(); } } }
/** * Return Javascript code that can be called on this JSObject to return the attribute to its * present state */ public String getRestoreMethod(String attr) { attr = attr.intern(); if (attr == SRC_ATTR) { return "src=\"" + jsObject.getMember("src") + "\""; } if (attr == VALUE_ATTR) { String value = getString(); if (nodeName == OBJECT_NAME) return "setString('" + escapeNewlines(value) + "')"; // FIX implement SPAN_NAME // FIX implement INPUT_NAME (including radio and checkbox) if (nodeName == TEXTAREA_NAME) return "value='" + value + "'"; } if (attr == DISABLED_ATTR) { if (nodeName == OBJECT_NAME || nodeName == APPLET_NAME) { // FIX add setDisabled() method to EmbeddedEditorApplet } if (nodeName == SPAN_NAME) { return ""; // spans are never "enabled" anyway } if (nodeName == INPUT_NAME) { // FIX handle radio and checkboxes return "disabled=" + jsObject.getMember("disabled"); } if (nodeName == TEXTAREA_NAME) return "disabled=" + jsObject.getMember("disabled"); } // inert return "unimplemented=" + attr; }
public void setClient(WebView view) { this.view = view; this.engine = view.getEngine(); JSObject window = (JSObject) engine.executeScript("window"); window.setMember("ide", this); Collection<IEclipseToBrowserFunction> onLoadFunctions = new ArrayList<IEclipseToBrowserFunction>(); IConfigurationElement[] extensions = BrowserExtensions.getExtensions( BrowserExtensions.EXTENSION_ID_ECLIPSE_TO_BROWSER, null, view.getEngine().locationProperty().get()); for (IConfigurationElement element : extensions) { try { String onLoad = element.getAttribute(BrowserExtensions.ELEMENT_ONLOAD); if (onLoad != null && onLoad.equals("true")) { onLoadFunctions.add( (IEclipseToBrowserFunction) WorkbenchPlugin.createExtension(element, BrowserExtensions.ELEMENT_CLASS)); } } catch (CoreException ex) { StatusManager.getManager() .handle( new Status( IStatus.ERROR, IdeUiPlugin.PLUGIN_ID, "Could not instantiate browser element provider extension.", ex)); return; } } callOnBrowser(onLoadFunctions); }
/** * Gets a list of all available command and keyboard shortcuts * * @deprecated for internal usage only. * @return list of available commands */ @Deprecated public ArrayList<Command> getCommandList() { JSObject names = (JSObject) mEditor.getModel().eval("this.commands.byName"); ArrayList<Command> arr = new ArrayList<>(); for (String str : Commons.getAllProperties(names)) { arr.add(new Command((JSObject) names.getMember(str))); } return arr; }
/** Redirects to screenbird homepage. */ private void redirectWebPage() { try { JSObject win = JSObject.getWindow(this); System.out.println("Redirecting window"); win.call("redirectHome", new Object[] {}); System.out.println("Redirected window"); } catch (Exception e) { System.err.println(e); System.err.println("Window already closed"); } }
/** * Reads all available cookies * * @return The complete cookie string */ protected String getCookie() { /* ** get all cookies for a document */ try { JSObject myBrowser = JSObject.getWindow(applet); JSObject myDocument = (JSObject) myBrowser.getMember("document"); String myCookie = (String) myDocument.getMember("cookie"); if (myCookie != null && myCookie.length() > 0) return myCookie; } catch (Exception e) { LOG.error("getCookie failed", e); } return "?"; }
/** * Using the Javascript located on the web page which opened this applet, we close the web page; * thus closing the applet with it. */ public boolean closeApplet() { try { JSObject win = JSObject.getWindow(this); System.out.println("Closing window"); win.call("closeRecorderForm", new Object[] {}); System.out.println("Closed window"); } catch (Exception e) { System.err.println(e); System.err.println("Window already closed"); } return false; }
public static String getCookie() { try { JSObject myDocument = (JSObject) jsBrowserWindow.getMember("document"); String myCookie = (String) myDocument.getMember("cookie"); Log.log("cookie: " + myCookie); if (myCookie.length() > 0) { return myCookie; } } catch (Exception e) { Log.log("Error getting cookie", e); } return ""; }
/** Inicia la ejecución del applet */ public void start() { Log.log("Starting Applet"); if (running) { return; } running = true; boolean jsObjectFound = false; jsBrowserWindow = null; try { Class.forName("netscape.javascript.JSObject"); jsObjectFound = true; } catch (Exception e) { Log.log("Error instantiating JSObject class", e); } if (jsObjectFound) { try { jsBrowserWindow = JSObject.getWindow(this); Log.log("jsBrowserWindow: " + jsBrowserWindow); } catch (Exception e) { Log.log("Error in JSObject", e); } } Log.log("Applet Started"); }
/* */ private static void report(JSObject js, Record r) /* */ { /* 179 */ long now = System.nanoTime(); /* 180 */ long offset = (r.tm - now) / 1000000L; /* 181 */ String label = r.label; /* */ /* 183 */ if (lastReported == 0L) { /* 184 */ firstReported = now; /* */ } /* */ /* 188 */ if (lastReported != 0L) { /* 189 */ label = "[" + (now - firstReported + 500000L) / 1000000L + " ms" + "(delta=" + (now - lastReported + 500000L) / 1000000L + ")] " + label; /* */ } /* */ /* 196 */ Trace.println("PERFLOG: report [" + label + "]"); /* 197 */ js.eval( "if (typeof perfLog == 'function') { perfLog(" + offset + ", '" + label + "');}"); /* */ /* 199 */ lastReported = now; /* */ }
@Override public void init() { this.printer = new PrinterController(this); this.pos = new PosController(this); this.window = JSObject.getWindow(this); this.log("[Applet] Запущен"); }
// Call a javascript function. Valid arguments can null, string and numbers. private synchronized void _func_call(String func, Collection args) throws Exception { ArrayList new_args = (ArrayList) prepare_call_args(args); String js_call = func + "(" + KMisc.list_join(new_args, ", ") + ")"; JSObject.getWindow(this.applet_obj).eval("javascript:" + js_call); KMisc.sleep_ms(15); // It seems like (some browsers at least) // do not support rapid successive calls. }
public void componentShown(ComponentEvent evt) { // sets the security manager to fix a bug in liveconnect in Safari on Mac if (key != -1) { return; } window = (JSObject) JSObject.getWindow(applet()); AccessController.doPrivileged( new PrivilegedAction() { public Object run() { log("> init Robot"); try { SecurityManager oldsecurity = System.getSecurityManager(); boolean isOpera = false; try { isOpera = (System.getProperty("browser").equals("Opera.plugin")); } catch (Exception e) { } try { securitymanager = oldsecurity; securitymanager.checkTopLevelWindow(null); // xdomain if (charMap == null) { if (!confirm( "DOH has detected that the current Web page is attempting to access DOH, but belongs to a different domain than the one you agreed to let DOH automate. If you did not intend to start a new DOH test by visiting this Web page, press Cancel now and leave the Web page. Otherwise, press OK to trust this domain to automate DOH tests.")) { stop(); return null; } } log("Found old security manager"); } catch (Exception e) { e.printStackTrace(); log("Making new security manager"); securitymanager = new RobotSecurityManager(isOpera, oldsecurity); securitymanager.checkTopLevelWindow(null); System.setSecurityManager(securitymanager); } // instantiate the Robot robot = new Robot(); } catch (Exception e) { log("Error calling _init_: " + e.getMessage()); key = -2; e.printStackTrace(); } log("< init Robot"); return null; } }); if (key == -2) { // applet not trusted // start the test without it window.eval("doh.robot._appletDead=true;doh.run();"); } else { // now that the applet has really started, let doh know it's ok to use it log("_initRobot"); dohrobot = (JSObject) window.eval("doh.robot"); dohrobot.call("_initRobot", new Object[] {applet()}); } }
public void alert(String s) { if (jso != null) try { jso.call("alert", new String[] {s}); } catch (Exception ex) { ex.printStackTrace(); } }
/** Register instances of the bridge classes as javascript objects */ private void addJSBridges() { // create the Java object in a scope where they won't be collected by the GC JSBridge jsobjBridge = new JSBridge(); FeedbackUtil jsobjFeedbackUtil = new FeedbackUtil(); webEngine .getLoadWorker() .stateProperty() .addListener( (ov, oldState, newState) -> { if (newState == State.SUCCEEDED) { JSObject jsobj = (JSObject) webEngine.executeScript("window"); jsobj.setMember("java", jsobjBridge); jsobj.setMember("feedbackUtil", jsobjFeedbackUtil); webEngine.executeScript("javaReady();"); } }); }
/** * Set the source accessor. * * <p>The purpose of the source accessor is to return an object that describes the starting arc of * the chord. The returned object is subsequently passed to the {@link #radius(DatumFunction)}, * {@link #startAngle(DatumFunction)} and {@link #endAngle(DatumFunction)} accessors. * * <p>This allows these other accessors to be reused for both the source and target arc * descriptions. * * <p>The default accessor assumes that the input data is a JavaScriptObject with suitably-named * attributes. * * <p>The source-accessor is invoked in the same manner as other value functions in D3. * * <p> * * @param accessor the function returning the source arc object * @return the current chord generator */ public Chord source(final DatumFunction<?> accessor) { assertObjectIsNotAnonymous(accessor); JSObject d3JsObject = getD3(); String accessorName = createNewTemporaryInstanceName(); d3JsObject.setMember(accessorName, accessor); String command = "this.source(function(d, i) { " // + "return d3." + accessorName + ".apply(this,{datum:d},i);" // + " });"; JSObject result = evalForJsObject(command); return new Chord(webEngine, result); }
@Override public void switchChanged(String name, boolean value, boolean arg2) { String val = "NO"; if (value) { val = "YES"; } Object[] args = {"switch-changed", name, val}; window.call(callback, args); }
/** * Set the size of the symbols using the specified function returning an integer. * * <p> * * @param sizeAccessorFunction the function that return the {@link DragEventType} of symbol. * @return this instance for chaining */ public Symbol size(DatumFunction<Integer> sizeAccessorFunction) { assertObjectIsNotAnonymous(sizeAccessorFunction); JSObject d3JsObject = getD3(); String accessorName = createNewTemporaryInstanceName(); d3JsObject.setMember(accessorName, sizeAccessorFunction); String command = "this.size(function(d, i) {" // + "return d3." + accessorName + ".apply(this,{datum:d},i);" // + " });"; JSObject result = evalForJsObject(command); return new Symbol(webEngine, result); }
/** @return the postcodeLocalities */ public List<String> getPostcodeLocalities() { final List<String> result = new ArrayList<>(); try { if (!(jsObject.getMember("postcode_localities") instanceof String)) { List<JSObject> jsLocalities = GeocoderUtils.getJSObjectsFromArray( (JSObject) jsObject.getMember("postcode_localities")); for (JSObject jsLocality : jsLocalities) { String text = jsLocality.toString(); if (text != null && !text.isEmpty() && !text.equals("undefined")) { result.add(text); } } } } catch (Exception e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "", e); } return result; }
@FXML private void setCode() { if (submission.getSelectionModel().isEmpty()) return; try { obj.call( "setCode", api.getCode( submission.getSelectionModel().getSelectedItem().getId(), contest.getSelectionModel().getSelectedItem().getValue())); } catch (Exception e) { getAlert(e, "提出コードの取得に失敗しました。").show(); return; } languageLabel.setText(submission.getSelectionModel().getSelectedItem().getLanguage()); Extension lang = Extension.of(languageLabel.getText()); if (Stream.of(Extension.C, Extension.CPP).anyMatch(e -> e.equals(lang))) obj.call("setMode", "c_cpp"); else obj.call("setMode", lang.toString().toLowerCase()); }
/** * Delete a cookie * * @param name The name of the cookie */ protected void deleteCookie(String name) { setCookie(name, " "); /* ** delete a cookie, set the expiration in the past */ java.util.Calendar c = java.util.Calendar.getInstance(); c.add(java.util.Calendar.MONTH, -1); String expires = "; expires=" + c.getTime().toString(); String s1 = name + expires; try { JSObject myBrowser = JSObject.getWindow(applet); JSObject myDocument = (JSObject) myBrowser.getMember("document"); LOG.debug("del: " + s1); myDocument.setMember("cookie", s1); } catch (JSException e) { LOG.error("deleteCookie " + name + " failed", e); } }
public boolean hasFocus() { try { return ((Boolean) window.eval( "var result=false;if(window.parent.document.hasFocus){result=window.parent.document.hasFocus();}else{result=true;}result;")) .booleanValue(); } catch (Exception e) { // runs even after you close the window! return false; } }
@Override public void sliderChanged( String name, double value, double min, double incr, double max, boolean arg5, boolean arg6) { Object[] args = {"slider-changed", name, value, min, incr, max}; window.call(callback, args); }
public void workerStateChanged( ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) { if (newValue == Worker.State.READY || newValue == Worker.State.SCHEDULED) { if (trafficBrowser != null) { trafficBrowser.setStartTime(Instant.now()); trafficBrowser.getTraffic().clear(); } numberOfAlerts.setValue("0"); } else if (newValue == Worker.State.SUCCEEDED) { JSObject result = (JSObject) webEngine.executeScript("window"); result.setMember( "burpCallbacks", new BurpExtenderCallbacksBridge(webEngine, BurpExtender.getBurpExtenderCallbacks())); result.setMember("burpKit", javaScriptHelpers); // result.setMember("locals", locals); // // result.setMember("globals", globals); if (controller != null) { result.setMember("burpController", controller); } } else if (newValue == Worker.State.FAILED) { dialog .title("Navigation Failed") .message(webEngine.getLoadWorker().getException().getMessage()) .showInformation(); resetParents(); } else if (newValue == Worker.State.CANCELLED) { dialog .title("Navigation Cancelled") .message(webEngine.getLoadWorker().getMessage()) .showInformation(); resetParents(); } }
/** * Write a cookie * * @param name The name of the cookie * @param value The value to write */ protected void setCookie(String name, String value) { value = cleanValue(value); /* ** write a cookie ** computes the expiration date, good for 1 month */ java.util.Calendar c = java.util.Calendar.getInstance(); c.add(java.util.Calendar.YEAR, 1); String expires = "; expires=" + c.getTime().toString(); String s1 = name + "=" + value + expires; LOG.debug(s1); try { JSObject myBrowser = JSObject.getWindow(applet); JSObject myDocument = (JSObject) myBrowser.getMember("document"); myDocument.setMember("cookie", s1); LOG.debug("set:" + s1); } catch (JSException e) { LOG.error("setCookie " + name + "=" + value + " failed", e); } }
/** * Registers the specified listener to receive events of the specified type from the zoom * behavior. * * <p>See {@link ZoomEventType} for more information. * * <p>If an event listener was already registered for the same type, the existing listener is * removed before the new listener is added. TODO: To register multiple listeners for the same * event type, the type may be followed by an optional namespace, such as "zoom.foo" and * "zoom.bar". To remove a listener, pass null as the listener. * * <p>For mousewheel events, which happen discretely with no explicit start and end reported by * the browser, events that occur within 50 milliseconds of each other are grouped into a single * zoom gesture. If you want more robust interpretation of these gestures, please petition your * browser vendor of choice for better touch event support. * * <p> * * @param type * @param listener * @return the current zoom instance */ public Zoom on(ZoomEventType type, DatumFunction<Void> listener) { assertObjectIsNotAnonymous(listener); String listenerName = createNewTemporaryInstanceName(); JSObject d3JsObject = getD3(); d3JsObject.setMember(listenerName, listener); String eventName = type.name().toLowerCase(); String command = "this.on('" + eventName + "', " + "function(d, index) { " // + "d3." + listenerName + ".apply(this,{datum:d},index);" // + " });"; JSObject result = evalForJsObject(command); return new Zoom(webEngine, result); }
// export world to a string variable which is passed as an argument to the js callback function public void exportWorldStateAsynchronously(final String callback) { final JSObject window = JSObject.getWindow(this); org.nlogo.awt.EventQueue.invokeLater( new Runnable() { public void run() { StringWriter sw = new StringWriter(); panel() .workspace() .exportWorld(new PrintWriter(sw)); // exportWorld(new PrintWriter(sw) ); String state = sw.toString(); Object[] args = {state}; window.call(callback, args); } }); }
@FXML private void saveCode() { FileChooser fc = new FileChooser(); fc.setTitle("保存先を指定"); fc.setInitialFileName(contest.getSelectionModel().getSelectedItem().getValue()); fc.getExtensionFilters().addAll(Extension.getFilterList()); fc.setSelectedExtensionFilter(Extension.of(languageLabel.getText()).getFilter()); Optional.ofNullable(fc.showSaveDialog(root.getScene().getWindow())) .ifPresent( f -> { try { Files.write(f.toPath(), ((String) obj.call("getCode")).getBytes()); } catch (IOException e) { } }); }
public void init() { win = JSObject.getWindow(this); toCopy = this.getParameter("tocopy"); try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { JButton copyButton = new JButton("Copy to Clipboard"); copyButton.addActionListener(new CopyToClipboard()); add(copyButton); } }); } catch (Exception e) { System.err.println("Error initializing ClipboardApplet."); } }