summaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/terminal/gwt/client/SuperDevMode.java
blob: 98e73c0c08f69acf8adf19a9bc32a047cc2e77f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/* 
@VaadinApache2LicenseForJavaFiles@
 */
package com.vaadin.terminal.gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.vaadin.terminal.gwt.client.ui.notification.VNotification;
import com.vaadin.terminal.gwt.client.ui.notification.VNotification.EventListener;
import com.vaadin.terminal.gwt.client.ui.notification.VNotification.HideEvent;

/**
 * Class that enables SuperDevMode using a ?superdevmode parameter in the url.
 * 
 * @author Vaadin Ltd
 * @version @VERSION@
 * @since 7.0
 * 
 */
public class SuperDevMode {

    private static final int COMPILE_TIMEOUT_IN_SECONDS = 60;
    protected static final String SKIP_RECOMPILE = "VaadinSuperDevMode_skip_recompile";

    public static class RecompileResult extends JavaScriptObject {
        protected RecompileResult() {

        }

        public final native boolean ok()
        /*-{
         return this.status == "ok";
        }-*/;
    }

    private static void recompileWidgetsetAndStartInDevMode(
            final String serverUrl) {
        VConsole.log("Recompiling widgetset using<br/>" + serverUrl
                + "<br/>and then reloading in super dev mode");
        VNotification n = new VNotification();
        n.show("<b>Recompiling widgetset, this should not take too long</b>",
                VNotification.CENTERED, VNotification.STYLE_SYSTEM);

        JsonpRequestBuilder b = new JsonpRequestBuilder();
        b.setCallbackParam("_callback");
        b.setTimeout(COMPILE_TIMEOUT_IN_SECONDS * 1000);
        b.requestObject(serverUrl + "recompile/" + GWT.getModuleName() + "?"
                + getRecompileParameters(GWT.getModuleName()),
                new AsyncCallback<RecompileResult>() {

                    public void onSuccess(RecompileResult result) {
                        VConsole.log("JSONP compile call successful");

                        if (!result.ok()) {
                            VConsole.log("* result: " + result);
                            failed();
                            return;
                        }

                        setSession(
                                getSuperDevModeHookKey(),
                                getSuperDevWidgetSetUrl(GWT.getModuleName(),
                                        serverUrl));
                        setSession(SKIP_RECOMPILE, "1");

                        VConsole.log("* result: OK. Reloading");
                        Location.reload();
                    }

                    public void onFailure(Throwable caught) {
                        VConsole.error("JSONP compile call failed");
                        // Don't log exception as they are shown as
                        // notifications
                        VConsole.error(Util.getSimpleName(caught) + ": "
                                + caught.getMessage());
                        failed();

                    }

                    private void failed() {
                        VNotification n = new VNotification();
                        n.addEventListener(new EventListener() {

                            public void notificationHidden(HideEvent event) {
                                recompileWidgetsetAndStartInDevMode(serverUrl);
                            }
                        });
                        n.show("Recompilation failed.<br/>"
                                + "Make sure CodeServer is running, "
                                + "check its output and click to retry",
                                VNotification.CENTERED,
                                VNotification.STYLE_SYSTEM);
                    }
                });

    }

    protected static String getSuperDevWidgetSetUrl(String widgetsetName,
            String serverUrl) {
        return serverUrl + GWT.getModuleName() + "/" + GWT.getModuleName()
                + ".nocache.js";
    }

    private native static String getRecompileParameters(String moduleName)
    /*-{
        var prop_map = $wnd.__gwt_activeModules[moduleName].bindings();
        
        // convert map to URL parameter string
        var props = [];
        for (var key in prop_map) {
           props.push(encodeURIComponent(key) + '=' + encodeURIComponent(prop_map[key]))
        }
        
        return props.join('&') + '&';
    }-*/;

    private static void setSession(String key, String value) {
        Storage.getSessionStorageIfSupported().setItem(key, value);
    }

