summaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/terminal/gwt/client/ApplicationConnection.java
blob: e4bb48c9ba5ade341117d4fb305aa7ef6b844b87 (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
/* 
@ITMillApache2LicenseForJavaFiles@
 */

package com.vaadin.terminal.gwt.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.impl.HTTPRequestImpl;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;
import com.vaadin.terminal.gwt.client.RenderInformation.Size;
import com.vaadin.terminal.gwt.client.ui.Field;
import com.vaadin.terminal.gwt.client.ui.IContextMenu;
import com.vaadin.terminal.gwt.client.ui.INotification;
import com.vaadin.terminal.gwt.client.ui.IView;
import com.vaadin.terminal.gwt.client.ui.INotification.HideEvent;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class ApplicationConnection {
    private static final String MODIFIED_CLASSNAME = "i-modified";

    private static final String REQUIRED_CLASSNAME_EXT = "-required";

    private static final String ERROR_CLASSNAME_EXT = "-error";

    public static final String VAR_RECORD_SEPARATOR = "\u001e";

    public static final String VAR_FIELD_SEPARATOR = "\u001f";

    public static final String VAR_BURST_SEPARATOR = "\u001d";

    public static final String VAR_ARRAYITEM_SEPARATOR = "\u001c";

    public static final String UIDL_SECURITY_HEADER = "com.vaadin.seckey";

    public static final String PARAM_UNLOADBURST = "onunloadburst";

    private static String uidl_security_key = "init";

    private final HashMap<String, String> resourcesMap = new HashMap<String, String>();

    private static Console console;

    private final Vector<String> pendingVariables = new Vector<String>();

    private final ComponentDetailMap idToPaintableDetail = ComponentDetailMap
            .create();

    private final WidgetSet widgetSet;

    private IContextMenu contextMenu = null;

    private Timer loadTimer;
    private Timer loadTimer2;
    private Timer loadTimer3;
    private Element loadElement;

    private final IView view;

    private boolean applicationRunning = false;

    private int activeRequests = 0;

    /** Parameters for this application connection loaded from the web-page */
    private final ApplicationConfiguration configuration;

    /** List of pending variable change bursts that must be submitted in order */
    private final Vector<Vector<String>> pendingVariableBursts = new Vector<Vector<String>>();

    /** Timer for automatic refirect to SessionExpiredURL */
    private Timer redirectTimer;

    /** redirectTimer scheduling interval in seconds */
    private int sessionExpirationInterval;

    private ArrayList<Paintable> relativeSizeChanges = new ArrayList<Paintable>();;
    private ArrayList<Paintable> componentCaptionSizeChanges = new ArrayList<Paintable>();;

    private Date requestStartTime;

    private boolean validatingLayouts = false;

    private Set<Paintable> zeroWidthComponents = null;

    private Set<Paintable> zeroHeightComponents = null;

    public ApplicationConnection(WidgetSet widgetSet,
            ApplicationConfiguration cnf) {
        this.widgetSet = widgetSet;
        configuration = cnf;
        windowName = configuration.getInitialWindowName();
        if (isDebugMode()) {
            console = new IDebugConsole(this, cnf, !isQuietDebugMode());
        } else {
            console = new NullConsole();
        }

        ComponentLocator componentLocator = new ComponentLocator(this);

        String appRootPanelName = cnf.getRootPanelId();
        // remove the end (window name) of autogenarated rootpanel id
        appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");

        initializeTestingToolsHooks(componentLocator, appRootPanelName);

        initializeClientHooks();

        view = new IView(cnf.getRootPanelId());
        showLoadingIndicator();

    }

    /**
     * Starts this application. Don't call this method directly - it's called by
     * {@link ApplicationConfiguration#startNextApplication()}, which should be
     * called once this application has started (first response received) or
     * failed to start. This ensures that the applications are started in order,
     * to avoid session-id problems.
     */
    void start() {
        makeUidlRequest("", true, false, false);
    }

    private native void initializeTestingToolsHooks(
            ComponentLocator componentLocator, String TTAppId)
    /*-{
         var ap = this;
         var client = {};
         client.isActive = function() {
             return ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::hasActiveRequest()();
         }
         var vi = ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::getVersionInfo()();
         if (vi) {
             client.getVersionInfo = function() {
                 return vi;
             }
         }
         
         client.getElementByPath = function(id) {
            return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getElementByPath(Ljava/lang/String;)(id);
         }
         client.getPathForElement = function(element) {
            return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getPathForElement(Lcom/google/gwt/user/client/Element;)(element);
         }

         if(!$wnd.itmill.clients) {
            $wnd.itmill.clients = {};
         }
         
        $wnd.itmill.clients[TTAppId] = client;
    }-*/;

    /**
     * Helper for tt initialization
     */
    @SuppressWarnings("unused")
    private JavaScriptObject getVersionInfo() {
        return configuration.getVersionInfoJSObject();
    }

    /**
     * Publishes a JavaScript API for mash-up applications.
     * <ul>
     * <li><code>itmill.forceSync()</code> sends pending variable changes, in
     * effect synchronizing the server and client state. This is done for all
     * applications on host page.</li>
     * </ul>
     * 
     * TODO make this multi-app aware
     */
    private native void initializeClientHooks()
    /*-{
        var app = this;
        var oldSync;
        if($wnd.itmill.forceSync) {
            oldSync = $wnd.itmill.forceSync;
        }
        $wnd.itmill.forceSync = function() {
            if(oldSync) {
                oldSync();
            }
            app.@com.vaadin.terminal.gwt.client.ApplicationConnection::sendPendingVariableChanges()();
        }
        var oldForceLayout;
        if($wnd.itmill.forceLayout) {
            oldForceLayout = $wnd.itmill.forceLayout;
        }
        $wnd.itmill.forceLayout = function() {
            if(oldForceLayout) {
                oldForceLayout();
            }
            app.@com.vaadin.terminal.gwt.client.ApplicationConnection::forceLayout()();
        }
    }-*/;

    public static Console getConsole() {
        return console;
    }

    /**
     * Checks if client side is in debug mode. Practically this is invoked by
     * adding ?debug parameter to URI.
     * 
     * @return true if client side is currently been debugged
     */
    public native static boolean isDebugMode()
    /*-{
        if($wnd.itmill.debug) {
            var parameters = $wnd.location.search;
            var re = /debug[^\/]*$/;
            return re.test(parameters);
        } else {
            return false;
        }
     }-*/;

    private native static boolean isQuietDebugMode()
    /*-{
     var uri = $wnd.location;
     var re = /debug=q[^\/]*$/;
     return re.test(uri);
     }-*/;

    public String getAppUri() {
        return configuration.getApplicationUri();
    };

    public boolean hasActiveRequest() {
        return (activeRequests > 0);
    }

    private void makeUidlRequest(String requestData, boolean repaintAll,
            boolean forceSync, boolean analyzeLayouts) {
        startRequest();

        // Security: double cookie submission pattern
        requestData = uidl_security_key + VAR_BURST_SEPARATOR + requestData;

        console.log("Making UIDL Request with params: " + requestData);
        String uri = getAppUri() + "UIDL" + configuration.getPathInfo();
        if (repaintAll) {
            uri += "?repaintAll=1";
            if (analyzeLayouts) {
                uri += "&analyzeLayouts=1";
            }
        }
        if (windowName != null && windowName.length() > 0) {
            uri += (repaintAll ? "&" : "?") + "windowName=" + windowName;
        }

        if (!forceSync) {
            final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
                    uri);
            // TODO enable timeout
            // rb.setTimeoutMillis(timeoutMillis);
            rb.setHeader("Content-Type", "text/plain;charset=utf-8");
            try {
                rb.sendRequest(requestData, new RequestCallback() {
                    public void onError(Request request, Throwable exception) {
                        showCommunicationError(exception.getMessage());
                        endRequest();
                        if (!applicationRunning) {
                            // start failed, let's try to start the next app
                            ApplicationConfiguration.startNextApplication();
                        }
                    }

                    public void onResponseReceived(Request request,
                            Response response) {
                        console.log("Server visit took "
                                + String.valueOf((new Date()).getTime()
                                        - requestStartTime.getTime()) + "ms");

                        switch (response.getStatusCode()) {
                        case 0:
                            showCommunicationError("Invalid status code 0 (server down?)");
                            return;
                            // TODO could add more cases
                        }
                        if ("init".equals(uidl_security_key)) {
                            // Read security key
                            String key = response
                                    .getHeader(UIDL_SECURITY_HEADER);
                            if (null != key) {
                                uidl_security_key = key;
                            }
                        }
                        if (applicationRunning) {
                            handleReceivedJSONMessage(response);
                        } else {
                            applicationRunning = true;
                            handleWhenCSSLoaded(response);
                            ApplicationConfiguration.startNextApplication();
                        }
                    }

                    int cssWaits = 0;
                    static final int MAX_CSS_WAITS = 20;

                    private void handleWhenCSSLoaded(final Response response) {
                        int heightOfLoadElement = DOM.getElementPropertyInt(
                                loadElement, "offsetHeight");
                        if (heightOfLoadElement == 0
                                && cssWaits < MAX_CSS_WAITS) {
                            (new Timer() {
                                @Override
                                public void run() {
                                    handleWhenCSSLoaded(response);
                                }
                            }).schedule(50);
                            console
                                    .log("Assuming CSS loading is not complete, "
                                            + "postponing render phase. "
                                            + "(.i-loading-indicator height == 0)");
                            cssWaits++;
                        } else {
                            handleReceivedJSONMessage(response);
                            if (cssWaits >= MAX_CSS_WAITS) {
                                console
                                        .error("CSS files may have not loaded properly.");
                            }
                        }
                    }

                });

            } catch (final RequestException e) {
                ClientExceptionHandler.displayError(e);
                endRequest();
            }
        } else {
            // Synchronized call, discarded response

            syncSendForce(((HTTPRequestImpl) GWT.create(HTTPRequestImpl.class))
                    .createXmlHTTPRequest(), uri + "&" + PARAM_UNLOADBURST
                    + "=1", requestData);
        }
    }

    /**
     * Shows the communication error notification. The 'details' only go to the
     * console for now.
     * 
     * @param details
     *            Optional details for debugging.
     */
    private void showCommunicationError(String details) {
        console.error("Communication error: " + details);
        String html = "";
        if (configuration.getCommunicationErrorCaption() != null) {
            html += "<h1>" + configuration.getCommunicationErrorCaption()
                    + "</h1>";
        }
        if (configuration.getCommunicationErrorMessage() != null) {
            html += "<p>" + configuration.getCommunicationErrorMessage()
                    + "</p>";
        }
        if (html.length() > 0) {
            INotification n = new INotification(1000 * 60 * 45);
            n.addEventListener(new NotificationRedirect(configuration
                    .getCommunicationErrorUrl()));
            n
                    .show(html, INotification.CENTERED_TOP,
                            INotification.STYLE_SYSTEM);
        } else {
            redirect(configuration.getCommunicationErrorUrl());
        }
    }

    private native void syncSendForce(JavaScriptObject xmlHttpRequest,
            String uri, String requestData)
    /*-{
         try {
             xmlHttpRequest.open("POST", uri, false);
             xmlHttpRequest.setRequestHeader("Content-Type", "text/plain;charset=utf-8");
             xmlHttpRequest.send(requestData);
    } catch (e) {
        // No errors are managed as this is synchronous forceful send that can just fail
    }
                    
    }-*/;

    private void startRequest() {
        activeRequests++;
        requestStartTime = new Date();
        // show initial throbber
        if (loadTimer == null) {
            loadTimer = new Timer() {
                @Override
                public void run() {
                    /*
                     * IE7 does not properly cancel the event with
                     * loadTimer.cancel() so we have to check that we really
                     * should make it visible
                     */
                    if (loadTimer != null) {
                        showLoadingIndicator();
                    }

                }
            };
            // First one kicks in at 300ms
        }
        loadTimer.schedule(300);
    }

    private void endRequest() {
        if (applicationRunning) {
            checkForPendingVariableBursts();
        }
        activeRequests--;
        // deferring to avoid flickering
        DeferredCommand.addCommand(new Command() {
            public void execute() {
                if (activeRequests == 0) {
                    hideLoadingIndicator();
                }
            }
        });
    }

    /**
     * This method is called after applying uidl change set to application.
     * 
     * It will clean current and queued variable change sets. And send next
     * change set if it exists.
     */
    private void checkForPendingVariableBursts() {
        cleanVariableBurst(pendingVariables);
        if (pendingVariableBursts.size() > 0) {
            for (Iterator<Vector<String>> iterator = pendingVariableBursts
                    .iterator(); iterator.hasNext();) {
                cleanVariableBurst(iterator.next());
            }
            Vector<String> nextBurst = pendingVariableBursts.firstElement();
            pendingVariableBursts.remove(0);
            buildAndSendVariableBurst(nextBurst, false);
        }
    }

    /**
     * Cleans given queue of variable changes of such changes that came from
     * components that do not exist anymore.
     * 
     * @param variableBurst
     */
    private void cleanVariableBurst(Vector<String> variableBurst) {
        for (int i = 1; i < variableBurst.size(); i += 2) {
            String id = variableBurst.get(i);
            id = id.substring(0, id.indexOf(VAR_FIELD_SEPARATOR));
            if (!idToPaintableDetail.containsKey(id)) {
                // variable owner does not exist anymore
                variableBurst.remove(i - 1);
                variableBurst.remove(i - 1);
                i -= 2;
                ApplicationConnection.getConsole().log(
                        "Removed variable from removed component: " + id);
            }
        }
    }

    private void showLoadingIndicator() {
        // show initial throbber
        if (loadElement == null) {
            loadElement = DOM.createDiv();
            DOM.setStyleAttribute(loadElement, "position", "absolute");
            DOM.appendChild(view.getElement(), loadElement);
            ApplicationConnection.getConsole().log("inserting load indicator");
        }
        DOM.setElementProperty(loadElement, "className", "i-loading-indicator");
        DOM.setStyleAttribute(loadElement, "display", "block");
        // Initialize other timers
        loadTimer2 = new Timer() {
            @Override
            public void run() {
                DOM.setElementProperty(loadElement, "className",
                        "i-loading-indicator-delay");
            }
        };
        // Second one kicks in at 1500ms from request start
        loadTimer2.schedule(1200);

        loadTimer3 = new Timer() {
            @Override
            public void run() {
                DOM.setElementProperty(loadElement, "className",
                        "i-loading-indicator-wait");
            }
        };
        // Third one kicks in at 5000ms from request start
        loadTimer3.schedule(4700);
    }

    private void hideLoadingIndicator() {
        if (loadTimer != null) {
            loadTimer.cancel();
            if (loadTimer2 != null) {
                loadTimer2.cancel();
                loadTimer3.cancel();
            }
            loadTimer = null;
        }
        if (loadElement != null) {
            DOM.setStyleAttribute(loadElement, "display", "none");
        }
    }

    private void handleReceivedJSONMessage(Response response) {
        final Date start = new Date();
        String jsonText = response.getText();
        // for(;;);[realjson]
        jsonText = jsonText.substring(9, jsonText.length() - 1);
        JSONValue json;
        try {
            json = JSONParser.parse(jsonText);
        } catch (final com.google.gwt.json.client.JSONException e) {
            endRequest();
            showCommunicationError(e.getMessage() + " - Original JSON-text:");
            console.log(jsonText);
            return;
        }
        // Handle redirect
        final JSONObject redirect = (JSONObject) ((JSONObject) json)
                .get("redirect");
        if (redirect != null) {
            final JSONString url = (JSONString) redirect.get("url");
            if (url != null) {
                console.log("redirecting to " + url.stringValue());
                redirect(url.stringValue());
                return;
            }
        }

        // Store resources
        final JSONObject resources = (JSONObject) ((JSONObject) json)
                .get("resources");
        for (final Iterator<String> i = resources.keySet().iterator(); i
                .hasNext();) {
            final String key = i.next();
            resourcesMap.put(key, ((JSONString) resources.get(key))
                    .stringValue());
        }

        // Store locale data
        if (((JSONObject) json).containsKey("locales")) {
            final JSONArray l = (JSONArray) ((JSONObject) json).get("locales");
            for (int i = 0; i < l.size(); i++) {
                LocaleService.addLocale((JSONObject) l.get(i));
            }
        }

        JSONObject meta = null;
        if (((JSONObject) json).containsKey("meta")) {
            meta = ((JSONObject) json).get("meta").isObject();
            if (meta.containsKey("repaintAll")) {
                view.clear();
                idToPaintableDetail.clear();
                if (meta.containsKey("invalidLayouts")) {
                    validatingLayouts = true;
                    zeroWidthComponents = new HashSet<Paintable>();
                    zeroHeightComponents = new HashSet<Paintable>();
                }
            }
            if (meta.containsKey("timedRedirect")) {
                final JSONObject timedRedirect = meta.get("timedRedirect")
                        .isObject();
                redirectTimer = new Timer() {
                    @Override
                    public void run() {
                        redirect(timedRedirect.get("url").isString()
                                .stringValue());
                    }
                };
                sessionExpirationInterval = Integer.parseInt(timedRedirect.get(
                        "interval").toString());
            }
        }
        if (redirectTimer != null) {
            redirectTimer.schedule(1000 * sessionExpirationInterval);
        }
        // Process changes
        final JSONArray changes = (JSONArray) ((JSONObject) json)
                .get("changes");

        Vector<Paintable> updatedWidgets = new Vector<Paintable>();
        relativeSizeChanges.clear();
        componentCaptionSizeChanges.clear();

        for (int i = 0; i < changes.size(); i++) {
            try {
                final UIDL change = new UIDL((JSONArray) changes.get(i));
                try {
                    console.dirUIDL(change);
                } catch (final Exception e) {
                    ClientExceptionHandler.displayError(e);
                    // TODO: dir doesn't work in any browser although it should
                    // work (works in hosted mode)
                    // it partially did at some part but now broken.
                }
                final UIDL uidl = change.getChildUIDL(0);
                // TODO optimize
                final Paintable paintable = getPaintable(uidl.getId());
                if (paintable != null) {
                    paintable.updateFromUIDL(uidl, this);
                    // paintable may have changed during render to another
                    // implementation, use the new one for updated widgets map
                    updatedWidgets.add(idToPaintableDetail.get(uidl.getId())
                            .getComponent());
                } else {
                    if (!uidl.getTag().equals("window")) {
                        ClientExceptionHandler
                                .displayError("Received update for "
                                        + uidl.getTag()
                                        + ", but there is no such paintable ("
                                        + uidl.getId() + ") rendered.");
                    } else {
                        view.updateFromUIDL(uidl, this);
                    }
                }
            } catch (final Throwable e) {
                ClientExceptionHandler.displayError(e);
            }
        }

        // Check which widgets' size has been updated
        Set<Paintable> sizeUpdatedWidgets = new HashSet<Paintable>();

        updatedWidgets.addAll(relativeSizeChanges);
        sizeUpdatedWidgets.addAll(componentCaptionSizeChanges);

        for (Paintable paintable : updatedWidgets) {
            ComponentDetail detail = idToPaintableDetail.get(getPid(paintable));
            Widget widget = (Widget) paintable;
            Size oldSize = detail.getOffsetSize();
            Size newSize = new Size(widget.getOffsetWidth(), widget
                    .getOffsetHeight());

            if (oldSize == null || !oldSize.equals(newSize)) {
                sizeUpdatedWidgets.add(paintable);
                detail.setOffsetSize(newSize);
            }

        }

        Util.componentSizeUpdated(sizeUpdatedWidgets);

        if (meta != null) {
            if (meta.containsKey("appError")) {
                JSONObject error = meta.get("appError").isObject();
                JSONValue val = error.get("caption");
                String html = "";
                if (val.isString() != null) {
                    html += "<h1>" + val.isString().stringValue() + "</h1>";
                }
                val = error.get("message");
                if (val.isString() != null) {
                    html += "<p>" + val.isString().stringValue() + "</p>";
                }
                val = error.get("url");
                String url = null;
                if (val.isString() != null) {
                    url = val.isString().stringValue();
                }

                if (html.length() != 0) {
                    /* 45 min */
                    INotification n = new INotification(1000 * 60 * 45);
                    n.addEventListener(new NotificationRedirect(url));
                    n.show(html, INotification.CENTERED_TOP,
                            INotification.STYLE_SYSTEM);
                } else {
                    redirect(url);
                }
                applicationRunning = false;
            }
            if (validatingLayouts) {
                getConsole().printLayoutProblems(
                        meta.get("invalidLayouts").isArray(), this,
                        zeroHeightComponents, zeroWidthComponents);
                zeroHeightComponents = null;
                zeroWidthComponents = null;
                validatingLayouts = false;

            }
        }

        final long prosessingTime = (new Date().getTime()) - start.getTime();
        console.log(" Processing time was " + String.valueOf(prosessingTime)
                + "ms for " + jsonText.length() + " characters of JSON");
        console.log("Referenced paintables: " + idToPaintableDetail.size());

        endRequest();
    }

    /**
     * This method assures that all pending variable changes are sent to server.
     * Method uses synchronized xmlhttprequest and does not return before the
     * changes are sent. No UIDL updates are processed and thut UI is left in
     * inconsistent state. This method should be called only when closing
     * windows - normally sendPendingVariableChanges() should be used.
     */
    public void sendPendingVariableChangesSync() {
        if (applicationRunning) {
            pendingVariableBursts.add(pendingVariables);
            Vector<String> nextBurst = pendingVariableBursts.firstElement();
            pendingVariableBursts.remove(0);
            buildAndSendVariableBurst(nextBurst, true);
        }
    }

    // Redirect browser, null reloads current page
    private static native void redirect(String url)
    /*-{
      if (url) {
         $wnd.location = url;
      } else {
          $wnd.location.reload(false);
      }
     }-*/;

    public void registerPaintable(String id, Paintable paintable) {
        ComponentDetail componentDetail = new ComponentDetail();
        componentDetail.setComponent(paintable);
        idToPaintableDetail.put(id, componentDetail);
        setPid(((Widget) paintable).getElement(), id);
    }

    private native void setPid(Element el, String pid)
    /*-{
        el.tkPid = pid;
    }-*/;

    public String getPid(Paintable paintable) {
        return getPid(((Widget) paintable).getElement());
    }

    public native String getPid(Element el)
    /*-{
        return el.tkPid;
    }-*/;

    public Element getElementByPid(String pid) {
        return ((Widget) getPaintable(pid)).getElement();
    }

    public void unregisterPaintable(Paintable p) {
        if (p == null) {
            ApplicationConnection.getConsole().error(
                    "WARN: Trying to unregister null paintable");
            return;
        }
        String id = getPid(p);
        idToPaintableDetail.remove(id);
        if (p instanceof HasWidgets) {
            unregisterChildPaintables((HasWidgets) p);
        }
    }

    public void unregisterChildPaintables(HasWidgets container) {
        final Iterator<Widget> it = container.iterator();
        while (it.hasNext()) {
            final Widget w = it.next();
            if (w instanceof Paintable) {
                unregisterPaintable((Paintable) w);
            } else if (w instanceof HasWidgets) {
                unregisterChildPaintables((HasWidgets) w);
            }
        }
    }

    /**
     * Returns Paintable element by its id
     * 
     * @param id
     *            Paintable ID
     */
    public Paintable getPaintable(String id) {
        ComponentDetail componentDetail = idToPaintableDetail.get(id);
        if (componentDetail == null) {
            return null;
        } else {
            return componentDetail.getComponent();
        }
    }

    private void addVariableToQueue(String paintableId, String variableName,
            String encodedValue, boolean immediate, char type) {
        final String id = paintableId + VAR_FIELD_SEPARATOR + variableName
                + VAR_FIELD_SEPARATOR + type;
        for (int i = 1; i < pendingVariables.size(); i += 2) {
            if ((pendingVariables.get(i)).equals(id)) {
                pendingVariables.remove(i - 1);
                pendingVariables.remove(i - 1);
                break;
            }
        }
        pendingVariables.add(encodedValue);
        pendingVariables.add(id);
        if (immediate) {
            sendPendingVariableChanges();
        }
    }

    /**
     * This method sends currently queued variable changes to server. It is
     * called when immediate variable update must happen.
     * 
     * To ensure correct order for variable changes (due servers multithreading
     * or network), we always wait for active request to be handler before
     * sending a new one. If there is an active request, we will put varible
     * "burst" to queue that will be purged after current request is handled.
     * 
     */
    @SuppressWarnings("unchecked")
    public void sendPendingVariableChanges() {
        if (applicationRunning) {
            if (hasActiveRequest()) {
                // skip empty queues if there are pending bursts to be sent
                if (pendingVariables.size() > 0
                        || pendingVariableBursts.size() == 0) {
                    Vector<String> burst = (Vector<String>) pendingVariables
                            .clone();
                    pendingVariableBursts.add(burst);
                    pendingVariables.clear();
                }
            } else {
                buildAndSendVariableBurst(pendingVariables, false);
            }
        }
    }

    /**
     * Build the variable burst and send it to server.
     * 
     * When sync is forced, we also force sending of all pending variable-bursts
     * at the same time. This is ok as we can assume that DOM will newer be
     * updated after this.
     * 
     * @param pendingVariables
     *            Vector of variablechanges to send
     * @param forceSync
     *            Should we use synchronous request?
     */
    private void buildAndSendVariableBurst(Vector<String> pendingVariables,
            boolean forceSync) {
        final StringBuffer req = new StringBuffer();

        while (!pendingVariables.isEmpty()) {
            for (int i = 0; i < pendingVariables.size(); i++) {
                if (i > 0) {
                    if (i % 2 == 0) {
                        req.append(VAR_RECORD_SEPARATOR);
                    } else {
                        req.append(VAR_FIELD_SEPARATOR);
                    }
                }
                req.append(pendingVariables.get(i));
            }

            pendingVariables.clear();
            // Append all the busts to this synchronous request
            if (forceSync && !pendingVariableBursts.isEmpty()) {
                pendingVariables = pendingVariableBursts.firstElement();
                pendingVariableBursts.remove(0);
                req.append(VAR_BURST_SEPARATOR);
            }
        }
        makeUidlRequest(req.toString(), false, forceSync, false);
    }

    public void updateVariable(String paintableId, String variableName,
            Paintable newValue, boolean immediate) {
        String pid = (newValue != null) ? getPid(newValue) : null;
        addVariableToQueue(paintableId, variableName, pid, immediate, 'p');
    }

    public void updateVariable(String paintableId, String variableName,
            String newValue, boolean immediate) {
        addVariableToQueue(paintableId, variableName, newValue, immediate, 's');
    }

    public void updateVariable(String paintableId, String variableName,
            int newValue, boolean immediate) {
        addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
                'i');
    }

    public void updateVariable(String paintableId, String variableName,
            long newValue, boolean immediate) {
        addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
                'l');
    }

    public void updateVariable(String paintableId, String variableName,
            float newValue, boolean immediate) {
        addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
                'f');
    }

    public void updateVariable(String paintableId, String variableName,
            double newValue, boolean immediate) {
        addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
                'd');
    }

    public void updateVariable(String paintableId, String variableName,
            boolean newValue, boolean immediate) {
        addVariableToQueue(paintableId, variableName, newValue ? "true"
                : "false", immediate, 'b');
    }

    public void updateVariable(String paintableId, String variableName,
            Object[] values, boolean immediate) {
        final StringBuffer buf = new StringBuffer();
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                buf.append(VAR_ARRAYITEM_SEPARATOR);
            }
            buf.append(values[i].toString());
        }
        addVariableToQueue(paintableId, variableName, buf.toString(),
                immediate, 'a');
    }

    /**
     * Update generic component features.
     * 
     * <h2>Selecting correct implementation</h2>
     * 
     * <p>
     * The implementation of a component depends on many properties, including
     * styles, component features, etc. Sometimes the user changes those
     * properties after the component has been created. Calling this method in
     * the beginning of your updateFromUIDL -method automatically replaces your
     * component with more appropriate if the requested implementation changes.
     * </p>
     * 
     * <h2>Caption, icon, error messages and description</h2>
     * 
     * <p>
     * Component can delegate management of caption, icon, error messages and
     * description to parent layout. This is optional an should be decided by
     * component author
     * </p>
     * 
     * <h2>Component visibility and disabling</h2>
     * 
     * This method will manage component visibility automatically and if
     * component is an instanceof FocusWidget, also handle component disabling
     * when needed.
     * 
     * @param component
     *            Widget to be updated, expected to implement an instance of
     *            Paintable
     * @param uidl
     *            UIDL to be painted
     * @param manageCaption
     *            True if you want to delegate caption, icon, description and
     *            error message management to parent.
     * 
     * @return Returns true iff no further painting is needed by caller
     */
    public boolean updateComponent(Widget component, UIDL uidl,
            boolean manageCaption) {
        String pid = getPid(component.getElement());
        if (pid == null) {
            getConsole().error(
                    "Trying to update an unregistered component: "
                            + Util.getSimpleName(component));
            return true;
        }

        ComponentDetail componentDetail = idToPaintableDetail.get(pid);

        if (componentDetail == null) {
            getConsole().error(
                    "ComponentDetail not found for "
                            + Util.getSimpleName(component) + " with PID "
                            + pid + ". This should not happen.");
            return true;
        }

        // If the server request that a cached instance should be used, do
        // nothing
        if (uidl.getBooleanAttribute("cached")) {
            return true;
        }

        // Visibility
        boolean visible = !uidl.getBooleanAttribute("invisible");
        boolean wasVisible = component.isVisible();
        component.setVisible(visible);
        if (wasVisible != visible) {
            // Changed invisibile <-> visible
            if (wasVisible && manageCaption) {
                // Must hide caption when component is hidden
                final Container parent = Util.getLayout(component);
                if (parent != null) {
                    parent.updateCaption((Paintable) component, uidl);
                }

            }
        }

        if (!visible) {
            // component is invisible, delete old size to notify parent, if
            // later make visible
            componentDetail.setOffsetSize(null);
            return true;
        }

        // Switch to correct implementation if needed
        if (!widgetSet.isCorrectImplementation(component, uidl)) {
            final Container parent = Util.getLayout(component);
            if (parent != null) {
                final Widget w = (Widget) widgetSet.createWidget(uidl);
                parent.replaceChildComponent(component, w);
                unregisterPaintable((Paintable) component);
                registerPaintable(uidl.getId(), (Paintable) w);
                ((Paintable) w).updateFromUIDL(uidl, this);
                return true;
            }
        }

        boolean enabled = !uidl.getBooleanAttribute("disabled");
        if (component instanceof FocusWidget) {
            FocusWidget fw = (FocusWidget) component;
            fw.setEnabled(enabled);
            if (uidl.hasAttribute("tabindex")) {
                fw.setTabIndex(uidl.getIntAttribute("tabindex"));
            }
        }

        StringBuffer styleBuf = new StringBuffer();
        final String primaryName = component.getStylePrimaryName();
        styleBuf.append(primaryName);

        // first disabling and read-only status
        if (!enabled) {
            styleBuf.append(" ");
            styleBuf.append("i-disabled");
        }
        if (uidl.getBooleanAttribute("readonly")) {
            styleBuf.append(" ");
            styleBuf.append("i-readonly");
        }

        // add additional styles as css classes, prefixed with component default
        // stylename
        if (uidl.hasAttribute("style")) {
            final String[] styles = uidl.getStringAttribute("style").split(" ");
            for (int i = 0; i < styles.length; i++) {
                styleBuf.append(" ");
                styleBuf.append(primaryName);
                styleBuf.append("-");
                styleBuf.append(styles[i]);
                styleBuf.append(" ");
                styleBuf.append(styles[i]);
            }
        }

        // add modified classname to Fields
        if (uidl.hasAttribute("modified") && component instanceof Field) {
            styleBuf.append(" ");
            styleBuf.append(MODIFIED_CLASSNAME);
        }

        TooltipInfo tooltipInfo = componentDetail.getTooltipInfo();
        if (uidl.hasAttribute("description")) {
            tooltipInfo.setTitle(uidl.getStringAttribute("description"));
        } else {
            tooltipInfo.setTitle(null);
        }

        // add error classname to components w/ error
        if (uidl.hasAttribute("error")) {
            styleBuf.append(" ");
            styleBuf.append(primaryName);
            styleBuf.append(ERROR_CLASSNAME_EXT);

            tooltipInfo.setErrorUidl(uidl.getErrors());
        } else {
            tooltipInfo.setErrorUidl(null);
        }

        // add required style to required components
        if (uidl.hasAttribute("required")) {
            styleBuf.append(" ");
            styleBuf.append(primaryName);
            styleBuf.append(REQUIRED_CLASSNAME_EXT);
        }

        // Styles + disabled & readonly
        component.setStyleName(styleBuf.toString());

        // Set captions
        if (manageCaption) {
            final Container parent = Util.getLayout(component);
            if (parent != null) {
                parent.updateCaption((Paintable) component, uidl);
            }
        }

        if (configuration.useDebugIdInDOM() && uidl.getId().startsWith("PID_S")) {
            DOM.setElementProperty(component.getElement(), "id", uidl.getId()
                    .substring(5));
        }

        /*
         * updateComponentSize need to be after caption update so caption can be
         * taken into account
         */

        updateComponentSize(componentDetail, uidl);

        return false;
    }

    private void updateComponentSize(ComponentDetail cd, UIDL uidl) {
        String w = uidl.hasAttribute("width") ? uidl
                .getStringAttribute("width") : "";

        String h = uidl.hasAttribute("height") ? uidl
                .getStringAttribute("height") : "";

        float relativeWidth = Util.parseRelativeSize(w);
        float relativeHeight = Util.parseRelativeSize(h);

        // First update maps so they are correct in the setHeight/setWidth calls
        if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
            // One or both is relative
            FloatSize relativeSize = new FloatSize(relativeWidth,
                    relativeHeight);
            if (cd.getRelativeSize() == null && cd.getOffsetSize() != null) {
                // The component has changed from absolute size to relative size
                relativeSizeChanges.add(cd.getComponent());
            }
            cd.setRelativeSize(relativeSize);
        } else if (relativeHeight < 0.0 && relativeWidth < 0.0) {
            if (cd.getRelativeSize() != null) {
                // The component has changed from relative size to absolute size
                relativeSizeChanges.add(cd.getComponent());
            }
            cd.setRelativeSize(null);
        }

        Widget component = (Widget) cd.getComponent();
        // Set absolute sizes
        if (relativeHeight < 0.0) {
            component.setHeight(h);
        }
        if (relativeWidth < 0.0) {
            component.setWidth(w);
        }

        // Set relative sizes
        if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
            // One or both is relative
            handleComponentRelativeSize(cd);
        }

    }

    /**
     * Traverses recursively child widgets until ContainerResizedListener child
     * widget is found. They will delegate it further if needed.
     * 
     * @param container
     */
    private boolean runningLayout = false;

    public void runDescendentsLayout(HasWidgets container) {
        if (runningLayout) {
            // getConsole().log(
            // "Already running descendents layout. Not running again for "
            // + Util.getSimpleName(container));
            return;
        }
        runningLayout = true;
        internalRunDescendentsLayout(container);
        runningLayout = false;
    }

    /**
     * This will cause re-layouting of all components. Mainly used for
     * development. Published to JavaScript.
     */
    public void forceLayout() {
        Set<Paintable> set = new HashSet<Paintable>();
        for (ComponentDetail cd : idToPaintableDetail.values()) {
            set.add(cd.getComponent());
        }
        Util.componentSizeUpdated(set);
    }

    private void internalRunDescendentsLayout(HasWidgets container) {
        // getConsole().log(
        // "runDescendentsLayout(" + Util.getSimpleName(container) + ")");
        final Iterator<Widget> childWidgets = container.iterator();
        while (childWidgets.hasNext()) {
            final Widget child = childWidgets.next();

            if (child instanceof Paintable) {

                if (handleComponentRelativeSize(child)) {
                    /*
                     * Only need to propagate event if "child" has a relative
                     * size
                     */

                    if (child instanceof ContainerResizedListener) {
                        ((ContainerResizedListener) child).iLayout();
                    }

                    if (child instanceof HasWidgets) {
                        final HasWidgets childContainer = (HasWidgets) child;
                        internalRunDescendentsLayout(childContainer);
                    }
                }
            } else if (child instanceof HasWidgets) {
                // propagate over non Paintable HasWidgets
                internalRunDescendentsLayout((HasWidgets) child);
            }

        }
    }

    /**
     * Converts relative sizes into pixel sizes.
     * 
     * @param child
     * @return true if the child has a relative size
     */
    private boolean handleComponentRelativeSize(ComponentDetail cd) {
        if (cd == null) {
            return false;
        }
        boolean debugSizes = false;

        FloatSize relativeSize = cd.getRelativeSize();
        if (relativeSize == null) {
            return false;
        }
        Widget widget = (Widget) cd.getComponent();

        boolean horizontalScrollBar = false;
        boolean verticalScrollBar = false;

        Container parent = Util.getLayout(widget);
        RenderSpace renderSpace;

        // Parent-less components (like sub-windows) are relative to browser
        // window.
        if (parent == null) {
            renderSpace = new RenderSpace(Window.getClientWidth(), Window
                    .getClientHeight());
        } else {
            renderSpace = parent.getAllocatedSpace(widget);
        }

        if (relativeSize.getHeight() >= 0) {
            if (renderSpace != null) {

                if (renderSpace.getScrollbarSize() > 0) {
                    if (relativeSize.getWidth() > 100) {
                        horizontalScrollBar = true;
                    } else if (relativeSize.getWidth() < 0
                            && renderSpace.getWidth() > 0) {
                        int offsetWidth = widget.getOffsetWidth();
                        int width = renderSpace.getWidth();
                        if (offsetWidth > width) {
                            horizontalScrollBar = true;
                        }
                    }
                }

                int height = renderSpace.getHeight();
                if (horizontalScrollBar) {
                    height -= renderSpace.getScrollbarSize();
                }
                if (validatingLayouts && height <= 0) {
                    zeroHeightComponents.add(cd.getComponent());
                }

                height = (int) (height * relativeSize.getHeight() / 100.0);

                if (height < 0) {
                    height = 0;
                }

                if (debugSizes) {
                    getConsole()
                            .log(
                                    "Widget "
                                            + Util.getSimpleName(widget)
                                            + "/"
                                            + getPid(widget.getElement())
                                            + " relative height "
                                            + relativeSize.getHeight()
                                            + "% of "
                                            + renderSpace.getHeight()
                                            + "px (reported by "

                                            + Util.getSimpleName(parent)
                                            + "/"
                                            + (parent == null ? "?" : parent
                                                    .hashCode()) + ") : "
                                            + height + "px");
                }
                widget.setHeight(height + "px");
            } else {
                widget.setHeight(relativeSize.getHeight() + "%");
                ApplicationConnection.getConsole().error(
                        Util.getLayout(widget).getClass().getName()
                                + " did not produce allocatedSpace for "
                                + widget.getClass().getName());
            }
        }

        if (relativeSize.getWidth() >= 0) {

            if (renderSpace != null) {

                int width = renderSpace.getWidth();

                if (renderSpace.getScrollbarSize() > 0) {
                    if (relativeSize.getHeight() > 100) {
                        verticalScrollBar = true;
                    } else if (relativeSize.getHeight() < 0
                            && renderSpace.getHeight() > 0
                            && widget.getOffsetHeight() > renderSpace
                                    .getHeight()) {
                        verticalScrollBar = true;
                    }
                }

                if (verticalScrollBar) {
                    width -= renderSpace.getScrollbarSize();
                }
                if (validatingLayouts && width <= 0) {
                    zeroWidthComponents.add(cd.getComponent());
                }

                width = (int) (width * relativeSize.getWidth() / 100.0);

                if (width < 0) {
                    width = 0;
                }

                if (debugSizes) {
                    getConsole().log(
                            "Widget " + Util.getSimpleName(widget) + "/"
                                    + getPid(widget.getElement())
                                    + " relative width "
                                    + relativeSize.getWidth() + "% of "
                                    + renderSpace.getWidth()
                                    + "px (reported by "
                                    + Util.getSimpleName(parent) + "/"
                                    + (parent == null ? "?" : getPid(parent))
                                    + ") : " + width + "px");
                }
                widget.setWidth(width + "px");
            } else {
                widget.setWidth(relativeSize.getWidth() + "%");
                ApplicationConnection.getConsole().error(
                        Util.getLayout(widget).getClass().getName()
                                + " did not produce allocatedSpace for "
                                + widget.getClass().getName());
            }
        }

        return true;
    }

    /**
     * Converts relative sizes into pixel sizes.
     * 
     * @param child
     * @return true if the child has a relative size
     */
    public boolean handleComponentRelativeSize(Widget child) {
        return handleComponentRelativeSize(idToPaintableDetail.get(getPid(child
                .getElement())));

    }

    public FloatSize getRelativeSize(Widget widget) {
        return idToPaintableDetail.get(getPid(widget.getElement()))
                .getRelativeSize();
    }

    /**
     * Get either existing or new Paintable for given UIDL.
     * 
     * If corresponding Paintable has been previously painted, return it.
     * Otherwise create and register a new Paintable from UIDL. Caller must
     * update the returned Paintable from UIDL after it has been connected to
     * parent.
     * 
     * @param uidl
     *            UIDL to create Paintable from.
     * @return Either existing or new Paintable corresponding to UIDL.
     */
    public Paintable getPaintable(UIDL uidl) {
        final String id = uidl.getId();
        Paintable w = getPaintable(id);
        if (w != null) {
            return w;
        } else {
            w = widgetSet.createWidget(uidl);
            registerPaintable(id, w);
            return w;

        }
    }

    /**
     * Returns a Paintable element by its root element
     * 
     * @param element
     *            Root element of the paintable
     */
    public Paintable getPaintable(Element element) {
        return getPaintable(getPid(element));
    }

    public String getResource(String name) {
        return resourcesMap.get(name);
    }

    /**
     * Singleton method to get instance of app's context menu.
     * 
     * @return IContextMenu object
     */
    public IContextMenu getContextMenu() {
        if (contextMenu == null) {
            contextMenu = new IContextMenu();
            DOM.setElementProperty(contextMenu.getElement(), "id",
                    "PID_TOOLKIT_CM");
        }
        return contextMenu;
    }

    /**
     * Translates custom protocols in UIRL URI's to be recognizable by browser.
     * All uri's from UIDL should be routed via this method before giving them
     * to browser due URI's in UIDL may contain custom protocols like theme://.
     * 
     * @param toolkitUri
     *            toolkit URI from uidl
     * @return translated URI ready for browser
     */
    public String translateToolkitUri(String toolkitUri) {
        if (toolkitUri == null) {
            return null;
        }
        if (toolkitUri.startsWith("theme://")) {
            final String themeUri = configuration.getThemeUri();
            if (themeUri == null) {
                console
                        .error("Theme not set: ThemeResource will not be found. ("
                                + toolkitUri + ")");
            }
            toolkitUri = themeUri + toolkitUri.substring(7);
        }
        return toolkitUri;
    }

    public String getThemeUri() {
        return configuration.getThemeUri();
    }

    /**
     * Listens for Notification hide event, and redirects. Used for system
     * messages, such as session expired.
     * 
     */
    private class NotificationRedirect implements INotification.EventListener {
        String url;

        NotificationRedirect(String url) {
            this.url = url;
        }

        public void notificationHidden(HideEvent event) {
            redirect(url);
        }

    }

    /* Extended title handling */

    /**
     * Data showed in tooltips are stored centrilized as it may be needed in
     * varios place: caption, layouts, and in owner components themselves.
     * 
     * Updating TooltipInfo is done in updateComponent method.
     * 
     */
    public TooltipInfo getTitleInfo(Paintable titleOwner) {
        if (null == titleOwner) {
            return null;
        }
        ComponentDetail pd = idToPaintableDetail.get(getPid(titleOwner));
        if (null != pd) {
            return pd.getTooltipInfo();
        } else {
            return null;
        }
    }

    private final ITooltip tooltip = new ITooltip(this);

    /**
     * Component may want to delegate Tooltip handling to client. Layouts add
     * Tooltip (description, errors) to caption, but some components may want
     * them to appear one other elements too.
     * 
     * Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
     * 
     * @param event
     * @param owner
     */
    public void handleTooltipEvent(Event event, Paintable owner) {
        tooltip.handleTooltipEvent(event, owner);

    }

    /**
     * Adds PNG-fix conditionally (only for IE6) to the specified IMG -element.
     * 
     * @param el
     *            the IMG element to fix
     */
    public void addPngFix(Element el) {
        BrowserInfo b = BrowserInfo.get();
        if (b.isIE6()) {
            Util.addPngFix(el, getThemeUri()
                    + "/../default/common/img/blank.gif");
        }
    }

    /*
     * Helper to run layout functions triggered by child components with a
     * decent interval.
     */
    private final Timer layoutTimer = new Timer() {

        private boolean isPending = false;

        @Override
        public void schedule(int delayMillis) {
            if (!isPending) {
                super.schedule(delayMillis);
                isPending = true;
            }
        }

        @Override
        public void run() {
            getConsole().log(
                    "Running re-layout of " + view.getClass().getName());
            runDescendentsLayout(view);
            isPending = false;
        }
    };

    /**
     * Components can call this function to run all layout functions. This is
     * usually done, when component knows that its size has changed.
     */
    public void requestLayoutPhase() {
        layoutTimer.schedule(500);
    }

    private String windowName = null;

    /**
     * Reset the name of the current browser-window. This should reflect the
     * window-name used in the server, but might be different from the
     * window-object target-name on client.
     * 
     * @param stringAttribute
     *            New name for the window.
     */
    public void setWindowName(String newName) {
        windowName = newName;
    }

    public void captionSizeUpdated(Paintable component) {
        componentCaptionSizeChanges.add(component);
    }

    public void analyzeLayouts() {
        makeUidlRequest("", true, false, true);
    }

    public IView getView() {
        return view;
    }

}