aboutsummaryrefslogtreecommitdiff
path: root/source/ui/CodeView.mc
blob: 03f1fa7736c5b7dc8aea54a1b5f7a2de51ee8737 (plain) (blame)
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
// Author:  cirakg & claude ai
// Summary: Shows a barcode entry: black modules on white at the largest whole module size that fits, linear or 2D.
//
// README 12.2:
//   * Always black on white (whatever the theme), quiet zone included.
//   * Linear codes use the widest horizontal band: on round screens the
//     band's narrower edge limits the width. The module size is the largest
//     whole number of pixels that fits the code plus 10 quiet modules on
//     each side; 1 px is allowed for linear codes (EAN-13 on 218 px screens
//     needs it, and the screenshot decode test covers it).
//   * 2D codes use the largest module size at which the code fits inside the
//     circle (round screens) or the screen (Codes.fits): at least 2 px for
//     square codes, 1 px for PDF417 (a stacked linear code).
//   * 2D codes are encoded once, as a job on a timer ("Encoding... 40%"),
//     and cached packed and sealed with the entry's key
//     (Vault.saveCodeCache), so later openings skip the encoding. Either
//     way a short job turns the packed modules into dark runs (Codes.Runs),
//     and onUpdate draws one rectangle per run (module by module would
//     trip the watchdog with large codes). Codes with more runs than one
//     event can draw are painted into a buffered bitmap in steps first
//     (RunsPainter), and onUpdate draws the bitmap.
//   * Human-readable text under linear codes when enabled and there's room.
//   * Brightness (option, on by default): AMOLED watches get full
//     brightness, MIP watches the backlight, renewed every RENEW_MS for up
//     to BOOST_MS (about a minute, within the burn-in protection limit of
//     AMOLED screens); a tap starts the minute again. The view's one
//     ticker timer does the renewing (and redraws the progress while
//     encoding), so a code screen never needs more timers.
//   * Too big: a message with the size needed.
//   * A locked code closes back to the list when auto-lock fires while it
//     is open (README 7.5), like a locked OTP entry: the ticker keeps
//     running for it and checks the session.
// The payload is decrypted when the screen opens and wiped once encoded.

import Toybox.Attention;
import Toybox.Graphics;
import Toybox.Lang;
import Toybox.System;
import Toybox.Timer;
import Toybox.WatchUi;

class CodeView extends WatchUi.View {

    static const QUIET_MODULES = 10;
    static const MIN_LINEAR_PX = 1;
    static const MIN_MATRIX_PX = 2;
    static const BOOST_MS = 60000;
    static const RENEW_MS = 5000;
    static const TICK_MS = 250;

    var header as Entry;
    private var _code as Codes.LinearCode or RunsPainter or Codes.CodeError or Null = null;
    private var _showText as Boolean = true;
    private var _shownLogged as Boolean = false;
    private var _job as Codes.DisplayJob or RunsPainter or Null = null;
    private var _cache as ByteArray? = null;
    private var _runner as Jobs.JobRunner? = null;
    private var _ticker as Timer.Timer? = null;
    private var _startedAt as Number = 0;
    // Brightness: when the current minute started and the last renewal;
    // _boostStart is -1 when there is nothing to renew.
    private var _boostStart as Number = -1;
    private var _lastBoost as Number = 0;
    // The cache-saving one-shot timer (kept so it is not collected).
    var saveTimer as Timer.Timer? = null;

    function initialize(entryHeader as Entry) {
        View.initialize();
        header = entryHeader;
    }

    function onShow() as Void {
        _shownLogged = false;
        encode();
        boostBrightness();
        if (header.locked) {
            startTicker();
        }
    }

    function onHide() as Void {
        stopJob();
        _boostStart = -1;
        stopTicker();
        _code = null;
    }