    private static String getSession(String key) {
        return Storage.getSessionStorageIfSupported().getItem(key);
    }

    private static void removeSession(String key) {
        Storage.getSessionStorageIfSupported().removeItem(key);
    }

    protected static void disableDevModeAndReload() {
        removeSession(getSuperDevModeHookKey());
        redirect(false);
    }

    protected static void redirect(boolean devModeOn) {
        UrlBuilder createUrlBuilder = Location.createUrlBuilder();
        if (!devModeOn) {
            createUrlBuilder.removeParameter("superdevmode");
        } else {
            createUrlBuilder.setParameter("superdevmode", "");
        }

        Location.assign(createUrlBuilder.buildString());

    }

    private static String getSuperDevModeHookKey() {
        String widgetsetName = GWT.getModuleName();
        final String superDevModeKey = "__gwtDevModeHook:" + widgetsetName;
        return superDevModeKey;
    }

    private static boolean hasSession(String key) {
        return getSession(key) != null;
    }

    /**
     * The URL of the code server. The default URL (http://localhost:9876/) will
     * be used if this is empty or null.
     * 
     * @param serverUrl
     *            The url of the code server or null to use the default
     * @return true if recompile started, false if we are running in
     *         SuperDevMode
     */
    protected static boolean recompileIfNeeded(String serverUrl) {
        if (serverUrl == null || "".equals(serverUrl)) {
            serverUrl = "http://localhost:9876/";
        } else {
            serverUrl = "http://" + serverUrl + "/";
        }

        if (hasSession(SKIP_RECOMPILE)) {
            VConsole.log("Running in SuperDevMode");
            // When we get here, we are running in super dev mode

            // Remove the flag so next reload will recompile
            removeSession(SKIP_RECOMPILE);

            // Remove the gwt flag so we will not end up in dev mode if we
            // remove the url parameter manually
            removeSession(getSuperDevModeHookKey());

            return false;
        }

        recompileWidgetsetAndStartInDevMode(serverUrl);
        return true;
    }

    protected static boolean isSuperDevModeEnabledInModule() {
        String moduleName = GWT.getModuleName();
        return isSuperDevModeEnabledInModule(moduleName);
    }

    protected native static boolean isSuperDevModeEnabledInModule(
            String moduleName)
    /*-{
        if (!$wnd.__gwt_activeModules)
           return false;
        var mod = $wnd.__gwt_activeModules[moduleName];
        if (!mod)
            return false;

        if (mod.superdevmode) {
           // Running in super dev mode already, it is supported
           return true;
        }

        return mod.canRedirect;
    }-*/;

    /**
     * Enables SuperDevMode if the url contains the "superdevmode" parameter.
     * <p>
     * The caller should not continue initialization of the application if this
     * method returns true. The application will be restarted once compilation
     * is done and then this method will return false.
     * </p>
     * 
     * @return true if a recompile operation has started and the page will be
     *         reloaded once it is done, false if no recompilation will be done.
     */
    public static boolean enableBasedOnParameter() {
        String superDevModeParameter = Location.getParameter("superdevmode");
        if (superDevModeParameter != null) {
            // Need to check the recompile flag also because if we are running
            // in super dev mode, as a result of the recompile, the enabled
            // check will fail...
            if (!isSuperDevModeEnabledInModule()) {
                showError("SuperDevMode is not enabled for this module/widgetset.<br/>"
                        + "Ensure that your module definition (.gwt.xml) contains <br/>"
                        + "&lt;add-linker name=&quot;xsiframe&quot;/&gt;<br/>"
                        + "&lt;set-configuration-property name=&quot;devModeRedirectEnabled&quot; value=&quot;true&quot; /&gt;<br/>");
                return false;
            }
            return SuperDevMode.recompileIfNeeded(superDevModeParameter);
        }
        return false;
    }

    private static void showError(String message) {
        VNotification n = new VNotification();
        n.show(message, VNotification.CENTERED_TOP, VNotification.STYLE_SYSTEM);
    }
}