use of com.codename1.ui.BrowserComponent in project CodenameOne by codenameone.
the class SEBrowserComponent method init.
private static void init(SEBrowserComponent self, BrowserComponent p) {
final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<>(self);
final WeakReference<BrowserComponent> weakP = new WeakReference<>(p);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SEBrowserComponent self = weakSelf.get();
if (self == null) {
return;
}
self.cnt = new InternalJPanel(self.instance, self);
// <--- Important if container is opaque it will cause
self.cnt.setOpaque(false);
// all kinds of flicker due to painting conflicts with CN1 pipeline.
self.cnt.setLayout(new BorderLayout());
self.cnt.add(BorderLayout.CENTER, self.panel);
// cnt.setVisible(false);
}
});
self.web.getEngine().getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> ov, String t, String t1) {
SEBrowserComponent self = weakSelf.get();
BrowserComponent p = weakP.get();
if (self == null || p == null) {
return;
}
if (t1.startsWith("Loading http:") || t1.startsWith("Loading file:") || t1.startsWith("Loading https:")) {
String url = t1.substring("Loading ".length());
if (!url.equals(self.currentURL)) {
p.fireWebEvent("onStart", new ActionEvent(url));
}
self.currentURL = url;
} else if ("Loading complete".equals(t1)) {
}
}
});
self.web.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {
@Override
public void handle(WebEvent<String> t) {
BrowserComponent p = weakP.get();
if (p == null) {
return;
}
String msg = t.getData();
if (msg.startsWith("!cn1_message:")) {
System.out.println("Receiving message " + msg);
p.fireWebEvent("onMessage", new ActionEvent(msg.substring("!cn1_message:".length())));
}
}
});
self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
@Override
public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
System.out.println("Received exception: " + t1.getMessage());
if (ov.getValue() != null) {
ov.getValue().printStackTrace();
}
if (t != ov.getValue() && t != null) {
t.printStackTrace();
}
if (t1 != ov.getValue() && t1 != t && t1 != null) {
t.printStackTrace();
}
}
});
self.web.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
@Override
public void changed(ObservableValue ov, State oldState, State newState) {
SEBrowserComponent self = weakSelf.get();
BrowserComponent p = weakP.get();
try {
netscape.javascript.JSObject w = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
if (w == null) {
System.err.println("Could not get window");
} else {
Bridge b = new Bridge(p);
self.putClientProperty("SEBrowserComponent.Bridge.jconsole", b);
w.setMember("jconsole", b);
}
} catch (Throwable t) {
Log.e(t);
}
if (self == null || p == null) {
return;
}
String url = self.web.getEngine().getLocation();
if (newState == State.SCHEDULED) {
p.fireWebEvent("onStart", new ActionEvent(url));
} else if (newState == State.RUNNING) {
p.fireWebEvent("onLoadResource", new ActionEvent(url));
} else if (newState == State.SUCCEEDED) {
if (!p.isNativeScrollingEnabled()) {
self.web.getEngine().executeScript("document.body.style.overflow='hidden'");
}
// let's just add a client property to the BrowserComponent to enable firebug
if (Boolean.TRUE.equals(p.getClientProperty("BrowserComponent.firebug"))) {
self.web.getEngine().executeScript("if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document['createElement' + 'NS'](E, 'script') : document['createElement']('script');E['setAttribute']('id', 'FirebugLite');E['setAttribute']('src', 'https://getfirebug.com/' + 'firebug-lite.js' + '#startOpened');E['setAttribute']('FirebugLite', '4');(document['getElementsByTagName']('head')[0] || document['getElementsByTagName']('body')[0]).appendChild(E);E = new Image;E['setAttribute']('src', 'https://getfirebug.com/' + '#startOpened');}");
}
netscape.javascript.JSObject window = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
Bridge b = new Bridge(p);
self.putClientProperty("SEBrowserComponent.Bridge.cn1application", b);
window.setMember("cn1application", b);
self.web.getEngine().executeScript("while (window._cn1ready && window._cn1ready.length > 0) {var f = window._cn1ready.shift(); f();}");
// System.out.println("cn1application is "+self.web.getEngine().executeScript("window.cn1application && window.cn1application.shouldNavigate"));
self.web.getEngine().executeScript("window.addEventListener('unload', function(e){console.log('unloading...');return 'foobar';});");
p.fireWebEvent("onLoad", new ActionEvent(url));
}
self.currentURL = url;
self.repaint();
}
});
self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
@Override
public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
BrowserComponent p = weakP.get();
if (p == null) {
return;
}
t1.printStackTrace();
if (t1 == null) {
if (t == null) {
p.fireWebEvent("onError", new ActionEvent("Unknown error", -1));
} else {
p.fireWebEvent("onError", new ActionEvent(t.getMessage(), -1));
}
} else {
p.fireWebEvent("onError", new ActionEvent(t1.getMessage(), -1));
}
}
});
// Monitor the location property so that we can send the shouldLoadURL event.
// This allows us to cancel the loading of a URL if we want to handle it ourself.
self.web.getEngine().locationProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> prop, String before, String after) {
SEBrowserComponent self = weakSelf.get();
BrowserComponent p = weakP.get();
if (self == null || p == null) {
return;
}
if (!p.fireBrowserNavigationCallbacks(self.web.getEngine().getLocation())) {
self.web.getEngine().getLoadWorker().cancel();
}
}
});
self.adjustmentListener = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
Display.getInstance().callSerially(new Runnable() {
public void run() {
SEBrowserComponent self = weakSelf.get();
if (self == null) {
return;
}
self.onPositionSizeChange();
}
});
}
};
}
use of com.codename1.ui.BrowserComponent in project CodenameOne by codenameone.
the class AddThemeEntry method updateThemePreview.
// GEN-LAST:event_trueTypeFontSizeValueStateChanged
private void updateThemePreview() {
if (disableRefresh) {
return;
}
updateThemeHashtable(themeHash);
refreshTheme(themeHash);
String name = codenameOnePreview.getComponentAt(0).getClass().getName();
String selectedName = (String) componentName.getSelectedItem();
if (!name.endsWith(selectedName)) {
try {
com.codename1.ui.Component c;
if (selectedName.equals("BrowserComponent")) {
// special case
c = new com.codename1.ui.Label("Preview", "BrowserComponent");
} else {
Class cls = Class.forName("com.codename1.ui." + selectedName);
c = (com.codename1.ui.Component) cls.newInstance();
if (c instanceof com.codename1.ui.Label) {
((com.codename1.ui.Label) c).setText("Preview");
} else {
if (c instanceof com.codename1.ui.List) {
((com.codename1.ui.List) c).setModel(new com.codename1.ui.list.DefaultListModel(new Object[] { "Preview 1", "Preview 2", "Preview 3" }));
}
}
}
codenameOnePreview.removeAll();
codenameOnePreview.addComponent(com.codename1.ui.layouts.BorderLayout.CENTER, c);
} catch (Throwable t) {
codenameOnePreview.removeAll();
com.codename1.ui.Label l = new com.codename1.ui.Label("Preview");
l.setUIID(selectedName);
codenameOnePreview.addComponent(com.codename1.ui.layouts.BorderLayout.CENTER, l);
}
}
com.codename1.ui.plaf.Style s;
if (prefix != null && prefix.length() > 0) {
s = com.codename1.ui.plaf.UIManager.getInstance().getComponentCustomStyle(selectedName, prefix.substring(0, prefix.length() - 1));
} else {
s = com.codename1.ui.plaf.UIManager.getInstance().getComponentStyle(selectedName);
}
codenameOnePreview.getComponentAt(0).setUnselectedStyle(s);
codenameOnePreview.revalidate();
previewPane.repaint();
}
use of com.codename1.ui.BrowserComponent in project CodenameOne by codenameone.
the class BlackBerryOS5Implementation method createBrowserComponent.
public PeerComponent createBrowserComponent(Object browserComponent) {
synchronized (UiApplication.getEventLock()) {
BrowserField bff = new BrowserField();
final BrowserComponent cmp = (BrowserComponent) browserComponent;
bff.addListener(new BrowserFieldListener() {
public void documentError(BrowserField browserField, Document document) throws Exception {
cmp.fireWebEvent("onError", new ActionEvent(document.getDocumentURI()));
super.documentError(browserField, document);
}
public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) throws Exception {
cmp.fireWebEvent("onStart", new ActionEvent(document.getDocumentURI()));
super.documentCreated(browserField, scriptEngine, document);
}
public void documentLoaded(BrowserField browserField, Document document) throws Exception {
cmp.fireWebEvent("onLoad", new ActionEvent(document.getDocumentURI()));
super.documentLoaded(browserField, document);
}
});
return PeerComponent.create(bff);
}
}
use of com.codename1.ui.BrowserComponent in project CodenameOne by codenameone.
the class JavascriptTests method runTest.
@Override
public boolean runTest() throws Exception {
Form f = new Form("Test Browser");
f.setLayout(new BorderLayout());
BrowserComponent bc = new BrowserComponent();
bc.setPage("<!doctype html><html><head><title>Foo</title><body>Body</body></head></html>", "http://www.codenameone.com");
final Res res = new Res();
bc.addWebEventListener(BrowserComponent.onLoad, e -> {
try {
int timeout = 5000;
bc.execute("window.person={name:'Steve', somefunc: function(a){this.someval = a}}");
JSRef tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.name)");
TestUtils.assertEqual(JSType.STRING, tmp.getJSType(), "Wrong JSType for person.name");
TestUtils.assertEqual("Steve", tmp.toString());
bc.execute("person.age=${0}", new Object[] { 24 });
tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.age)");
TestUtils.assertEqual(JSType.NUMBER, tmp.getJSType(), "Wrong JSType for age");
TestUtils.assertEqual(24, tmp.getInt(), "Age should be 24");
bc.execute("person.enabled=${0}", new Object[] { true });
tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.enabled)");
TestUtils.assertEqual(JSType.BOOLEAN, tmp.getJSType(), "Wrong JSType for enabled");
TestUtils.assertEqual(true, tmp.getBoolean(), "Wrong value for enabled");
tmp = bc.executeAndWait(timeout, "callback.onSuccess(person)");
TestUtils.assertEqual(JSType.OBJECT, tmp.getJSType(), "Wrong type for person");
tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.somefunc)");
TestUtils.assertEqual(JSType.FUNCTION, tmp.getJSType(), "Wrong type for somefunc");
tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.firstName)");
TestUtils.assertEqual(JSType.UNDEFINED, tmp.getJSType(), "firstName should be undefined");
bc.execute("window.person2={name:'Marlene'}");
tmp = bc.executeAndWait(timeout, "callback.onSuccess(48)");
bc.execute("window.person2.age=${0}", new Object[] { tmp });
tmp = bc.executeAndWait(timeout, "callback.onSuccess(window.person2.age)");
TestUtils.assertEqual(JSType.NUMBER, tmp.getJSType(), "Wrong type for age after setting with JSRef");
TestUtils.assertEqual(48, tmp.getInt(), "Wrong value for age after setting with JSRef");
tmp = bc.executeAndWait(timeout, "callback.onSuccess(${0} + ${1} + ${2} + ${3})", new Object[] { 1, 2, 3, 4 });
TestUtils.assertEqual(JSType.NUMBER, tmp.getJSType(), "Wrong type for 1+2+3+4");
TestUtils.assertEqual(10, tmp.getInt(), "Wrong value for 1+2+3+4");
JSRef name1 = bc.executeAndWait(timeout, "callback.onSuccess(person.name)");
JSRef name2 = bc.executeAndWait(timeout, "callback.onSuccess(person2.name)");
JSRef name1name2 = bc.executeAndWait(timeout, "callback.onSuccess(${0} +' '+${1})", new Object[] { name1, name2 });
TestUtils.assertEqual(JSType.STRING, name1name2.getJSType(), "Wrong type for name1name2");
TestUtils.assertEqual("Steve Marlene", name1name2.toString(), "Wrong value for name1name2");
// Steve
JSProxy proxy = bc.createJSProxy("person.name");
tmp = proxy.callAndWait(timeout, "indexOf", new Object[] { "e" });
TestUtils.assertEqual(2, tmp.getInt(), "Wrong position for 'e'");
tmp = proxy.getAndWait(timeout, "length");
TestUtils.assertEqual(5, tmp.getInt(), "Wrong string length in proxy");
synchronized (res) {
res.complete = true;
res.notifyAll();
}
res.complete = true;
} catch (Throwable t) {
synchronized (res) {
res.complete = true;
res.error = t;
res.notifyAll();
}
}
});
f.add(BorderLayout.CENTER, bc);
f.show();
while (!res.complete) {
Display.getInstance().invokeAndBlock(() -> {
synchronized (res) {
Util.wait(res, 1000);
}
});
}
if (res.error != null) {
Log.e(res.error);
throw new Exception(res.error.getMessage());
}
return true;
}
use of com.codename1.ui.BrowserComponent in project CodenameOne by codenameone.
the class TestComponent method testBrowserComponent2267.
// Test for https://github.com/codenameone/CodenameOne/issues/2267
private void testBrowserComponent2267() {
Form hi = new Form();
String formName = "testBrowserComponent2267";
hi.setName(formName);
hi.setLayout(new BorderLayout());
BrowserComponent browserComponent = new BrowserComponent();
hi.add(BorderLayout.CENTER, browserComponent);
final Throwable[] ex = new Throwable[1];
final boolean[] complete = new boolean[1];
Button loadButton = new Button("setUrl");
String buttonName = "setUrl";
loadButton.setName(buttonName);
loadButton.addActionListener((ev) -> {
ActionListener errorHandler = new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.consume();
ex[0] = (Throwable) e.getSource();
complete[0] = true;
Display.getInstance().removeEdtErrorHandler(this);
}
};
try {
Display.getInstance().addEdtErrorHandler(errorHandler);
browserComponent.addWebEventListener("onLoad", e -> {
Display.getInstance().removeEdtErrorHandler(errorHandler);
complete[0] = true;
});
browserComponent.setURL("https://www.google.es");
} catch (Throwable t) {
ex[0] = t;
complete[0] = true;
Display.getInstance().removeEdtErrorHandler(errorHandler);
} finally {
// complete[0] = true;
}
});
hi.add(BorderLayout.SOUTH, loadButton);
hi.show();
TestUtils.waitForFormName(formName, 2000);
TestUtils.clickButtonByName(buttonName);
while (!complete[0]) {
Display.getInstance().invokeAndBlock(() -> {
Util.sleep(50);
});
}
String message = null;
if (ex[0] != null) {
message = ex[0].getMessage();
}
TestUtils.assertBool(ex[0] == null, "We received an exception setting the browserComponent URL: " + message);
}
Aggregations