    private function encode() as Void {
        var vault = AppState.theVault();
        try {
            if (Codes.isMatrix(header.type)) {
                var packed = Codes.Packed.parse(vault.loadCodeCache(header.id));
                if (packed != null) {
                    startJob(new Codes.DisplayJob(null, packed));
                    return;
                }
            }
            var entry = vault.open(header.id);
            var payload = Bytes.toUtf8(entry.payload as ByteArray);
            _showText = (entry.options & Codes.OPT_SHOW_TEXT) != 0;
            if (payload == null) {
                _code = new Codes.CodeError("damaged text");
            } else if (Codes.isMatrix(entry.type)) {
                var screen = System.getDeviceSettings();
                var job = Codes.matrixJob(entry.type, payload, entry.options, screen.screenWidth, screen.screenHeight, Ui.isRound());
                if (job != null) {
                    startJob(new Codes.DisplayJob(job, null));
                } else {
                    _code = new Codes.CodeError(Codes.name(entry.type) + " is not supported yet");
                }
            } else {
                _code = Codes.encode(entry.type, payload, entry.options);
            }
            entry.wipeSecrets();
        } catch (e instanceof VaultError) {
            _code = new Codes.CodeError(e.code == VaultError.LOCKED ? "locked" : "damaged entry");
        }
    }

    // The first step runs now: a small cached code is then ready for the
    // first draw.
    private function startJob(job as Codes.DisplayJob or RunsPainter) as Void {
        _startedAt = System.getTimer();
        _job = job;
        if (job.step(1)) {
            onEncoded();
            return;
        }
        var runner = new Jobs.JobRunner(job, 1, method(:onEncoded));
        _runner = runner;
        runner.start();
        startTicker();
    }

    private function startTicker() as Void {
        if (_ticker == null) {
            var ticker = new Timer.Timer();
            ticker.start(method(:onTick), TICK_MS, true);
            _ticker = ticker;
        }
    }

    private function stopTicker() as Void {
        var ticker = _ticker;
        if (ticker != null) {
            ticker.stop();
        }
        _ticker = null;
    }

    // Progress redraws while a job runs; brightness renewals during the
    // minute; auto-lock for a locked code. The ticker stops when none of
    // them is needed.
    function onTick() as Void {
        if (header.locked && AppState.checkAutoLock()) {
            WatchUi.popView(WatchUi.SLIDE_RIGHT);
            return;
        }
        if (_job != null) {
            WatchUi.requestUpdate();
        }
        if (_boostStart >= 0) {
            var now = System.getTimer();
            if (now - _boostStart >= BOOST_MS) {
                _boostStart = -1;
            } else if (now - _lastBoost >= RENEW_MS) {
                _lastBoost = now;
                light();
            }
        }
        if (_job == null && _boostStart < 0 && !header.locked) {
            stopTicker();
        }
    }

    function onEncoded() as Void {
        var job = _job;
        stopJob();
        if (job instanceof RunsPainter) {
            _code = job;
            WatchUi.requestUpdate();
            return;
        }
        if (job == null) {
            return;
        }
        var err = job.error;
        var runs = job.runs;
        if (err != null || runs == null) {
            _code = new Codes.CodeError(err != null ? err : "could not encode");
        } else {
            var cache = job.cache;
            var ms = job.stageMs;
            Diag.data("matrix_stages", "type=" + header.type + " cached=" + (cache == null) + " encode_ms=" + ms[0]
                + " pack_ms=" + ms[1] + " runs_ms=" + ms[2]);
            if (cache != null) {
                Diag.data("matrix_encoded", "type=" + header.type + " size=" + runs.width + "x" + runs.height
                    + " ms=" + (System.getTimer() - _startedAt));
                // Sealing and storing the cache gets its own timer event: the
                // job's last step already used much of this event's budget.
                _cache = cache;
                var t = new Timer.Timer();
                t.start(method(:saveCache), 50, false);
                saveTimer = t;
            }
            var painter = new RunsPainter(runs, Codes.minModulePx(header.type));
            if (!painter.ready()) {
                startJob(painter);
                return;
            }
            _code = painter;
        }
        WatchUi.requestUpdate();
    }

