summaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/terminal/gwt/client/ui/layout/LayoutDependencyTree.java
blob: 1ca8933ff2fd1226ccee28466f28c3ba55c4b5ee (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
/*
@VaadinApache2LicenseForJavaFiles@
 */
package com.vaadin.terminal.gwt.client.ui.layout;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.vaadin.terminal.gwt.client.ComponentConnector;
import com.vaadin.terminal.gwt.client.ComponentContainerConnector;
import com.vaadin.terminal.gwt.client.ComponentState;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VConsole;
import com.vaadin.terminal.gwt.client.ui.ManagedLayout;

public class LayoutDependencyTree {
    private class LayoutDependency {
        private final ComponentConnector connector;
        private final int direction;

        private boolean needsLayout = false;
        private boolean needsMeasure = false;

        private boolean scrollingParentCached = false;
        private ComponentConnector scrollingBoundary = null;

        private Set<ComponentConnector> measureBlockers = new HashSet<ComponentConnector>();
        private Set<ComponentConnector> layoutBlockers = new HashSet<ComponentConnector>();

        public LayoutDependency(ComponentConnector connector, int direction) {
            this.connector = connector;
            this.direction = direction;
        }

        private void addLayoutBlocker(ComponentConnector blocker) {
            boolean blockerAdded = layoutBlockers.add(blocker);
            if (blockerAdded && layoutBlockers.size() == 1) {
                if (needsLayout) {
                    getLayoutQueue(direction).remove(connector);
                } else {
                    // Propagation already done if needsLayout is set
                    propagatePotentialLayout();
                }
            }
        }

        private void removeLayoutBlocker(ComponentConnector blocker) {
            boolean removed = layoutBlockers.remove(blocker);
            if (removed && layoutBlockers.isEmpty()) {
                if (needsLayout) {
                    getLayoutQueue(direction).add((ManagedLayout) connector);
                } else {
                    propagateNoUpcomingLayout();
                }
            }
        }

        private void addMeasureBlocker(ComponentConnector blocker) {
            boolean blockerAdded = measureBlockers.add(blocker);
            if (blockerAdded && measureBlockers.size() == 1) {
                if (needsMeasure) {
                    getMeasureQueue(direction).remove(connector);
                } else {
                    propagatePotentialResize();
                }
            }
        }

        private void removeMeasureBlocker(ComponentConnector blocker) {
            boolean removed = measureBlockers.remove(blocker);
            if (removed && measureBlockers.isEmpty()) {
                if (needsMeasure) {
                    getMeasureQueue(direction).add(connector);
                } else {
                    propagateNoUpcomingResize();
                }
            }
        }

        public void setNeedsMeasure(boolean needsMeasure) {
            if (needsMeasure && !this.needsMeasure) {
                // If enabling needsMeasure
                this.needsMeasure = needsMeasure;

                if (measureBlockers.isEmpty()) {
                    // Add to queue if there are no blockers
                    getMeasureQueue(direction).add(connector);
                    // Only need to propagate if not already propagated when
                    // setting blockers
                    propagatePotentialResize();
                }
            } else if (!needsMeasure && this.needsMeasure
                    && measureBlockers.isEmpty()) {
                // Only disable if there are no blockers (elements gets measured
                // in both directions even if there is a blocker in one
                // direction)
                this.needsMeasure = needsMeasure;
                getMeasureQueue(direction).remove(connector);
                propagateNoUpcomingResize();
            }
        }

        public void setNeedsLayout(boolean needsLayout) {
            if (!(connector instanceof ManagedLayout)) {
                throw new IllegalStateException(
                        "Only managed layouts can need layout, layout attempted for "
                                + Util.getConnectorString(connector));
            }
            if (needsLayout && !this.needsLayout) {
                // If enabling needsLayout
                this.needsLayout = needsLayout;

                if (layoutBlockers.isEmpty()) {
                    // Add to queue if there are no blockers
                    getLayoutQueue(direction).add((ManagedLayout) connector);
                    // Only need to propagate if not already propagated when
                    // setting blockers
                    propagatePotentialLayout();
                }
            } else if (!needsLayout && this.needsLayout
                    && layoutBlockers.isEmpty()) {
                // Only disable if there are no layout blockers
                // (SimpleManagedLayout gets layouted in both directions
                // even if there is a blocker in one direction)
                this.needsLayout = needsLayout;
                getLayoutQueue(direction).remove(connector);
                propagateNoUpcomingLayout();
            }
        }

        private void propagatePotentialResize() {
            for (ComponentConnector needsSize : getNeedsSizeForLayout()) {
                LayoutDependency layoutDependency = getDependency(needsSize,
                        direction);
                layoutDependency.addLayoutBlocker(connector);
            }
        }

        private Collection<ComponentConnector> getNeedsSizeForLayout() {
            // Find all connectors that need the size of this connector for
            // layouting

            // Parent needs size if it isn't relative?
            // Connector itself needs size if it isn't undefined?
            // Children doesn't care?

            ArrayList<ComponentConnector> needsSize = new ArrayList<ComponentConnector>();

            if (!isUndefinedInDirection(connector, direction)) {
                needsSize.add(connector);
            }
            if (!isRelativeInDirection(connector, direction)) {
                ComponentConnector parent = connector.getParent();
                if (parent != null) {
                    needsSize.add(parent);
                }
            }

            return needsSize;
        }

        private void propagateNoUpcomingResize() {
            for (ComponentConnector mightNeedLayout : getNeedsSizeForLayout()) {
                LayoutDependency layoutDependency = getDependency(
                        mightNeedLayout, direction);
                layoutDependency.removeLayoutBlocker(connector);
            }
        }

        private void propagatePotentialLayout() {
            for (ComponentConnector sizeMightChange : getResizedByLayout()) {
                LayoutDependency layoutDependency = getDependency(
                        sizeMightChange, direction);
                layoutDependency.addMeasureBlocker(connector);
            }
        }

        private Collection<ComponentConnector> getResizedByLayout() {
            // Components that might get resized by a layout of this component

            // Parent never resized
            // Connector itself resized if undefined
            // Children resized if relative

            ArrayList<ComponentConnector> resized = new ArrayList<ComponentConnector>();
            if (isUndefinedInDirection(connector, direction)) {
                resized.add(connector);
            }

            if (connector instanceof ComponentContainerConnector) {
                ComponentContainerConnector container = (ComponentContainerConnector) connector;
                for (ComponentConnector child : container.getChildren()) {
                    if (isRelativeInDirection(child, direction)) {
                        resized.add(child);
                    }
                }
            }

            return resized;
        }

        private void propagateNoUpcomingLayout() {
            for (ComponentConnector sizeMightChange : getResizedByLayout()) {
                LayoutDependency layoutDependency = getDependency(
                        sizeMightChange, direction);
                layoutDependency.removeMeasureBlocker(connector);
            }
        }

        public void markSizeAsChanged() {
            // When the size has changed, all that use that size should be
            // layouted
            for (ComponentConnector connector : getNeedsSizeForLayout()) {
                LayoutDependency layoutDependency = getDependency(connector,
                        direction);
                if (connector instanceof ManagedLayout) {
                    layoutDependency.setNeedsLayout(true);
                } else {
                    // Should simulate setNeedsLayout(true) + markAsLayouted ->
                    // propagate needs measure
                    layoutDependency.propagatePostLayoutMeasure();
                }
            }

            // Should also go through the hierarchy to discover appeared or
            // disappeared scrollbars
            ComponentConnector scrollingBoundary = getScrollingBoundary(connector);
            if (scrollingBoundary != null) {
                getDependency(scrollingBoundary, getOppositeDirection())
                        .setNeedsMeasure(true);
            }

        }

        /**
         * Go up the hierarchy to find a component whose size might have changed
         * in the other direction because changes to this component causes
         * scrollbars to appear or disappear.
         * 
         * @return
         */
        private LayoutDependency findPotentiallyChangedScrollbar() {
            ComponentConnector currentConnector = connector;
            while (true) {
                ComponentContainerConnector parent = currentConnector
                        .getParent();
                if (parent == null) {
                    return null;
                }
                if (parent instanceof MayScrollChildren) {
                    return getDependency(currentConnector,
                            getOppositeDirection());
                }
                currentConnector = parent;
            }
        }

        private int getOppositeDirection() {
            return direction == HORIZONTAL ? VERTICAL : HORIZONTAL;
        }

        public void markAsLayouted() {
            if (!layoutBlockers.isEmpty()) {
                // Don't do anything if there are layout blockers (SimpleLayout
                // gets layouted in both directions even if one direction is
                // blocked)
                return;
            }
            setNeedsLayout(false);
            propagatePostLayoutMeasure();
        }

        private void propagatePostLayoutMeasure() {
            for (ComponentConnector resized : getResizedByLayout()) {
                LayoutDependency layoutDependency = getDependency(resized,
                        direction);
                layoutDependency.setNeedsMeasure(true);
            }

            // Special case for e.g. wrapping texts
            if (direction == HORIZONTAL && !connector.isUndefinedWidth()
                    && connector.isUndefinedHeight()) {
                LayoutDependency dependency = getDependency(connector, VERTICAL);
                dependency.setNeedsMeasure(true);
            }
        }

        @Override
        public String toString() {
            String s = getCompactConnectorString(connector) + "\n";
            if (direction == VERTICAL) {
                s += "Vertical";
            } else {
                s += "Horizontal";
            }
            ComponentState state = connector.getState();
            s += " sizing: "
                    + getSizeDefinition(direction == VERTICAL ? state
                            .getHeight() : state.getWidth()) + "\n";

            if (needsLayout) {
                s += "Needs layout\n";
            }
            if (getLayoutQueue(direction).contains(connector)) {
                s += "In layout queue\n";
            }
            s += "Layout blockers: " + blockersToString(layoutBlockers) + "\n";

            if (needsMeasure) {
                s += "Needs measure\n";
            }
            if (getMeasureQueue(direction).contains(connector)) {
                s += "In measure queue\n";
            }
            s += "Measure blockers: " + blockersToString(measureBlockers);

            return s;
        }

        public boolean noMoreChangesExpected() {
            return !needsLayout && !needsMeasure && layoutBlockers.isEmpty()
                    && measureBlockers.isEmpty();
        }

    }

    private static final int HORIZONTAL = 0;
    private static final int VERTICAL = 1;

    private final Map<?, ?>[] dependenciesInDirection = new Map<?, ?>[] {
            new HashMap<ComponentConnector, LayoutDependency>(),
            new HashMap<ComponentConnector, LayoutDependency>() };

    private final Collection<?>[] measureQueueInDirection = new HashSet<?>[] {
            new HashSet<ComponentConnector>(),
            new HashSet<ComponentConnector>() };

    private final Collection<?>[] layoutQueueInDirection = new HashSet<?>[] {
            new HashSet<ComponentConnector>(),
            new HashSet<ComponentConnector>() };

    public void setNeedsMeasure(ComponentConnector connector,
            boolean needsMeasure) {
        setNeedsHorizontalMeasure(connector, needsMeasure);
        setNeedsVerticalMeasure(connector, needsMeasure);
    }

    public void setNeedsHorizontalMeasure(ComponentConnector connector,
            boolean needsMeasure) {
        LayoutDependency dependency = getDependency(connector, HORIZONTAL);
        dependency.setNeedsMeasure(needsMeasure);
    }

    public void setNeedsVerticalMeasure(ComponentConnector connector,
            boolean needsMeasure) {
        LayoutDependency dependency = getDependency(connector, VERTICAL);
        dependency.setNeedsMeasure(needsMeasure);
    }

    private LayoutDependency getDependency(ComponentConnector connector,
            int direction) {
        @SuppressWarnings("unchecked")
        Map<ComponentConnector, LayoutDependency> dependencies = (Map<ComponentConnector, LayoutDependency>) dependenciesInDirection[direction];
        LayoutDependency dependency = dependencies.get(connector);
        if (dependency == null) {
            dependency = new LayoutDependency(connector, direction);
            dependencies.put(connector, dependency);
        }
        return dependency;
    }

    @SuppressWarnings("unchecked")
    private Collection<ManagedLayout> getLayoutQueue(int direction) {
        return (Collection<ManagedLayout>) layoutQueueInDirection[direction];
    }

    @SuppressWarnings("unchecked")
    private Collection<ComponentConnector> getMeasureQueue(int direction) {
        return (Collection<ComponentConnector>) measureQueueInDirection[direction];
    }

    public void setNeedsHorizontalLayout(ManagedLayout layout,
            boolean needsLayout) {
        LayoutDependency dependency = getDependency(layout, HORIZONTAL);
        dependency.setNeedsLayout(needsLayout);
    }

    public void setNeedsVerticalLayout(ManagedLayout layout, boolean needsLayout) {
        LayoutDependency dependency = getDependency(layout, VERTICAL);
        dependency.setNeedsLayout(needsLayout);
    }

    public void markAsHorizontallyLayouted(ManagedLayout layout) {
        LayoutDependency dependency = getDependency(layout, HORIZONTAL);
        dependency.markAsLayouted();
    }

    public void markAsVerticallyLayouted(ManagedLayout layout) {
        LayoutDependency dependency = getDependency(layout, VERTICAL);
        dependency.markAsLayouted();
    }

    public void markHeightAsChanged(ComponentConnector connector) {
        LayoutDependency dependency = getDependency(connector, VERTICAL);
        dependency.markSizeAsChanged();
    }

    public void markWidthAsChanged(ComponentConnector connector) {
        LayoutDependency dependency = getDependency(connector, HORIZONTAL);
        dependency.markSizeAsChanged();
    }

    private static boolean isRelativeInDirection(ComponentConnector connector,
            int direction) {
        if (direction == HORIZONTAL) {
            return connector.isRelativeWidth();
        } else {
            return connector.isRelativeHeight();
        }
    }

    private static boolean isUndefinedInDirection(ComponentConnector connector,
            int direction) {
        if (direction == VERTICAL) {
            return connector.isUndefinedHeight();
        } else {
            return connector.isUndefinedWidth();
        }
    }

    private static String getCompactConnectorString(ComponentConnector connector) {
        return Util.getSimpleName(connector) + " ("
                + connector.getConnectorId() + ")";
    }

    private static String getSizeDefinition(String size) {
        if (size == null || size.length() == 0) {
            return "undefined";
        } else if (size.endsWith("%")) {
            return "relative";
        } else {
            return "fixed";
        }
    }

    private static String blockersToString(
            Collection<ComponentConnector> blockers) {
        StringBuilder b = new StringBuilder("[");
        for (ComponentConnector blocker : blockers) {
            if (b.length() != 1) {
                b.append(", ");
            }
            b.append(getCompactConnectorString(blocker));
        }
        b.append(']');
        return b.toString();
    }

    public boolean hasConnectorsToMeasure() {
        return !measureQueueInDirection[HORIZONTAL].isEmpty()
                || !measureQueueInDirection[VERTICAL].isEmpty();
    }

    public boolean hasHorizontalConnectorToLayout() {
        return !getLayoutQueue(HORIZONTAL).isEmpty();
    }

    public boolean hasVerticaConnectorToLayout() {
        return !getLayoutQueue(VERTICAL).isEmpty();
    }

    public ManagedLayout[] getHorizontalLayoutTargets() {
        Collection<ManagedLayout> queue = getLayoutQueue(HORIZONTAL);
        return queue.toArray(new ManagedLayout[queue.size()]);
    }

    public ManagedLayout[] getVerticalLayoutTargets() {
        Collection<ManagedLayout> queue = getLayoutQueue(VERTICAL);
        return queue.toArray(new ManagedLayout[queue.size()]);
    }

    public Collection<ComponentConnector> getMeasureTargets() {
        Collection<ComponentConnector> measureTargets = new HashSet<ComponentConnector>(
                getMeasureQueue(HORIZONTAL));
        measureTargets.addAll(getMeasureQueue(VERTICAL));
        return measureTargets;
    }

    public void logDependencyStatus(ComponentConnector connector) {
        VConsole.log("====");
        VConsole.log(getDependency(connector, HORIZONTAL).toString());
        VConsole.log(getDependency(connector, VERTICAL).toString());
    }

    public boolean noMoreChangesExpected(ComponentConnector connector) {
        return getDependency(connector, HORIZONTAL).noMoreChangesExpected()
                && getDependency(connector, VERTICAL).noMoreChangesExpected();
    }

    public ComponentConnector getScrollingBoundary(ComponentConnector connector) {
        LayoutDependency dependency = getDependency(connector, HORIZONTAL);
        if (!dependency.scrollingParentCached) {
            ComponentContainerConnector parent = dependency.connector
                    .getParent();
            if (parent instanceof MayScrollChildren) {
                dependency.scrollingBoundary = connector;
            } else if (parent != null) {
                dependency.scrollingBoundary = getScrollingBoundary(parent);
            } else {
                // No scrolling parent
            }

            dependency.scrollingParentCached = true;
        }
        return dependency.scrollingBoundary;
    }
}