Changeset 38926


Ignore:
Timestamp:
2024-04-16T15:22:42+12:00 (7 weeks ago)
Author:
anupama
Message:
  1. I couldn't get JavaScript to Java communication working in webswing, in order to stop the application and do cleanup when the user navigates away from the collage webswing applet/application page. But instead, I found I could call the kill() method on the webswing instance which will call application exit, which I had set up to handle the cleanup code. So the mystery of why JS to Java doesn't work remains, but the problem of shutting down the app neatly on navigating away is resolved. 2. Java webswing methods only to be called when run in webswing mode.
Location:
main/trunk/greenstone3
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • main/trunk/greenstone3/src/java/org/greenstone/applet/GsdlCollageApplet/GsdlCollageApplet.java

    r38925 r38926  
    44import org.webswing.toolkit.api.action.WebActionEvent;
    55import org.webswing.toolkit.api.action.WebActionListener;
     6
     7import org.webswing.toolkit.api.url.*;
    68
    79//import java.applet.Applet;
     
    3941    private int Y_DIM = 300;
    4042
     43    boolean isWebswing = false; // if run as webswing
    4144    // To run this GsdlCollageApplet as Application instead of as Applet
    42     boolean isWebswingApplication = false; // if run as webswing *and* application (not applet)
    4345    boolean isRunAsApplet = true;
    4446    // set only if JPhind object is run as an application
     
    163165    //}
    164166
    165     // Handle getting called by webswing JavaScript:
    166     // when the user navigates away from the webswing app's web page, do cleanup
    167     // https://www.webswing.org/docs/23.2/integrate/jslink.html#invoking-java-from-javascript
    168     // https://vaadin.com/directory/component/webswing-vaadin1
    169     org.webswing.toolkit.api.WebswingUtil.getWebswingApi().addBrowserActionListener(new org.webswing.toolkit.api.action.WebActionListener() {
    170         @Override
    171         public void actionPerformed(org.webswing.toolkit.api.action.WebActionEvent actionEvent) {
    172             switch (actionEvent.getActionName()) {
    173             case "navigatingAway":
    174             // do cleanup
    175             System.err.println("@@@@ In Java collage addBrowserActionListener on navigatingAway - called");
    176             GsdlCollageApplet.this.stopRunning();
    177             break;
    178             case "testJavaCall":
    179             org.webswing.toolkit.api.WebswingUtil.getWebswingApi().sendActionEvent("javaToWebswingJSConsoleLog", "GsdlCollageApplet got TEST call !!", null);
    180             //WebswingUtil.getWebswingApi().sendActionEvent("@@@ javaToWebswingJSConsoleLog", "GsdlCollageApplet - testjavaCall handler got your message", null);
    181             }
    182         }
    183         });
    184    
    185167    this.addMouseListener(new CollageMouseAdapter());
    186168    }
     
    233215    }
    234216   
    235     isWebswingApplication = appParams.getOrDefault("webswing", "0").equals("1") ? true : false;
     217    isWebswing = appParams.getOrDefault("webswing", "0").equals("1") ? true : false;
     218
     219    // Handle getting called by webswing JavaScript (but only if run in webswing mode):
     220    // when the user navigates away from the webswing app's web page, do cleanup
     221    // https://www.webswing.org/docs/23.2/integrate/jslink.html#invoking-java-from-javascript
     222    // https://vaadin.com/directory/component/webswing-vaadin1
     223    if(isWebswing) {
     224
     225        System.err.println("#### isWebswing, about to add listeners");
     226       
     227        WebswingUtil.getWebswingApi().addBrowserActionListener(new WebActionListener() {
     228            //@Override
     229            public void actionPerformed(WebActionEvent actionEvent) {
     230
     231            System.err.println("******** JavaScript to Java: actionPerformed called.");
     232            //System.err.println("actionEvent = ");
     233           
     234            switch (actionEvent.getActionName()) {
     235            case "navigatingAway":
     236                // do cleanup
     237                System.err.println("@@@@ In Java collage addBrowserActionListener - on navigatingAway called");
     238                GsdlCollageApplet.this.stopRunning();
     239                break;
     240            case "testJavaCall":
     241                WebswingUtil.getWebswingApi().sendActionEvent("javaToWebswingJSConsoleLog", "GsdlCollageApplet got TEST call !!", null);
     242                //WebswingUtil.getWebswingApi().sendActionEvent("javaToWebswingJSConsoleLog", "GsdlCollageApplet - testjavaCall handler got your message", null);
     243            }           
     244            }
     245        });
     246    }
     247   
    236248    // Need these parameters set before init(), so that the display works
    237249    int w = this.getWidth();
     
    554566        if(isRunAsApplet) {
    555567            GsdlCollageApplet.this.getAppletContext().showDocument(from_url,"gsdlDoc");
    556         } else if(isWebswingApplication) {
     568        } else if(isWebswing) {
    557569            WebswingUtil.getWebswingApi().sendActionEvent("openURL",
    558570                      from_url.toString() + " - " +"gsdlDoc",
     
    611623    public void stop()
    612624    {
     625    System.err.println("\n\n*** Stopping collage Applet: stopping threads...");
    613626    //download_thread_.stop();
    614627    //display_thread_.stop();
     
    714727    /**
    715728     * After building the GS3 Multimedia collection, try running this Application as:
    716 java -cp ./web/applet/GsdlCollageApplet.jar:./web/WEB-INF/lib/log4j-1.2.8.jar:./web/WEB-INF/classes org.greenstone.applet.GsdlCollageApplet.GsdlCollageApplet --statusbar 0 --baseurl "http://localhost:8383/greenstone3/" --library library --collection smallbea --gsdlversion 3 --hrefMustHave "library/sites/localsite/collect/smallbea" --documentroot greenstone3 --verbosity 3 --imageType ".jpg%.png" --imageMustNotHave "interfaces/" --classifier "CL2.3" --maxDepth 500 --maxDisplay 25 --refreshDelay 1500 --isJava2 auto --bgcolor "#96c29a" --width 645 --height 780
     729java -cp ./web/applet/GsdlCollageApplet.jar:./web/WEB-INF/lib/log4j-1.2.8.jar:./web/WEB-INF/classes:./web/ext/webswing/api/webswing-api.jar org.greenstone.applet.GsdlCollageApplet.GsdlCollageApplet --statusbar 0 --baseurl "http://localhost:8383/greenstone3/" --library library --collection smallbea --gsdlversion 3 --hrefMustHave "library/sites/localsite/collect/smallbea" --documentroot greenstone3 --verbosity 3 --imageType ".jpg%.png" --imageMustNotHave "interfaces/" --classifier "CL2.3" --maxDepth 500 --maxDisplay 25 --refreshDelay 1500 --isJava2 auto --bgcolor "#96c29a" --width 645 --height 780
    717730     */
    718731    public static void main(String[] args) {
     
    759772        frame.addWindowListener(new WindowAdapter() {
    760773        public void windowClosing(WindowEvent e) {
    761             // WHY doesn't javascript console log unless I prefix webswing package name??
    762             //WebswingUtil.getWebswingApi().sendActionEvent("@@@ javaToWebswingJSConsoleLog", "GsdlCollageApplet - quitting now", null);
    763             org.webswing.toolkit.api.WebswingUtil.getWebswingApi().sendActionEvent("javaToWebswingJSConsoleLog", "GsdlCollageApplet about to QUIT !!", null);
    764            
     774            if(collageApp.isWebswing) {         
     775            WebswingUtil.getWebswingApi().sendActionEvent("javaToWebswingJSConsoleLog", "GsdlCollageApplet - quitting now", null);
     776            //org.webswing.toolkit.api.WebswingUtil.getWebswingApi().sendActionEvent("javaToWebswingJSConsoleLog", "GsdlCollageApplet about to QUIT !!", null);
     777            }
    765778            collageApp.showStatus("Stopping threads");
    766             System.err.println("\n\n*** Closing applet: stopping threads...");
     779            System.err.println("\n\n*** Closing collage Application: stopping threads...");
    767780            collageApp.stopRunning();
    768781           
  • main/trunk/greenstone3/src/java/org/greenstone/applet/phind/JPhind.java

    r38873 r38926  
    138138    implements ActionListener {
    139139
    140     boolean isWebswingApplication = false; // if run as webswing *and* application (not applet)
     140    // if run as webswing vs either commandline application or as applet through appletviewer
     141    boolean isWebswing = false;
     142    // if run as applet vs application
     143    boolean isRunAsApplet = true;
    141144   
    142     boolean isRunAsApplet = true;
    143145    // set only if JPhind object is run as an application
    144146    URL docBaseURL = null;
     
    284286    }
    285287
    286     isWebswingApplication = appParams.getOrDefault("webswing", "0").equals("1") ? true : false;
     288    isWebswing = appParams.getOrDefault("webswing", "0").equals("1") ? true : false;
    287289   
    288290    // manually calling (J)Applet method init()
     
    730732            getAppletContext().showDocument(url);
    731733        }
    732         } else if(isWebswingApplication) {
     734        } else if(isWebswing) { // webswing and not applet but application
    733735        if (window.length() > 0) {
    734736            WebswingUtil.getWebswingApi().sendActionEvent("openURL",
  • main/trunk/greenstone3/src/java/org/greenstone/gsdl3/service/GsdlCollageBrowse.java

    r38921 r38926  
    9191    String siteName = this.site_home.substring(this.site_home.lastIndexOf("/sites/")+"/sites/".length());
    9292   
    93     String app_info = "<"+GSXML.APPLET_ELEM+" CODEBASE='applet' CODE='org.greenstone.applet.GsdlCollageApplet.GsdlCollageApplet.class' ARCHIVE='GsdlCollageApplet.jar' WIDTH='600' HEIGHT='300'>"; // w=645,h=780
     93    String app_info = "<"+GSXML.APPLET_ELEM+" CODEBASE='applet' CODE='org.greenstone.applet.GsdlCollageApplet.GsdlCollageApplet.class' ARCHIVE='GsdlCollageApplet.jar, webswing-api.jar' WIDTH='600' HEIGHT='300'>"; // w=645,h=780
    9494    app_info +="<param name='library' value='" + this.library_name + "'/>";
    9595    app_info +="<param name='collection'   value='" + this.cluster_name + "'/>";
  • main/trunk/greenstone3/web/interfaces/default/transform/pages/webswing-collage.xsl

    r38925 r38926  
    191191       
    192192       //console.log("args: " +  webswingInstance0.options.args);
    193    
     193
     194       // Allow sending user events to swing application
     195       // https://www.webswing.org/docs/20.2/integrate/embed.html
     196       //webswingInstance0.setControl(true);
     197       
    194198    function getParam(name) {
    195199        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
     
    203207    <xsl:text disable-output-escaping="yes">
    204208
    205       var doButtonClick = function() {
    206       console.log("button clicked");
    207           webswingInstance0.performAction({actionName: "testJavaCall"});
    208       }
    209209      var unloaded = false;
     210     
    210211    (function (window, document) {
    211212        var loader = function () {
     
    239240       // event handlers got triggered. We use the unloaded var to ensure we cleanup only once
    240241       if(!unloaded) {
     242          if(typeof webswingInstance0.kill === 'function') { // it should exist
     243         
     244             console.log("@@@ Asking webswing to stop the collage application");
     245         webswingInstance0.kill();
     246         unloaded = true; // do not unload again, if multiple listeners call navigatingAway() callback function
     247         console.log("@@@@ unloaded");
     248          } // else cannot call method that does not exist
     249       } else {
     250          console.log("@@@@ already unloaded.");
     251       }
     252       /*   
    241253       if(typeof webswingInstance0.performAction === 'function') {
    242               //event.preventDefault(); // if listening for beforeunload event
    243               console.log("@@@@ Calling Java to stop running the webswing collage app");
    244               webswingInstance0.performAction({actionName: "navigatingAway"});
    245               unloaded = true;
     254       
     255              //console.log("@@@@ Calling Java to stop running the webswing collage app");
     256              //webswingInstance0.performAction({actionName: "navigatingAway"});
     257         
     258              // May need web sockets to tell the Java Application to terminate?
     259              // https://vivekvijayan10.medium.com/how-to-communicate-between-or-send-data-from-javascript-to-java-through-sockets-a9bf22840b91
     260
     261              unloaded = true; // do not unload again, if multiple listeners call navigatingAway() callback function
    246262          console.log("@@@@ unloaded");
    247           //alert("check log");
     263
    248264        } else {
    249265            console.log("performAction method DOESN'T exist on the webswing object!");
     
    252268            console.log("@@@@ already unloaded.");
    253269        }
    254 
     270        */
    255271    };
    256    
    257         window.addEventListener ? window.addEventListener("load", loader, false) : window.attachEvent("onload", loader);
    258 
     272    window.addEventListener ? window.addEventListener("load", loader, false) : window.attachEvent("onload", loader);
     273
     274
     275    // When the user navigates away from this page or reloads it, we want to
     276    // shutdown the webswing Java application. 
     277   
    259278    // https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
    260     // unload has been deprecated, and so we try pagehide and visibilitychange events
    261     window.addEventListener ? window.addEventListener("unload", navigatingAway, false) : window.attachEvent("onunload", navigatingAway);
     279    // unload is discouraged as it is not always supported (some mobile devices),
     280    // so we listen for pagehide events too. Visibilitychange events happen on minimising win
     281    // or another tab getting focus. We do not want to stop the app on mere visibilitychange:
     282    // https://dev.to/amersikira/top-3-ways-to-easily-detect-when-a-user-leaves-a-page-using-javascript-2ce4
     283   
     284    // Pagehide is also fired when user presses back button: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
     285    // https://stackoverflow.com/questions/15925251/trigger-an-event-when-user-navigates-away
     286   
     287    // Order of registering may matter and be useful:
     288    // https://stackoverflow.com/questions/31852179/javascript-event-listeners-firing-order
     289    // https://stackoverflow.com/questions/2706109/are-javascript-dom-event-handlers-called-in-order-of-registration
     290    // https://medium.com/@olofbaage/javascript-essentials-all-you-need-to-know-about-event-listeners-8ed889bffb8d
     291    // Event support detection
     292    // https://stackoverflow.com/questions/158673/onbeforeunload-support-detection
     293    // https://stackoverflow.com/questions/2877393/detecting-support-for-a-given-javascript-event
     294    // http://perfectionkills.com/detecting-event-support-without-browser-sniffing
     295
     296    // Does onUnload not leave enough time to get webswing to shutdown? OnBeforeUnload works
     297    // https://caniuse.com/?search=beforeunload
     298    window.addEventListener ? window.addEventListener("beforeunload", navigatingAway, false) : window.attachEvent("onbeforeunload", navigatingAway);
    262299    window.addEventListener ? window.addEventListener("pagehide", navigatingAway, false) : window.attachEvent("onpagehide", navigatingAway);
    263     window.addEventListener ? window.addEventListener("visibilitychange", navigatingAway, false) : window.attachEvent("onvisibilitychange", navigatingAway);   
     300    //window.addEventListener ? window.addEventListener("visibilitychange", navigatingAway, false) : window.attachEvent("onvisibilitychange", navigatingAway); 
    264301   
    265302    })(window, document);
    266303    </xsl:text>
    267304  </script>
    268  
    269  <button type="button" onclick="doButtonClick()">Click Me!</button>
     305
    270306    </xsl:template>
    271307
Note: See TracChangeset for help on using the changeset viewer.