    // Store the packed matrix sealed in the vault (one-shot timer).
    function saveCache() as Void {
        saveTimer = null;
        var cache = _cache;
        _cache = null;
        if (cache == null) {
            return;
        }
        try {
            AppState.theVault().saveCodeCache(header.id, cache);
        } catch (e instanceof VaultError) {
            // Locked meanwhile: no cache this time.
        }
    }

    private function stopJob() as Void {
        var runner = _runner;
        if (runner != null) {
            runner.cancel();
        }
        _runner = null;
        _job = null;
    }

    // Start (or restart, on a tap) the bright minute.
    function boostBrightness() as Void {
        if (!AppState.options.fullBrightness || !(Attention has :backlight)) {
            return;
        }
        _boostStart = System.getTimer();
        _lastBoost = _boostStart;
        light();
        startTicker();
    }

    // Full brightness on AMOLED screens, the backlight on MIP screens.
    private function light() as Void {
        try {
            if (System.getDeviceSettings().requiresBurnInProtection) {
                Attention.backlight(1.0);
            } else {
                Attention.backlight(true);
            }
        } catch (e instanceof Lang.Exception) {
            // BacklightOnTooLongException: the system's limit was reached;
            // a tap asks again.
            _boostStart = -1;
        }
    }

    function onUpdate(dc as Graphics.Dc) as Void {
        var w = dc.getWidth();
        var h = dc.getHeight();
        dc.setColor(Graphics.COLOR_BLACK, Graphics.COLOR_WHITE);
        dc.clear();
        var smallFont = Graphics.FONT_XTINY;
        var smallH = dc.getFontHeight(smallFont);
        var code = _code;
        var job = _job;
        if (code instanceof Codes.LinearCode) {
            drawLinear(dc, code, smallFont, smallH);
        } else if (code instanceof RunsPainter) {
            drawMatrix(dc, code, smallFont, smallH);
        } else if (job != null) {
            var percent = job.percent();
            dc.drawText(w / 2, h / 2 - smallH / 2, smallFont, (job instanceof RunsPainter ? "Drawing… " : "Encoding… ")
                + percent + "%", Graphics.TEXT_JUSTIFY_CENTER);
            Diag.data("code_progress", "percent=" + percent); // for UI scripts
        } else {
            drawMessage(dc, code instanceof Codes.CodeError ? code.message : "…", smallFont, smallH);
        }
        // Name at the top and type and ID at the bottom, in small print.
        var top = Ui.isRound() ? h / 10 : 2;
        dc.setColor(Graphics.COLOR_DK_GRAY, Graphics.COLOR_TRANSPARENT);
        dc.drawText(w / 2, top, smallFont, Ui.fit(dc, header.name, smallFont, 2 * Ui.halfWidthAt(dc, top + smallH)),
            Graphics.TEXT_JUSTIFY_CENTER);
        var bottom = Ui.isRound() ? h - h / 10 - smallH : h - smallH - 2;
        dc.drawText(w / 2, bottom, smallFont, Ui.fit(dc, Codes.name(header.type) + " · " + header.id, smallFont,
            2 * Ui.halfWidthAt(dc, bottom)), Graphics.TEXT_JUSTIFY_CENTER);
        if (!_shownLogged && code != null) {
            _shownLogged = true;
            Diag.shown(code instanceof Codes.CodeError ? "code_error" : "code");
        }
    }

    private function drawMessage(dc as Graphics.Dc, message as String, font as Graphics.FontType, fontH as Number) as Void {
        var w = dc.getWidth();
        var h = dc.getHeight();
        dc.setColor(Graphics.COLOR_BLACK, Graphics.COLOR_TRANSPARENT);
        var lines = Ui.wrap(dc, message, font, 2 * Ui.halfWidthAt(dc, h / 2) - 16);
        var y = h / 2 - lines.size() * fontH / 2;
        for (var i = 0; i < lines.size(); i++) {
            dc.drawText(w / 2, y, font, lines[i], Graphics.TEXT_JUSTIFY_CENTER);
            y += fontH;
        }
    }

