Search in sources :

Example 66 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class SEBrowserComponent method init.

private static void init(SEBrowserComponent self, BrowserComponent p) {
    final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<SEBrowserComponent>(self);
    final WeakReference<BrowserComponent> weakP = new WeakReference<BrowserComponent>(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;
            }
            /*
                // DISABLING TRANSPARENCY BECAUSE IT CAUSES A MESS WHEN SCROLLING
                // ORIGINALLY TRIED TO ADD THIS FOR CSS GENERATION, BUT LATER OPTED
                // TO ONLY USE CEF FOR THAT ANYWAYS
                // SINCE THIS FX COMPONENT IS DEPRECATED, WE'LL JUST LET IT DIE
                self.transparent = p.getStyle().getBgTransparency() == 0;
                if (self.transparent) {
                    try {
                        Class WebPage = Class.forName("com.sun.webkit.WebPage", true, SEBrowserComponent.class.getClassLoader());
                        Class Accessor = Class.forName("com.sun.javafx.webkit.Accessor", true, SEBrowserComponent.class.getClassLoader());
                        Method getPageFor = Accessor.getMethod("getPageFor", new Class[]{WebEngine.class});
                        Object webPage = getPageFor.invoke(null, self.web.getEngine());
                        Method setBackgroundColor = WebPage.getMethod("setBackgroundColor", new Class[]{int.class});
                        setBackgroundColor.invoke(webPage, 0);
                    } catch (Exception ex){}
                }
                */
            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();
                }
            });
        }
    };
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) ObservableValue(javafx.beans.value.ObservableValue) BorderLayout(java.awt.BorderLayout) WeakReference(java.lang.ref.WeakReference) WebEvent(javafx.scene.web.WebEvent) AdjustmentEvent(java.awt.event.AdjustmentEvent) IBrowserComponent(com.codename1.impl.javase.IBrowserComponent) State(javafx.concurrent.Worker.State) AdjustmentListener(java.awt.event.AdjustmentListener)

Example 67 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class ProjectTemplate method processFiles.

public void processFiles() throws IOException {
    process(projectRoot);
    File cn1SettingsFile = new File(projectRoot, "codenameone_settings.properties");
    if (!cn1SettingsFile.exists()) {
        cn1SettingsFile = new File(projectRoot, path("common", "codenameone_settings.properties"));
    }
    if (cn1SettingsFile.exists()) {
        SortedProperties props = new SortedProperties();
        try (FileInputStream fis = new FileInputStream(cn1SettingsFile)) {
            props.load(fis);
        }
        props.setProperty("codename1.packageName", properties.getProperty("packageName"));
        props.setProperty("codename1.mainName", properties.getProperty("mainName"));
        try (FileOutputStream fos = new FileOutputStream(cn1SettingsFile)) {
            props.store(fos, "Updated mainName and packageName");
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) SortedProperties(com.codename1.ant.SortedProperties) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 68 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class TestUtils method screenshotTest.

/**
 * The screenshot test takes a screenshot of the screen and compares it to
 * a prior screenshot, if both are 100% identical the test passes. If not
 * the test fails.<br>
 * If this is the first time the test is run then the screenshot is taken
 * and saved under the given name in the devices storage. The test passes
 * for this case but a warning is printed to the console. The name will have
 * .png appended to it so it will be identified.<br>
 * This test will only work on devices that support the ImageIO API with PNG
 * file format.
 *
 * @param screenshotName the name to use for the storage, must be unique!
 * @return true if the screenshots are identical or no prior screenshot exists
 * or if the test can't be run on this device. False if a screenshot exists and
 * it isn't 100% identical.
 */
public static boolean screenshotTest(String screenshotName) {
    if (verbose) {
        log("screenshotTest(" + screenshotName + ")");
    }
    try {
        ImageIO io = ImageIO.getImageIO();
        if (io == null || !io.isFormatSupported(ImageIO.FORMAT_PNG)) {
            log("screenshot test skipped due to no image IO support for PNG format");
            return true;
        }
        Image mute = Image.createImage(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayHeight());
        Display.getInstance().getCurrent().paintComponent(mute.getGraphics(), true);
        screenshotName = screenshotName + ".png";
        if (Storage.getInstance().exists(screenshotName)) {
            int[] rgba = mute.getRGBCached();
            Image orig = Image.createImage(Storage.getInstance().createInputStream(screenshotName));
            int[] origRgba = orig.getRGBCached();
            orig = null;
            for (int iter = 0; iter < rgba.length; iter++) {
                if (rgba[iter] != origRgba[iter]) {
                    log("screenshots do not match at offset " + iter + " saving additional image under " + screenshotName + ".fail");
                    io.save(mute, Storage.getInstance().createOutputStream(screenshotName + ".fail"), ImageIO.FORMAT_PNG, 1);
                    return false;
                }
            }
        } else {
            io.save(mute, Storage.getInstance().createOutputStream(screenshotName), ImageIO.FORMAT_PNG, 1);
        }
        return true;
    } catch (IOException err) {
        log(err);
        return false;
    }
}
Also used : IOException(java.io.IOException) Image(com.codename1.ui.Image) ImageIO(com.codename1.ui.util.ImageIO)

Example 69 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class PropertyIndex method loadJSON.

/**
 * Loads JSON for the object from the given input stream
 * @param stream the input stream containing the JSON file
 */
public void loadJSON(InputStream stream) throws IOException {
    JSONParser jp = new JSONParser();
    JSONParser.setUseBoolean(true);
    JSONParser.setUseLongs(true);
    populateFromMap(jp.parseJSON(new InputStreamReader(stream, "UTF-8")), parent.getClass());
}
Also used : InputStreamReader(java.io.InputStreamReader) JSONParser(com.codename1.io.JSONParser)

Example 70 with File

use of com.codename1.io.File in project CodenameOne by codenameone.

the class AndroidImplementation method openOutputStream.

/**
 * @inheritDoc
 */
public OutputStream openOutputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        String con = (String) connection;
        if (con.startsWith("file://")) {
            con = con.substring(7);
        }
        OutputStream fc = createFileOuputStream((String) con);
        BufferedOutputStream o = new BufferedOutputStream(fc, (String) con);
        return o;
    }
    return new BufferedOutputStream(((URLConnection) connection).getOutputStream(), connection.toString());
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream)

Aggregations

IOException (java.io.IOException)76 File (java.io.File)61 FileInputStream (java.io.FileInputStream)43 InputStream (java.io.InputStream)33 EncodedImage (com.codename1.ui.EncodedImage)23 FileOutputStream (java.io.FileOutputStream)23 OutputStream (java.io.OutputStream)22 SortedProperties (com.codename1.ant.SortedProperties)18 FileSystemStorage (com.codename1.io.FileSystemStorage)17 BufferedInputStream (com.codename1.io.BufferedInputStream)15 Image (com.codename1.ui.Image)15 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ActionEvent (com.codename1.ui.events.ActionEvent)14 RandomAccessFile (java.io.RandomAccessFile)14 ArrayList (java.util.ArrayList)14 EditableResources (com.codename1.ui.util.EditableResources)13 InvocationTargetException (java.lang.reflect.InvocationTargetException)13 Properties (java.util.Properties)12 File (com.codename1.io.File)11 BufferedImage (java.awt.image.BufferedImage)11