summaryrefslogtreecommitdiffstats
path: root/mobile/android/thirdparty/org/lucasr/dspec/DesignSpec.java
blob: 43505be4e2b9d71bfc2c9fa5518cf35030b7238b (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
/*
 * Copyright (C) 2014 Lucas Rocha
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.lucasr.dspec;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Draw a baseline grid, keylines, and spacing markers on top of a {@link View}.
 *
 * A {@link DesignSpec} can be configure programmatically as follows:
 * <ol>
 * <li>Toggle baseline grid visibility with {@link #setBaselineGridVisible(boolean)}.</li>
 * <li>Change baseline grid cell width with {@link #setBaselineGridCellSize(float)}.
 * <li>Change baseline grid color with {@link #setBaselineGridColor(int)}.
 * <li>Toggle keylines visibility with {@link #setKeylinesVisible(boolean)}.
 * <li>Change keylines color with {@link #setKeylinesColor(int)}.
 * <li>Add keylines with {@link #addKeyline(float, From)}.
 * <li>Toggle spacings visibility with {@link #setSpacingsVisible(boolean)}.
 * <li>Change spacings color with {@link #setSpacingsColor(int)}.
 * <li>Add spacing with {@link #addSpacing(float, float, From)}.
 * </ol>
 *
 * You can also define a {@link DesignSpec} via a raw JSON resource as follows:
 * <pre>
 * {
 *     "baselineGridVisible": true,
 *     "baselineGridCellSize": 8,
 *     "keylines": [
 *         { "offset": 16,
 *           "from": "LEFT" },
 *         { "offset": 72,
 *           "from": "LEFT" },
 *         { "offset": 16,
 *           "from": "RIGHT" }
 *     ],
 *     "spacings": [
 *         { "offset": 0,
 *           "size": 16,
 *           "from": "LEFT" },
 *         { "offset": 56,
 *           "size": 16,
 *           "from": "LEFT" },
 *         { "offset": 0,
 *           "size": 16,
 *           "from": "RIGHT" }
 *     ]
 * }
 * </pre>
 *
 * The {@link From} arguments implicitly define the orientation of the given
 * keyline or spacing i.e. {@link From#LEFT}, {@link From#RIGHT}, {@link From#HORIZONTAL_CENTER}
 * are implicitly vertical; and {@link From#TOP}, {@link From#BOTTOM}, {@link From#VERTICAL_CENTER}
 * are implicitly horizontal.
 *
 * The {@link From} arguments also define the 'direction' of the offsets and sizes in keylines and
 * spacings. For example, a keyline using {@link From#RIGHT} will have its offset measured from
 * right to left of the target {@link View}.
 *
 * The easiest way to use a {@link DesignSpec} is by enclosing your target {@link View} with
 * a {@link DesignSpecFrameLayout} using the {@code designSpec} attribute as follows:
 * <pre>
 * <org.lucasr.dspec.DesignSpecFrameLayout
 *     xmlns:android="http://schemas.android.com/apk/res/android"
 *     android:id="@+id/design_spec"
 *     android:layout_width="match_parent"
 *     android:layout_height="match_parent"
 *     app:designSpec="@raw/my_spec">
 *
 *     ...
 *
 * </org.lucasr.dspec.DesignSpecFrameLayout>
 * </pre>
 *
 * Where {@code @raw/my_spec} is a raw JSON resource. Because the {@link DesignSpec} is
 * defined in an Android resource, you can vary it according to the target form factor using
 * well-known resource qualifiers making it easy to define different specs for phones and tablets.
 *
 * Because {@link DesignSpec} is a {@link Drawable}, you can simply add it to any
 * {@link android.view.ViewOverlay} if you're running your app on API level >= 18:
 *
 * <pre>
 * DesignSpec designSpec = DesignSpec.fromResource(someView, R.raw.some_spec);
 * someView.getOverlay().add(designSpec);
 * </pre>
 *
 * @see DesignSpecFrameLayout
 * @see #fromResource(View, int)
 */
public class DesignSpec extends Drawable {
    private static final boolean DEFAULT_BASELINE_GRID_VISIBLE = false;
    private static final boolean DEFAULT_KEYLINES_VISIBLE = true;
    private static final boolean DEFAULT_SPACINGS_VISIBLE = true;

    private static final int DEFAULT_BASELINE_GRID_CELL_SIZE_DIP = 8;

    private static final String DEFAULT_BASELINE_GRID_COLOR = "#44C2185B";
    private static final String DEFAULT_KEYLINE_COLOR = "#CCC2185B";
    private static final String DEFAULT_SPACING_COLOR = "#CC89FDFD";

    private static final float KEYLINE_STROKE_WIDTH_DIP = 1.1f;

    private static final String JSON_KEY_BASELINE_GRID_VISIBLE = "baselineGridVisible";
    private static final String JSON_KEY_BASELINE_GRID_CELL_SIZE = "baselineGridCellSize";
    private static final String JSON_KEY_BASELINE_GRID_COLOR = "baselineGridColor";

    private static final String JSON_KEY_KEYLINES_VISIBLE = "keylinesVisible";
    private static final String JSON_KEY_KEYLINES_COLOR = "keylinesColor";
    private static final String JSON_KEY_KEYLINES = "keylines";

    private static final String JSON_KEY_OFFSET = "offset";
    private static final String JSON_KEY_SIZE = "size";
    private static final String JSON_KEY_FROM = "from";

    private static final String JSON_KEY_SPACINGS_VISIBLE = "spacingsVisible";
    private static final String JSON_KEY_SPACINGS_COLOR = "spacingsColor";
    private static final String JSON_KEY_SPACINGS = "spacings";

    /**
     * Defined the reference point from which keyline/spacing offsets and sizes
     * will be calculated.
     */
    public enum From {
        LEFT,
        RIGHT,
        TOP,
        BOTTOM,
        VERTICAL_CENTER,
        HORIZONTAL_CENTER
    }

    private static class Keyline {
        public final float position;
        public final From from;

        public Keyline(float position, From from) {
            this.position = position;
            this.from = from;
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Keyline)) {
                return false;
            }

            if (o == this) {
                return true;
            }

            final Keyline other = (Keyline) o;
            return (this.position == other.position && this.from == other.from);
        }
    }

    private static class Spacing {
        public final float offset;
        public final float size;
        public final From from;

        public Spacing(float offset, float size, From from) {
            this.offset = offset;
            this.size = size;
            this.from = from;
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Keyline)) {
                return false;
            }

            if (o == this) {
                return true;
            }

            final Spacing other = (Spacing) o;
            return (this.offset == other.offset &&
                    this.size == other.size &&
                    this.from == other.from);
        }
    }

    private final View mHostView;

    private final float mDensity;

    private boolean mBaselineGridVisible = DEFAULT_BASELINE_GRID_VISIBLE;
    private float mBaselineGridCellSize;
    private final Paint mBaselineGridPaint;

    private boolean mKeylinesVisible = DEFAULT_KEYLINES_VISIBLE;
    private final Paint mKeylinesPaint;
    private final List<Keyline> mKeylines;

    private boolean mSpacingsVisible = DEFAULT_SPACINGS_VISIBLE;
    private final Paint mSpacingsPaint;
    private final List<Spacing> mSpacings;

    public DesignSpec(Resources resources, View hostView) {
        mHostView = hostView;
        mDensity = resources.getDisplayMetrics().density;

        mKeylines = new ArrayList<Keyline>();
        mSpacings = new ArrayList<Spacing>();

        mBaselineGridPaint = new Paint();
        mBaselineGridPaint.setColor(Color.parseColor(DEFAULT_BASELINE_GRID_COLOR));

        mKeylinesPaint = new Paint();
        mKeylinesPaint.setStrokeWidth(KEYLINE_STROKE_WIDTH_DIP * mDensity);
        mKeylinesPaint.setColor(Color.parseColor(DEFAULT_KEYLINE_COLOR));

        mSpacingsPaint = new Paint();
        mSpacingsPaint.setColor(Color.parseColor(DEFAULT_SPACING_COLOR));

        mBaselineGridCellSize = mDensity * DEFAULT_BASELINE_GRID_CELL_SIZE_DIP;
    }

    /**
     * Whether or not the baseline grid should be drawn.
     */
    public boolean isBaselineGridVisible() {
        return mBaselineGridVisible;
    }

    /**
     * Sets the baseline grid visibility.
     */
    public DesignSpec setBaselineGridVisible(boolean visible) {
        if (mBaselineGridVisible == visible) {
            return this;
        }

        mBaselineGridVisible = visible;
        invalidateSelf();

        return this;
    }

    /**
     * Sets the size of the baseline grid cells. By default, it uses the
     * material design 8dp cell size.
     */
    public DesignSpec setBaselineGridCellSize(float cellSize) {
        if (mBaselineGridCellSize == cellSize) {
            return this;
        }

        mBaselineGridCellSize = cellSize;
        invalidateSelf();

        return this;
    }

    /**
     * Sets the baseline grid color.
     */
    public DesignSpec setBaselineGridColor(int color) {
        if (mBaselineGridPaint.getColor() == color) {
            return this;
        }

        mBaselineGridPaint.setColor(color);
        invalidateSelf();

        return this;
    }

    /**
     * Whether or not the keylines should be drawn.
     */
    public boolean areKeylinesVisible() {
        return mKeylinesVisible;
    }

    /**
     * Sets the visibility of keylines.
     */
    public DesignSpec setKeylinesVisible(boolean visible) {
        if (mKeylinesVisible == visible) {
            return this;
        }

        mKeylinesVisible = visible;
        invalidateSelf();

        return this;
    }

    /**
     * Sets the keyline color.
     */
    public DesignSpec setKeylinesColor(int color) {
        if (mKeylinesPaint.getColor() == color) {
            return this;
        }

        mKeylinesPaint.setColor(color);
        invalidateSelf();

        return this;
    }

    /**
     * Adds a keyline to the {@link DesignSpec}.
     */
    public DesignSpec addKeyline(float position, From from) {
        final Keyline keyline = new Keyline(position * mDensity, from);
        if (mKeylines.contains(keyline)) {
            return this;
        }

        mKeylines.add(keyline);
        return this;
    }

    /**
     * Whether or not the spacing markers should be drawn.
     */
    public boolean areSpacingsVisible() {
        return mSpacingsVisible;
    }

    /**
     * Sets the visibility of spacing markers.
     */
    public DesignSpec setSpacingsVisible(boolean visible) {
        if (mSpacingsVisible == visible) {
            return this;
        }

        mSpacingsVisible = visible;
        invalidateSelf();

        return this;
    }

    /**
     * Sets the spacing mark color.
     */
    public DesignSpec setSpacingsColor(int color) {
        if (mSpacingsPaint.getColor() == color) {
            return this;
        }

        mSpacingsPaint.setColor(color);
        invalidateSelf();

        return this;
    }

    /**
     * Adds a spacing mark to the {@link DesignSpec}.
     */
    public DesignSpec addSpacing(float position, float size, From from) {
        final Spacing spacing = new Spacing(position * mDensity, size * mDensity, from);
        if (mSpacings.contains(spacing)) {
            return this;
        }

        mSpacings.add(spacing);
        return this;
    }

    private void drawBaselineGrid(Canvas canvas) {
        if (!mBaselineGridVisible) {
            return;
        }

        final int width = getIntrinsicWidth();
        final int height = getIntrinsicHeight();

        float x = mBaselineGridCellSize;
        while (x < width) {
            canvas.drawLine(x, 0, x, height, mBaselineGridPaint);
            x += mBaselineGridCellSize;
        }

        float y = mBaselineGridCellSize;
        while (y < height) {
            canvas.drawLine(0, y, width, y, mBaselineGridPaint);
            y += mBaselineGridCellSize;
        }
    }

    private void drawKeylines(Canvas canvas) {
        if (!mKeylinesVisible) {
            return;
        }

        final int width = getIntrinsicWidth();
        final int height = getIntrinsicHeight();

        final int count = mKeylines.size();
        for (int i = 0; i < count; i++) {
            final Keyline keyline = mKeylines.get(i);

            final float position;
            switch (keyline.from) {
                case LEFT:
                case TOP:
                    position = keyline.position;
                    break;

                case RIGHT:
                    position = width - keyline.position;
                    break;

                case BOTTOM:
                    position = height - keyline.position;
                    break;

                case VERTICAL_CENTER:
                    position = (height / 2) + keyline.position;
                    break;

                case HORIZONTAL_CENTER:
                    position = (width / 2) + keyline.position;
                    break;

                default:
                    throw new IllegalStateException("Invalid keyline offset");
            }

            switch (keyline.from) {
                case LEFT:
                case RIGHT:
                case HORIZONTAL_CENTER:
                    canvas.drawLine(position, 0, position, height, mKeylinesPaint);
                    break;

                case TOP:
                case BOTTOM:
                case VERTICAL_CENTER:
                    canvas.drawLine(0, position, width, position, mKeylinesPaint);
                    break;
            }
        }
    }

    private void drawSpacings(Canvas canvas) {
        if (!mSpacingsVisible) {
            return;
        }

        final int width = getIntrinsicWidth();
        final int height = getIntrinsicHeight();

        final int count = mSpacings.size();
        for (int i = 0; i < count; i++) {
            final Spacing spacing = mSpacings.get(i);

            final float position1;
            final float position2;
            switch (spacing.from) {
                case LEFT:
                case TOP:
                    position1 = spacing.offset;
                    position2 = position1 + spacing.size;
                    break;

                case RIGHT:
                    position1 = width - spacing.offset + spacing.size;
                    position2 = width - spacing.offset;
                    break;

                case BOTTOM:
                    position1 = height - spacing.offset + spacing.size;
                    position2 = height - spacing.offset;
                    break;

                case VERTICAL_CENTER:
                    position1 = (height / 2) + spacing.offset;
                    position2 = position1 + spacing.size;
                    break;

                case HORIZONTAL_CENTER:
                    position1 = (width / 2) + spacing.offset;
                    position2 = position1 + spacing.size;
                    break;

                default:
                    throw new IllegalStateException("Invalid spacing offset");
            }

            switch (spacing.from) {
                case LEFT:
                case RIGHT:
                case HORIZONTAL_CENTER:
                    canvas.drawRect(position1, 0, position2, height, mSpacingsPaint);
                    break;

                case TOP:
                case BOTTOM:
                case VERTICAL_CENTER:
                    canvas.drawRect(0, position1, width, position2, mSpacingsPaint);
                    break;
            }
        }
    }

    /**
     * Draws the {@link DesignSpec}. You should call this in your {@link View}'s
     * {@link View#onDraw(Canvas)} method if you're not simply enclosing it with a
     * {@link DesignSpecFrameLayout}.
     */
    @Override
    public void draw(Canvas canvas) {
        drawSpacings(canvas);
        drawBaselineGrid(canvas);
        drawKeylines(canvas);
    }

    @Override
    public int getIntrinsicWidth() {
        return mHostView.getWidth();
    }

    @Override
    public int getIntrinsicHeight() {
        return mHostView.getHeight();
    }

    @Override
    public void setAlpha(int alpha) {
        mBaselineGridPaint.setAlpha(alpha);
        mKeylinesPaint.setAlpha(alpha);
        mSpacingsPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mBaselineGridPaint.setColorFilter(cf);
        mKeylinesPaint.setColorFilter(cf);
        mSpacingsPaint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return  PixelFormat.TRANSLUCENT;
    }

    /**
     * Creates a new {@link DesignSpec} instance from a resource ID using a {@link View}
     * that will provide the {@link DesignSpec}'s intrinsic dimensions.
     *
     * @param view The {@link View} who will own the new {@link DesignSpec} instance.
     * @param resId The resource ID pointing to a raw JSON resource.
     * @return The newly created {@link DesignSpec} instance.
     */
    public static DesignSpec fromResource(View view, int resId) {
        final Resources resources = view.getResources();
        final DesignSpec spec = new DesignSpec(resources, view);
        if (resId == 0) {
            return spec;
        }

        final JSONObject json;
        try {
            json = RawResource.getAsJSON(resources, resId);
        } catch (IOException e) {
            throw new IllegalStateException("Could not read design spec resource", e);
        }

        final float density = resources.getDisplayMetrics().density;

        spec.setBaselineGridCellSize(density * json.optInt(JSON_KEY_BASELINE_GRID_CELL_SIZE,
                DEFAULT_BASELINE_GRID_CELL_SIZE_DIP));

        spec.setBaselineGridVisible(json.optBoolean(JSON_KEY_BASELINE_GRID_VISIBLE,
                DEFAULT_BASELINE_GRID_VISIBLE));
        spec.setKeylinesVisible(json.optBoolean(JSON_KEY_KEYLINES_VISIBLE,
                DEFAULT_KEYLINES_VISIBLE));
        spec.setSpacingsVisible(json.optBoolean(JSON_KEY_SPACINGS_VISIBLE,
                DEFAULT_SPACINGS_VISIBLE));

        spec.setBaselineGridColor(Color.parseColor(json.optString(JSON_KEY_BASELINE_GRID_COLOR,
                DEFAULT_BASELINE_GRID_COLOR)));
        spec.setKeylinesColor(Color.parseColor(json.optString(JSON_KEY_KEYLINES_COLOR,
                DEFAULT_KEYLINE_COLOR)));
        spec.setSpacingsColor(Color.parseColor(json.optString(JSON_KEY_SPACINGS_COLOR,
                DEFAULT_SPACING_COLOR)));

        final JSONArray keylines = json.optJSONArray(JSON_KEY_KEYLINES);
        if (keylines != null) {
            final int keylineCount = keylines.length();
            for (int i = 0; i < keylineCount; i++) {
                try {
                    final JSONObject keyline = keylines.getJSONObject(i);
                    spec.addKeyline(keyline.getInt(JSON_KEY_OFFSET),
                            From.valueOf(keyline.getString(JSON_KEY_FROM).toUpperCase()));
                } catch (JSONException e) {
                    continue;
                }
            }
        }

        final JSONArray spacings = json.optJSONArray(JSON_KEY_SPACINGS);
        if (spacings != null) {
            final int spacingCount = spacings.length();
            for (int i = 0; i < spacingCount; i++) {
                try {
                    final JSONObject spacing = spacings.getJSONObject(i);
                    spec.addSpacing(spacing.getInt(JSON_KEY_OFFSET), spacing.getInt(JSON_KEY_SIZE),
                            From.valueOf(spacing.getString(JSON_KEY_FROM).toUpperCase()));
                } catch (JSONException e) {
                    continue;
                }
            }
        }

        return spec;
    }
}