    // The bars in the widest band that fits, with text below when enabled.
    private function drawLinear(dc as Graphics.Dc, code as Codes.LinearCode, font as Graphics.FontType, fontH as Number) as Void {
        var w = dc.getWidth();
        var h = dc.getHeight();
        var modules = code.modules;
        var total = modules.size() + 2 * QUIET_MODULES;
        var barH = h * 30 / 100;
        var textH = _showText ? fontH : 0;
        var bandTop = (h - barH - textH) / 2;
        var width = 2 * Ui.halfWidthBetween(dc, bandTop, bandTop + barH + textH) + (Ui.isRound() ? 12 : 8);
        var px = width / total;
        if (px < MIN_LINEAR_PX) {
            drawMessage(dc, "Too large for this screen: needs " + total + " px, " + width + " px available", font, fontH);
            return;
        }
        var x0 = (w - modules.size() * px) / 2;
        dc.setColor(Graphics.COLOR_BLACK, Graphics.COLOR_WHITE);
        var i = 0;
        var n = modules.size();
        while (i < n) {
            if (modules[i] == 1) {
                var start = i;
                while (i < n && modules[i] == 1) {
                    i++;
                }
                dc.fillRectangle(x0 + start * px, bandTop, (i - start) * px, barH);
            } else {
                i++;
            }
        }
        if (_showText) {
            dc.drawText(w / 2, bandTop + barH + 2, font, code.text, Graphics.TEXT_JUSTIFY_CENTER);
        }
    }

    // A 2D code at the largest module size that fits (Codes.fits: inside the
    // circle on round screens), centred.
    private function drawMatrix(dc as Graphics.Dc, painter as RunsPainter, font as Graphics.FontType, fontH as Number) as Void {
        var drawn = painter.draw(dc);
        if (drawn < 0) {
            // The system reclaimed the bitmap: paint it again.
            _code = null;
            startJob(painter);
            return;
        }
        if (drawn == 0) {
            var code = painter.runs;
            var minPx = Codes.minModulePx(header.type);
            drawMessage(dc, "Too large for this screen: needs " + minPx + " px per module, " + (code.width + 2 * code.quiet) * minPx
                + " x " + (code.drawnHeight() + 2 * code.quiet) * minPx + " px", font, fontH);
        }
    }
}

// Draws Codes.Runs centred at the largest module size (16 down to minPx)
// that fits. Up to DIRECT_RUNS runs per watchdog unit are drawn straight
// from the list in onUpdate (one fillRectangle each, measured in the
// watchdog stress build); bigger codes are painted into a two-colour
// buffered bitmap, RUNS_PER_STEP runs per job step, and onUpdate draws the
// bitmap.
class RunsPainter extends Jobs.Job {
    static const DIRECT_RUNS = 1500;
    static const RUNS_PER_STEP = 1000;

    var runs as Codes.Runs;
    var px as Number = 0;

    private var _bitmap as Graphics.BufferedBitmapReference? = null;
    private var _at as Number = 0;

    function initialize(code as Codes.Runs, minPx as Number) {
        Job.initialize();
        runs = code;
        var screen = System.getDeviceSettings();
        var totalW = code.width + 2 * code.quiet;
        var totalH = code.drawnHeight() + 2 * code.quiet;
        for (var p = 16; p >= minPx && px == 0; p--) {
            if (Codes.fits(totalW, totalH, p, screen.screenWidth, screen.screenHeight, Ui.isRound())) {
                px = p;
            }
        }
    }

    // True when the runs go straight to the screen.
    function direct() as Boolean {
        return runs.runs.size() <= DIRECT_RUNS * Jobs.stepsPerTick();
    }

    // True when draw() can run: too large, direct, or the bitmap is painted.
    function ready() as Boolean {
        return px == 0 || direct() || (_bitmap != null && _at >= runs.runs.size());
    }

    function percent() as Number {
        return 100 * _at / runs.runs.size();
    }

    function step(budget as Number) as Boolean {
        if (ready()) {
            return true;
        }
        var ref = _bitmap;
        var bitmap = ref != null ? ref.get() : null;
        if (bitmap == null) {
            // First step, or the system reclaimed the bitmap: start over.
            ref = Graphics.createBufferedBitmap({
                :width => runs.width * px,
                :height => runs.drawnHeight() * px,
                :palette => [Graphics.COLOR_WHITE, Graphics.COLOR_BLACK] as Array<Graphics.ColorValue>
            });
            _bitmap = ref;
            _at = 0;
            bitmap = ref.get();
            if (bitmap == null) {
                px = 0; // no memory for it: shown as too large
                return true;
            }
            var bdc = (bitmap as Graphics.BufferedBitmap).getDc();
            bdc.setColor(Graphics.COLOR_BLACK, Graphics.COLOR_WHITE);
            bdc.clear();
            return false;
        }
        var stop = _at + RUNS_PER_STEP < runs.runs.size() ? _at + RUNS_PER_STEP : runs.runs.size();
        var bdc = (bitmap as Graphics.BufferedBitmap).getDc();
        bdc.setColor(Graphics.COLOR_BLACK, Graphics.COLOR_WHITE);
        paint(bdc, runs, 0, 0, px, _at, stop);
        _at = stop;
        return _at >= runs.runs.size();
    }

    // 1 drawn, 0 too large for the screen, -1 the bitmap was reclaimed by
    // the system (step() again, then draw).
    function draw(dc as Graphics.Dc) as Number {
        if (px == 0) {
            return 0;
        }
        var x0 = (dc.getWidth() - runs.width * px) / 2;
        var y0 = (dc.getHeight() - runs.drawnHeight() * px) / 2;
        if (direct()) {
            dc.setColor(Graphics.COLOR_BLACK, Graphics.COLOR_WHITE);
            paint(dc, runs, x0, y0, px, 0, runs.runs.size());
            return 1;
        }
        var ref = _bitmap;
        if (ref == null || ref.get() == null) {
            _bitmap = null;
            _at = 0;
            return -1;
        }
        dc.drawBitmap(x0, y0, ref);
        return 1;
    }

    // Runs from..to-1 as rectangles at (x0, y0), px pixels per module.
    static function paint(dc as Graphics.Dc, code as Codes.Runs, x0 as Number, y0 as Number, px as Number, from as Number,
            to as Number) as Void {
        var rowPx = code.rowHeight * px;
        var list = code.runs;
        for (var i = from; i < to; i++) {
            var r = list[i];
            dc.fillRectangle(x0 + ((r >> 10) & 0x3FF) * px, y0 + (r >> 20) * rowPx, (r & 0x3FF) * px, rowPx);
        }
    }
}

// Input on a code: a tap asks for full brightness again; BACK closes.
class CodeDelegate extends WatchUi.BehaviorDelegate {

    function initialize() {
        BehaviorDelegate.initialize();
    }

    function onTap(event as WatchUi.ClickEvent) as Boolean {
        boost();
        return true;
    }

    function onSelect() as Boolean {
        boost();
        return true;
    }

    private function boost() as Void {
        AppState.activity();
        var current = WatchUi.getCurrentView()[0];
        if (current instanceof CodeView) {
            current.boostBrightness();
        }
    }

    function onBack() as Boolean {
        var current = WatchUi.getCurrentView()[0];
        if (current instanceof CodeView && current.header.locked && AppState.theVault().session.autoLockMs == 0) {
            AppState.lock();
        }
        WatchUi.popView(WatchUi.SLIDE_RIGHT);
        return true;
    }
}