summaryrefslogtreecommitdiff
path: root/src/ui/documentwidget.c
blob: f8a2e330c68a5ccdb2e78aa1c74537357f9c3025 (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
#include "documentwidget.h"
#include "scrollwidget.h"
#include "inputwidget.h"
#include "paint.h"
#include "command.h"
#include "util.h"
#include "app.h"
#include "../gemini.h"
#include "../gmdocument.h"
#include "../gmrequest.h"
#include "../gmutil.h"

#include <the_Foundation/file.h>
#include <the_Foundation/objectlist.h>
#include <the_Foundation/path.h>
#include <the_Foundation/ptrarray.h>
#include <the_Foundation/regexp.h>
#include <the_Foundation/stringarray.h>

#include <SDL_clipboard.h>
#include <SDL_timer.h>

enum iDocumentState {
    blank_DocumentState,
    fetching_DocumentState,
    receivedPartialResponse_DocumentState,
    layout_DocumentState,
    ready_DocumentState,
};

iDeclareClass(MediaRequest)

struct Impl_MediaRequest {
    iObject object;
    iDocumentWidget *doc;
    iGmLinkId linkId;
    iGmRequest *req;
    iAtomicInt isUpdated;
};

static void updated_MediaRequest_(iAnyObject *obj) {
    iMediaRequest *d = obj;
    int wasUpdated = exchange_Atomic(&d->isUpdated, iTrue);
    if (!wasUpdated) {
        postCommandf_App("media.updated link:%u request:%p", d->linkId, d);
    }
}

static void finished_MediaRequest_(iAnyObject *obj) {
    iMediaRequest *d = obj;
    postCommandf_App("media.finished link:%u request:%p", d->linkId, d);
}

void init_MediaRequest(iMediaRequest *d, iDocumentWidget *doc, iGmLinkId linkId, const iString *url) {
    d->doc    = doc;
    d->linkId = linkId;
    d->req    = new_GmRequest();
    setUrl_GmRequest(d->req, url);
    iConnect(GmRequest, d->req, updated, d, updated_MediaRequest_);
    iConnect(GmRequest, d->req, finished, d, finished_MediaRequest_);
    set_Atomic(&d->isUpdated, iFalse);
    submit_GmRequest(d->req);
}

void deinit_MediaRequest(iMediaRequest *d) {
    iDisconnect(GmRequest, d->req, updated, d, updated_MediaRequest_);
    iDisconnect(GmRequest, d->req, finished, d, finished_MediaRequest_);
    iRelease(d->req);
}

iDefineObjectConstructionArgs(MediaRequest,
                              (iDocumentWidget *doc, iGmLinkId linkId, const iString *url),
                              doc, linkId, url)
iDefineClass(MediaRequest)

struct Impl_DocumentWidget {
    iWidget widget;
    enum iDocumentState state;
    iString *url;
    iString *titleUser;
    iGmRequest *request;
    iAtomicInt isRequestUpdated; /* request has new content, need to parse it */
    iObjectList *media;
    iGmDocument *doc;
    iBool selecting;
    iRangecc selectMark;
    iRangecc foundMark;
    int pageMargin;
    int scrollY;
    iPtrArray visibleLinks;
    const iGmRun *hoverLink;
    iClick click;
    iScrollWidget *scroll;
    iWidget *menu;
    SDL_Cursor *arrowCursor;
    SDL_Cursor *beamCursor;
    SDL_Cursor *handCursor;
};

iDefineObjectConstruction(DocumentWidget)

void init_DocumentWidget(iDocumentWidget *d) {
    iWidget *w = as_Widget(d);
    init_Widget(w);
    setId_Widget(w, "document");
    d->state            = blank_DocumentState;
    d->url              = new_String();
    d->titleUser        = new_String();
    d->request          = NULL;
    d->isRequestUpdated = iFalse;
    d->media            = new_ObjectList();
    d->doc              = new_GmDocument();
    d->selecting        = iFalse;
    d->selectMark       = iNullRange;
    d->foundMark        = iNullRange;
    d->pageMargin       = 5;
    d->scrollY          = 0;
    d->hoverLink        = NULL;
    d->arrowCursor      = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
    d->beamCursor       = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
    d->handCursor       = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
    init_PtrArray(&d->visibleLinks);
    init_Click(&d->click, d, SDL_BUTTON_LEFT);
    addChild_Widget(w, iClob(d->scroll = new_ScrollWidget()));
    d->menu =
        makeMenu_Widget(w,
                        (iMenuItem[]){ { "Back", SDLK_LEFT, KMOD_PRIMARY, "navigate.back" },
                                       { "Forward", SDLK_RIGHT, KMOD_PRIMARY, "navigate.forward" },
                                       { "Reload", 'r', KMOD_PRIMARY, "navigate.reload" },
                                       { "---", 0, 0, NULL },
                                       { "Copy", 'c', KMOD_PRIMARY, "copy" },
                                       { "Copy Link", 0, 0, "document.copylink" } },
                        6);
}

void deinit_DocumentWidget(iDocumentWidget *d) {
    iRelease(d->media);
    iRelease(d->request);
    iRelease(d->doc);
    deinit_PtrArray(&d->visibleLinks);
    delete_String(d->url);
    delete_String(d->titleUser);
    SDL_FreeCursor(d->arrowCursor);
    SDL_FreeCursor(d->beamCursor);
    SDL_FreeCursor(d->handCursor);
}

#if 0
static iString *cleanUrl_(const iString *url) {
    iString *clean = copy_String(url);
    if (startsWith_String(url, "//")) {
        prependCStr_String(clean, "gemini:");
    }
    else if (indexOfCStr_String(url, "://") == iInvalidPos && !startsWithCase_String(url, "gemini:")
             && !startsWithCase_String(url, "data:")) {
        /* Prepend default protocol. */
        prependCStr_String(clean, "gemini://");
    }
    return clean;
}
#endif

static int documentWidth_DocumentWidget_(const iDocumentWidget *d) {
    const iWidget *w = constAs_Widget(d);
    const iRect bounds = bounds_Widget(w);
    return iMini(bounds.size.x - gap_UI * d->pageMargin * 2, fontSize_UI * 40);
}

static iRect documentBounds_DocumentWidget_(const iDocumentWidget *d) {
    const iRect bounds = bounds_Widget(constAs_Widget(d));
    const int   margin = gap_UI * d->pageMargin;
    iRect       rect;
    rect.size.x = documentWidth_DocumentWidget_(d);
    rect.pos.x  = bounds.size.x / 2 - rect.size.x / 2;
    rect.pos.y  = top_Rect(bounds) + margin;
    rect.size.y = height_Rect(bounds) - 2 * margin;
    if (size_GmDocument(d->doc).y < rect.size.y) {
        /* Center vertically if short. */
        int offset = (rect.size.y - size_GmDocument(d->doc).y) / 2;
        rect.pos.y += offset;
        rect.size.y = size_GmDocument(d->doc).y;
    }
    return rect;
}

static iInt2 documentPos_DocumentWidget_(const iDocumentWidget *d, iInt2 pos) {
    return addY_I2(sub_I2(pos, topLeft_Rect(documentBounds_DocumentWidget_(d))), d->scrollY);
}

static void requestUpdated_DocumentWidget_(iAnyObject *obj) {
    iDocumentWidget *d = obj;
    const int wasUpdated = exchange_Atomic(&d->isRequestUpdated, iTrue);
    if (!wasUpdated) {
        postCommand_Widget(obj, "document.request.updated request:%p", d->request);
    }
}

static void requestFinished_DocumentWidget_(iAnyObject *obj) {
    iDocumentWidget *d = obj;
    postCommand_Widget(obj, "document.request.finished request:%p", d->request);
}

static iRangei visibleRange_DocumentWidget_(const iDocumentWidget *d) {
    const int margin = gap_UI * d->pageMargin;
    return (iRangei){ d->scrollY - margin,
                      d->scrollY + height_Rect(bounds_Widget(constAs_Widget(d))) - margin };
}

static void addVisibleLink_DocumentWidget_(void *context, const iGmRun *run) {
    iDocumentWidget *d = context;
    if (run->linkId && linkFlags_GmDocument(d->doc, run->linkId) & supportedProtocol_GmLinkFlag) {
        pushBack_PtrArray(&d->visibleLinks, run);
    }
}

static int scrollMax_DocumentWidget_(const iDocumentWidget *d) {
    return size_GmDocument(d->doc).y - height_Rect(bounds_Widget(constAs_Widget(d))) +
           2 * d->pageMargin * gap_UI;
}

static void updateHover_DocumentWidget_(iDocumentWidget *d, iInt2 mouse) {
    const iRect docBounds      = documentBounds_DocumentWidget_(d);
    const iGmRun *oldHoverLink = d->hoverLink;
    d->hoverLink               = NULL;
    const iInt2 hoverPos = addY_I2(sub_I2(mouse, topLeft_Rect(docBounds)), d->scrollY);
    if (d->state == ready_DocumentState || d->state == receivedPartialResponse_DocumentState) {
        iConstForEach(PtrArray, i, &d->visibleLinks) {
            const iGmRun *run = i.ptr;
            if (contains_Rect(run->bounds, hoverPos)) {
                d->hoverLink = run;
                break;
            }
        }
    }
    if (d->hoverLink != oldHoverLink) {
        refresh_Widget(as_Widget(d));
    }
    if (!contains_Widget(constAs_Widget(d), mouse) ||
        contains_Widget(constAs_Widget(d->scroll), mouse)) {
        SDL_SetCursor(d->arrowCursor);
    }
    else {
        SDL_SetCursor(d->hoverLink ? d->handCursor : d->beamCursor);
    }
}

static void updateVisible_DocumentWidget_(iDocumentWidget *d) {
    const iRangei visRange = visibleRange_DocumentWidget_(d);
    const iRect   bounds   = bounds_Widget(as_Widget(d));
    setRange_ScrollWidget(d->scroll, (iRangei){ 0, scrollMax_DocumentWidget_(d) });
    const int docSize = size_GmDocument(d->doc).y;
    setThumb_ScrollWidget(d->scroll,
                          d->scrollY,
                          docSize > 0 ? height_Rect(bounds) * size_Range(&visRange) / docSize : 0);
    clear_PtrArray(&d->visibleLinks);
    render_GmDocument(d->doc, visRange, addVisibleLink_DocumentWidget_, d);
    updateHover_DocumentWidget_(d, mouseCoord_Window(get_Window()));
}

static void updateWindowTitle_DocumentWidget_(const iDocumentWidget *d) {
    iStringArray *title = iClob(new_StringArray());
    if (!isEmpty_String(title_GmDocument(d->doc))) {
        pushBack_StringArray(title, title_GmDocument(d->doc));
    }
    if (!isEmpty_String(d->titleUser)) {
        pushBack_StringArray(title, d->titleUser);
    }
    else {
        iUrl parts;
        init_Url(&parts, d->url);
        if (!isEmpty_Range(&parts.host)) {
            pushBackRange_StringArray(title, parts.host);
        }
    }
    if (isEmpty_StringArray(title)) {
        pushBackCStr_StringArray(title, "Lagrange");
    }
    setTitle_Window(get_Window(), collect_String(joinCStr_StringArray(title, " \u2013 ")));
}

static void setSource_DocumentWidget_(iDocumentWidget *d, const iString *source) {
    setUrl_GmDocument(d->doc, d->url);
    setSource_GmDocument(d->doc, source, documentWidth_DocumentWidget_(d));
    d->foundMark  = iNullRange;
    d->selectMark = iNullRange;
    d->hoverLink  = NULL;
    updateWindowTitle_DocumentWidget_(d);
    updateVisible_DocumentWidget_(d);
    refresh_Widget(as_Widget(d));
}

static void showErrorPage_DocumentWidget_(iDocumentWidget *d, enum iGmStatusCode code) {
    iString *src = collectNew_String();
    const iGmError *msg = get_GmError(code);
    format_String(src,
                  "# %lc %s\n%s",
                  msg->icon ? msg->icon : 0x2327, /* X in a box */
                  msg->title,
                  msg->info);
    switch (code) {
        case failedToOpenFile_GmStatusCode:
        case certificateNotValid_GmStatusCode:
            appendFormat_String(src, "\n\n%s", cstr_String(meta_GmRequest(d->request)));
            break;
        case unsupportedMimeType_GmStatusCode:
            appendFormat_String(src, "\n```\n%s\n```\n", cstr_String(meta_GmRequest(d->request)));
            break;
        case slowDown_GmStatusCode:
            appendFormat_String(src, "\n\nWait %s seconds before your next request.",
                                cstr_String(meta_GmRequest(d->request)));
            break;
        default:
            break;
    }
    setSource_DocumentWidget_(d, src);
}

static void updateSource_DocumentWidget_(iDocumentWidget *d) {
    /* TODO: Do this in the background. However, that requires a text metrics calculator
       that does not try to cache the glyph bitmaps. */
    const enum iGmStatusCode statusCode = status_GmRequest(d->request);
    if (statusCode != input_GmStatusCode &&
        statusCode != sensitiveInput_GmStatusCode) {
        iString str;
        initBlock_String(&str, body_GmRequest(d->request));
        if (statusCode == success_GmStatusCode) {
            /* Check the MIME type. */
            const iString *mime = meta_GmRequest(d->request);
            if (startsWith_String(mime, "text/plain")) {
                setFormat_GmDocument(d->doc, plainText_GmDocumentFormat);
            }
            else if (startsWith_String(mime, "text/gemini")) {
                setFormat_GmDocument(d->doc, gemini_GmDocumentFormat);
            }
            else if (startsWith_String(mime, "image/")) {
                if (isFinished_GmRequest(d->request)) {
                    /* Make a simple document with an image. */
                    const char *imageTitle = "Image";
                    iUrl parts;
                    init_Url(&parts, url_GmRequest(d->request));
                    if (!isEmpty_Range(&parts.path)) {
                        imageTitle = baseName_Path(collect_String(newRange_String(parts.path))).start;
                    }
                    format_String(
                        &str, "=> %s %s\n", cstr_String(url_GmRequest(d->request)), imageTitle);
                    setImage_GmDocument(d->doc, 1, mime, body_GmRequest(d->request));
                }
                else {
                    clear_String(&str);
                }
            }
            else {
                showErrorPage_DocumentWidget_(d, unsupportedMimeType_GmStatusCode);
                deinit_String(&str);
                return;
            }
        }
        setSource_DocumentWidget_(d, &str);
        deinit_String(&str);
    }
}

static void fetch_DocumentWidget_(iDocumentWidget *d) {
    /* Forget the previous request. */
    if (d->request) {
        iRelease(d->request);
        d->request = NULL;
    }
    postCommandf_App("document.request.started url:%s", cstr_String(d->url));
    clear_ObjectList(d->media);
    d->state = fetching_DocumentState;
    set_Atomic(&d->isRequestUpdated, iFalse);
    d->request = new_GmRequest();
    setUrl_GmRequest(d->request, d->url);
    iConnect(GmRequest, d->request, updated, d, requestUpdated_DocumentWidget_);
    iConnect(GmRequest, d->request, finished, d, requestFinished_DocumentWidget_);
    submit_GmRequest(d->request);
}

void setUrl_DocumentWidget(iDocumentWidget *d, const iString *url) {
    if (cmpStringSc_String(d->url, url, &iCaseInsensitive)) {
        set_String(d->url, url);
        fetch_DocumentWidget_(d);
    }
    /* See if there a username in the URL. */ {
        clear_String(d->titleUser);
        iRegExp *userPats[2] = { new_RegExp("~([^/?]+)", 0),
                                 new_RegExp("/users/([^/?]+)", caseInsensitive_RegExpOption) };
        iRegExpMatch m;
        iForIndices(i, userPats) {
            if (matchString_RegExp(userPats[i], d->url, &m)) {
                setRange_String(d->titleUser, capturedRange_RegExpMatch(&m, 1));
            }
            iRelease(userPats[i]);
        }
    }
}

iBool isRequestOngoing_DocumentWidget(const iDocumentWidget *d) {
    return d->state == fetching_DocumentState || d->state == receivedPartialResponse_DocumentState;
}

static void scroll_DocumentWidget_(iDocumentWidget *d, int offset) {
    d->scrollY += offset;
    if (d->scrollY < 0) {
        d->scrollY = 0;
    }
    const int scrollMax = scrollMax_DocumentWidget_(d);
    if (scrollMax > 0) {
        d->scrollY = iMin(d->scrollY, scrollMax);
    }
    else {
        d->scrollY = 0;
    }
    updateVisible_DocumentWidget_(d);
    refresh_Widget(as_Widget(d));
}

static void scrollTo_DocumentWidget_(iDocumentWidget *d, int documentY) {
    d->scrollY = documentY - documentBounds_DocumentWidget_(d).size.y / 2;
    scroll_DocumentWidget_(d, 0); /* clamp it */
}

static void checkResponseCode_DocumentWidget_(iDocumentWidget *d) {
    if (!d->request) {
        return;
    }
    enum iGmStatusCode statusCode = status_GmRequest(d->request);
    if (d->state == fetching_DocumentState) {
        d->state = receivedPartialResponse_DocumentState;
        switch (statusCode / 10) {
            case 1: /* input required */ {
                iUrl parts;
                init_Url(&parts, d->url);
                printf("%s\n", cstr_String(meta_GmRequest(d->request)));
                iWidget *dlg = makeValueInput_Widget(
                    as_Widget(d),
                    NULL,
                    format_CStr(cyan_ColorEscape "%s",
                                cstr_String(collect_String(newRange_String(parts.host)))),
                    isEmpty_String(meta_GmRequest(d->request))
                        ? format_CStr("Please enter input for %s:",
                                      cstr_String(collect_String(newRange_String(parts.path))))
                        : cstr_String(meta_GmRequest(d->request)),
                    orange_ColorEscape "Send \u21d2",
                    "document.input.submit");
                setSensitive_InputWidget(findChild_Widget(dlg, "input"),
                                         statusCode == sensitiveInput_GmStatusCode);
                break;
            }
            case 2: /* success */
                d->scrollY = 0;
                reset_GmDocument(d->doc); /* new content incoming */
                updateSource_DocumentWidget_(d);
                break;
            case 3: /* redirect */
                if (isEmpty_String(meta_GmRequest(d->request))) {
                    showErrorPage_DocumentWidget_(d, invalidRedirect_GmStatusCode);
                }
                else {
                    postCommandf_App(
                        "open redirect:1 url:%s",
                        cstr_String(absoluteUrl_String(d->url, meta_GmRequest(d->request))));
                    iReleasePtr(&d->request);
                }
                break;
            default:
                if (isDefined_GmError(statusCode)) {
                    showErrorPage_DocumentWidget_(d, statusCode);
                }
                else if (statusCode / 10 == 4) {
                    showErrorPage_DocumentWidget_(d, temporaryFailure_GmStatusCode);
                }
                else if (statusCode / 10 == 5) {
                    showErrorPage_DocumentWidget_(d, permanentFailure_GmStatusCode);
                }
                break;
        }
    }
    else if (d->state == receivedPartialResponse_DocumentState) {
        switch (statusCode) {
            case success_GmStatusCode:
                /* More content available. */
                updateSource_DocumentWidget_(d);
                break;
            default:
                break;
        }
    }
}

static const char *sourceLoc_DocumentWidget_(const iDocumentWidget *d, iInt2 pos) {
    return findLoc_GmDocument(d->doc, documentPos_DocumentWidget_(d, pos));
}

static void removeMediaRequest_DocumentWidget_(iDocumentWidget *d, iGmLinkId linkId) {
    iForEach(ObjectList, i, d->media) {
        iMediaRequest *req = (iMediaRequest *) i.object;
        if (req->linkId == linkId) {
            remove_ObjectListIterator(&i);
            break;
        }
    }
}

static iMediaRequest *findMediaRequest_DocumentWidget_(const iDocumentWidget *d, iGmLinkId linkId) {
    iConstForEach(ObjectList, i, d->media) {
        const iMediaRequest *req = (const iMediaRequest *) i.object;
        if (req->linkId == linkId) {
            return iConstCast(iMediaRequest *, req);
        }
    }
    return NULL;
}

static iBool requestMedia_DocumentWidget_(iDocumentWidget *d, iGmLinkId linkId) {
    if (!findMediaRequest_DocumentWidget_(d, linkId)) {
        pushBack_ObjectList(
            d->media,
            iClob(new_MediaRequest(
                d, linkId, absoluteUrl_String(d->url, linkUrl_GmDocument(d->doc, linkId)))));
        return iTrue;
    }
    return iFalse;
}

static iBool handleMediaEvent_DocumentWidget_(iDocumentWidget *d, const char *cmd) {
    iMediaRequest *req = pointerLabel_Command(cmd, "request");
    if (!req || req->doc != d) {
        return iFalse; /* not our request */
    }
    if (equal_Command(cmd, "media.updated")) {
        /* TODO: Show a progress indicator */
        return iTrue;
    }
    else if (equal_Command(cmd, "media.finished")) {
        const enum iGmStatusCode code = status_GmRequest(req->req);
        /* Give the media to the document for presentation. */
        if (code == success_GmStatusCode) {
            printf("media finished: %s\n  size: %zu\n  type: %s\n",
                   cstr_String(url_GmRequest(req->req)),
                   size_Block(body_GmRequest(req->req)),
                   cstr_String(meta_GmRequest(req->req)));
            if (startsWith_String(meta_GmRequest(req->req), "image/")) {
                setImage_GmDocument(d->doc, req->linkId, meta_GmRequest(req->req),
                                    body_GmRequest(req->req));
                updateVisible_DocumentWidget_(d);
                refresh_Widget(as_Widget(d));
            }
        }
        else {
            const iGmError *err = get_GmError(code);
            makeMessage_Widget(format_CStr(orange_ColorEscape "%s", err->title), err->info);
            removeMediaRequest_DocumentWidget_(d, req->linkId);
        }
        return iTrue;
    }
    return iFalse;
}

static iBool processEvent_DocumentWidget_(iDocumentWidget *d, const SDL_Event *ev) {
    iWidget *w = as_Widget(d);
    if (isResize_UserEvent(ev)) {
        setWidth_GmDocument(d->doc, documentWidth_DocumentWidget_(d));
        scroll_DocumentWidget_(d, 0);
        updateVisible_DocumentWidget_(d);
        refresh_Widget(w);
    }
    else if (isCommand_UserEvent(ev, "copy")) {
        if (d->selectMark.start) {
            iRangecc mark = d->selectMark;
            if (mark.start > mark.end) {
                iSwap(const char *, mark.start, mark.end);
            }
            iString *copied = newRange_String(mark);
            SDL_SetClipboardText(cstr_String(copied));
            delete_String(copied);
            return iTrue;
        }
    }
    else if (isCommand_Widget(w, ev, "document.copylink")) {
        if (d->hoverLink) {
            SDL_SetClipboardText(cstr_String(
                absoluteUrl_String(d->url, linkUrl_GmDocument(d->doc, d->hoverLink->linkId))));
        }
        else {
            SDL_SetClipboardText(cstr_String(d->url));
        }
        return iTrue;
    }
    else if (isCommand_UserEvent(ev, "document.input.submit")) {
        iString *value = collect_String(suffix_Command(command_UserEvent(ev), "value"));
        urlEncode_String(value);
        iString *url = collect_String(copy_String(d->url));
        const size_t qPos = indexOfCStr_String(url, "?");
        if (qPos != iInvalidPos) {
            remove_Block(&url->chars, qPos, iInvalidSize);
        }
        appendCStr_String(url, "?");
        append_String(url, value);
        postCommandf_App("open url:%s", cstr_String(url));
        return iTrue;
    }
    else if (isCommand_UserEvent(ev, "valueinput.cancelled") &&
             cmp_String(string_Command(command_UserEvent(ev), "id"), "document.input.submit") ==
                 0) {
        postCommand_App("navigate.back");
        return iTrue;
    }
    else if (isCommand_Widget(w, ev, "document.request.updated") &&
             pointerLabel_Command(command_UserEvent(ev), "request") == d->request) {
        checkResponseCode_DocumentWidget_(d);
//        updateSource_DocumentWidget_(d);
        return iFalse;
    }
    else if (isCommand_Widget(w, ev, "document.request.finished") &&
             pointerLabel_Command(command_UserEvent(ev), "request") == d->request) {
//        updateSource_DocumentWidget_(d);
        checkResponseCode_DocumentWidget_(d);
        d->state = ready_DocumentState;
        iReleasePtr(&d->request);
        postCommandf_App("document.changed url:%s", cstr_String(d->url));
        return iFalse;
    }
    else if (isCommand_UserEvent(ev, "document.request.cancelled")) {
        postCommand_App("navigate.back");
        return iFalse;
    }
    else if (isCommand_UserEvent(ev, "document.stop")) {
        if (d->request) {
            postCommandf_App("document.request.cancelled url:%s", cstr_String(d->url));
            iReleasePtr(&d->request);
            d->state = ready_DocumentState;
        }
        return iTrue;
    }
    else if (isCommand_UserEvent(ev, "media.updated") || isCommand_UserEvent(ev, "media.finished")) {
        return handleMediaEvent_DocumentWidget_(d, command_UserEvent(ev));
    }
    else if (isCommand_UserEvent(ev, "document.reload")) {
        fetch_DocumentWidget_(d);
        return iTrue;
    }
    else if (isCommand_Widget(w, ev, "scroll.moved")) {
        d->scrollY = arg_Command(command_UserEvent(ev));
        updateVisible_DocumentWidget_(d);
        return iTrue;
    }
    else if (isCommand_Widget(w, ev, "scroll.page")) {
        scroll_DocumentWidget_(
            d, arg_Command(command_UserEvent(ev)) * height_Rect(documentBounds_DocumentWidget_(d)));
        return iTrue;
    }
    else if (isCommand_UserEvent(ev, "find.next") || isCommand_UserEvent(ev, "find.prev")) {
        const int dir = isCommand_UserEvent(ev, "find.next") ? +1 : -1;
        iRangecc (*finder)(const iGmDocument *, const iString *, const char *) =
            dir > 0 ? findText_GmDocument : findTextBefore_GmDocument;
        iInputWidget *find = findWidget_App("find.input");
        if (isEmpty_String(text_InputWidget(find))) {
            d->foundMark = iNullRange;
        }
        else {
            const iBool wrap = d->foundMark.start != NULL;
            d->foundMark     = finder(d->doc, text_InputWidget(find), dir > 0 ? d->foundMark.end
                                                                              : d->foundMark.start);
            if (!d->foundMark.start && wrap) {
                /* Wrap around. */
                d->foundMark = finder(d->doc, text_InputWidget(find), NULL);
            }
            if (d->foundMark.start) {
                const iGmRun *found;
                if ((found = findRunAtLoc_GmDocument(d->doc, d->foundMark.start)) != NULL) {
                    scrollTo_DocumentWidget_(d, mid_Rect(found->bounds).y);
                }
            }
        }
        refresh_Widget(w);
        return iTrue;
    }   
    else if (isCommand_UserEvent(ev, "find.clearmark")) {
        if (d->foundMark.start) {
            d->foundMark = iNullRange;
            refresh_Widget(w);
        }
        return iTrue;
    }
    if (ev->type == SDL_KEYDOWN) {
        const int mods = keyMods_Sym(ev->key.keysym.mod);
        const int key = ev->key.keysym.sym;
        switch (key) {
            case SDLK_HOME:
                d->scrollY = 0;
                updateVisible_DocumentWidget_(d);
                refresh_Widget(w);
                return iTrue;
            case SDLK_END:
                d->scrollY = scrollMax_DocumentWidget_(d);
                updateVisible_DocumentWidget_(d);
                refresh_Widget(w);
                return iTrue;
            case SDLK_UP:
            case SDLK_DOWN:
                if (mods == 0) {
                    scroll_DocumentWidget_(d, 2 * lineHeight_Text(paragraph_FontId) *
                                                  (key == SDLK_UP ? -1 : 1));
                    return iTrue;
                }
                break;
            case SDLK_PAGEUP:
            case SDLK_PAGEDOWN:
            case ' ':
                postCommand_Widget(w, "scroll.page arg:%d", key == SDLK_PAGEUP ? -1 : +1);
                return iTrue;
            case '0': {
                extern int enableHalfPixelGlyphs_Text;
                enableHalfPixelGlyphs_Text = !enableHalfPixelGlyphs_Text;
                refresh_Widget(w);
                printf("halfpixel: %d\n", enableHalfPixelGlyphs_Text);
                fflush(stdout);
                break;
            }
        }
    }
    else if (ev->type == SDL_MOUSEWHEEL) {
        scroll_DocumentWidget_(d, -3 * ev->wheel.y * lineHeight_Text(default_FontId));
        return iTrue;
    }
    else if (ev->type == SDL_MOUSEMOTION) {
        if (isVisible_Widget(d->menu)) {
            SDL_SetCursor(d->arrowCursor);
        }
        else {
            updateHover_DocumentWidget_(d, init_I2(ev->motion.x, ev->motion.y));
        }
    }
    if (ev->type == SDL_MOUSEBUTTONDOWN) {
        if (ev->button.button == SDL_BUTTON_X1) {
            postCommand_App("navigate.back");
            return iTrue;
        }
        if (ev->button.button == SDL_BUTTON_X2) {
            postCommand_App("navigate.forward");
            return iTrue;
        }
    }
    processContextMenuEvent_Widget(d->menu, ev);
    switch (processEvent_Click(&d->click, ev)) {
        case started_ClickResult:
            d->selecting = iFalse;
            return iTrue;
        case drag_ClickResult: {
            /* Begin selecting a range of text. */
            if (!d->selecting) {
                d->selecting = iTrue;
                d->selectMark.start = d->selectMark.end =
                    sourceLoc_DocumentWidget_(d, d->click.startPos);
                refresh_Widget(w);
            }
            const char *loc = sourceLoc_DocumentWidget_(d, pos_Click(&d->click));
            if (!d->selectMark.start) {
                d->selectMark.start = d->selectMark.end = loc;
            }
            else if (loc) {
                d->selectMark.end = loc;
            }
            refresh_Widget(w);
            return iTrue;
        }
        case finished_ClickResult:
            if (!isMoved_Click(&d->click)) {
                if (d->hoverLink) {
                    const iGmLinkId linkId = d->hoverLink->linkId;
                    iAssert(linkId);
                    /* Media links are opened inline by default. */
                    if (isMediaLink_GmDocument(d->doc, linkId)) {
                        if (!requestMedia_DocumentWidget_(d, linkId)) {
                            if (linkFlags_GmDocument(d->doc, linkId) & content_GmLinkFlag) {
                                setImage_GmDocument(d->doc, linkId, NULL, NULL);
                                d->hoverLink = NULL;
                                updateVisible_DocumentWidget_(d);
                                refresh_Widget(w);
                                return iTrue;
                            }
                            else {
                                /* Show the existing content again if we have it. */
                                iMediaRequest *req = findMediaRequest_DocumentWidget_(d, linkId);
                                if (req) {
                                    setImage_GmDocument(d->doc, linkId, meta_GmRequest(req->req),
                                                        body_GmRequest(req->req));
                                    updateVisible_DocumentWidget_(d);
                                    refresh_Widget(w);
                                    return iTrue;
                                }
                            }
                        }
                        refresh_Widget(w);
                    }
                    else {
                        postCommandf_App("open url:%s",
                                         cstr_String(absoluteUrl_String(
                                             d->url, linkUrl_GmDocument(d->doc, linkId))));
                    }
                }
                if (d->selectMark.start) {
                    d->selectMark = iNullRange;
                    refresh_Widget(w);
                }
            }
            return iTrue;
        case double_ClickResult:
        case aborted_ClickResult:
            return iTrue;
        default:
            break;
    }
    return processEvent_Widget(w, ev);
}

iDeclareType(DrawContext)

struct Impl_DrawContext {
    const iDocumentWidget *widget;
    iRect widgetBounds;
    iRect bounds; /* document area */
    iPaint paint;
    iBool inSelectMark;
    iBool inFoundMark;
};

static void fillRange_DrawContext_(iDrawContext *d, const iGmRun *run, enum iColorId color,
                                   iRangecc mark, iBool *isInside) {
    if (mark.start > mark.end) {
        /* Selection may be done in either direction. */
        iSwap(const char *, mark.start, mark.end);
    }
    if ((!*isInside && contains_Range(&run->text, mark.start)) || *isInside) {
        int x = 0;
        if (!*isInside) {
            x = advanceRange_Text(run->font, (iRangecc){ run->text.start, mark.start }).x;
        }
        int w = width_Rect(run->bounds) - x;
        if (contains_Range(&run->text, mark.end) || run->text.end == mark.end) {
            w = advanceRange_Text(run->font,
                                  !*isInside ? mark : (iRangecc){ run->text.start, mark.end }).x;
            *isInside = iFalse;
        }
        else {
            *isInside = iTrue; /* at least until the next run */
        }
        if (w > width_Rect(run->visBounds) - x) {
            w = width_Rect(run->visBounds) - x;
        }
        const iInt2 visPos = add_I2(run->bounds.pos, addY_I2(d->bounds.pos, -d->widget->scrollY));
        fillRect_Paint(&d->paint, (iRect){ addX_I2(visPos, x),
                                           init_I2(w, height_Rect(run->bounds)) }, color);
    }
}

static void drawRun_DrawContext_(void *context, const iGmRun *run) {
    iDrawContext *d      = context;
    const iInt2   origin = addY_I2(d->bounds.pos, -d->widget->scrollY);
    if (run->imageId) {
        SDL_Texture *tex = imageTexture_GmDocument(d->widget->doc, run->imageId);
        if (tex) {
            const iRect dst = moved_Rect(run->visBounds, origin);
            SDL_RenderCopy(d->paint.dst->render, tex, NULL,
                           &(SDL_Rect){ dst.pos.x, dst.pos.y, dst.size.x, dst.size.y });
        }
        return;
    }
    iString text;
    /* TODO: making a copy is unnecessary; the text routines should accept Rangecc */
    initRange_String(&text, run->text);
    enum iColorId      fg  = run->color;
    const iGmDocument *doc = d->widget->doc;
    const iBool        isHover =
        run->linkId != 0 && d->widget->hoverLink && run->linkId == d->widget->hoverLink->linkId &&
        !isEmpty_Rect(run->bounds);
    const iInt2 visPos = add_I2(run->visBounds.pos, origin);
    /* Text markers. */
    fillRange_DrawContext_(d, run, teal_ColorId, d->widget->foundMark, &d->inFoundMark);
    fillRange_DrawContext_(d, run, brown_ColorId, d->widget->selectMark, &d->inSelectMark);
    if (run->linkId && !isEmpty_Rect(run->bounds)) {
//        const int flags = linkFlags_GmDocument(doc, run->linkId);
        fg = /*flags & visited_GmLinkFlag ? gray88_ColorId :*/ white_ColorId;
        if (isHover || linkFlags_GmDocument(doc, run->linkId) & content_GmLinkFlag) {
            fg = linkColor_GmDocument(doc, run->linkId);
        }
    }
    drawString_Text(run->font, visPos, fg, &text);
    deinit_String(&text);
    /* Presentation of links. */
    if (run->linkId) {
        /* TODO: Show status of an ongoing media request. */
        const int flags = linkFlags_GmDocument(doc, run->linkId);
        const iRect linkRect = moved_Rect(run->visBounds, origin);
        iMediaRequest *mr = NULL;
        if (flags & content_GmLinkFlag) {
            fg = linkColor_GmDocument(doc, run->linkId);
            if (!isEmpty_Rect(run->bounds)) {
                iGmImageInfo info;
                imageInfo_GmDocument(doc, linkImage_GmDocument(doc, run->linkId), &info);
                iString text;
                init_String(&text);
                format_String(&text, "%s \u2014 %d x %d \u2014 %.1fMB",
                              info.mime, info.size.x, info.size.y, info.numBytes / 1.0e6f);
                if (findMediaRequest_DocumentWidget_(d->widget, run->linkId)) {
                    appendFormat_String(
                        &text, "  %s\U0001f7a8", isHover ? white_ColorEscape : "");
                }
                drawAlign_Text(default_FontId,
                               add_I2(topRight_Rect(run->bounds), origin),
                               fg,
                               right_Alignment,
                               "%s", cstr_String(&text));
                deinit_String(&text);
            }
        }
        else if (run->flags & endOfLine_GmRunFlag &&
                 (mr = findMediaRequest_DocumentWidget_(d->widget, run->linkId)) != NULL) {
            if (!isFinished_GmRequest(mr->req)) {
                draw_Text(default_FontId,
                          topRight_Rect(linkRect),
                          linkColor_GmDocument(doc, run->linkId),
                          " \u2014 Fetching\u2026");
            }
        }
        else if (isHover) {
            const iGmLinkId linkId = d->widget->hoverLink->linkId;
            const iString * url    = linkUrl_GmDocument(doc, linkId);
            const int       flags  = linkFlags_GmDocument(doc, linkId);
            iUrl parts;
            init_Url(&parts, url);
            const iString *host = collect_String(newRange_String(parts.host));
            fg = linkColor_GmDocument(doc, linkId);
            const iBool showHost  = (!isEmpty_String(host) && flags & userFriendly_GmLinkFlag);
            const iBool showImage = (flags & imageFileExtension_GmLinkFlag) != 0;
            const iBool showAudio = (flags & audioFileExtension_GmLinkFlag) != 0;
            iString str;
            init_String(&str);
            if (run->flags & endOfLine_GmRunFlag &&
                (flags & (imageFileExtension_GmLinkFlag | audioFileExtension_GmLinkFlag) ||
                 showHost)) {
                format_String(&str, " \u2014%s%s%s\r%c%s",
                              showHost ? " " : "",
                              showHost ? cstr_String(host) : "",
                              showHost && (showImage || showAudio) ? " \u2014" : "",
                              showImage || showAudio ? '0' + fg : ('0' + fg - 1),
                              showImage ? " View Image \U0001f5bc"
                                        : showAudio ? " Play Audio \U0001f3b5" : "");
            }
            if (run->flags & endOfLine_GmRunFlag && flags & visited_GmLinkFlag) {
                iDate date;
                init_Date(&date, linkTime_GmDocument(doc, run->linkId));
                appendFormat_String(&str,
                                    " \u2014 %s%s",
                                    escape_Color(fg),
                                    cstr_String(collect_String(format_Date(&date, "%b %d"))));
            }
            if (!isEmpty_String(&str)) {
                const iInt2 textSize = measure_Text(default_FontId, cstr_String(&str));
                int tx = topRight_Rect(linkRect).x;
                const char *msg = cstr_String(&str);
                if (tx + textSize.x > right_Rect(d->widgetBounds)) {
                    tx = right_Rect(d->widgetBounds) - textSize.x;
                    fillRect_Paint(&d->paint, (iRect){ init_I2(tx, top_Rect(linkRect)), textSize },
                                   black_ColorId);
                    msg += 4; /* skip the space and dash */
                    tx += measure_Text(default_FontId, " \u2014").x / 2;
                }
                drawAlign_Text(default_FontId,
                               init_I2(tx, top_Rect(linkRect)),
                               fg - 1,
                               left_Alignment,
                               "%s",
                               msg);
                deinit_String(&str);
            }
        }
    }

//    drawRect_Paint(&d->paint, (iRect){ visPos, run->bounds.size }, green_ColorId);
//    drawRect_Paint(&d->paint, (iRect){ visPos, run->visBounds.size }, red_ColorId);
}

static void draw_DocumentWidget_(const iDocumentWidget *d) {
    const iWidget *w      = constAs_Widget(d);
    const iRect    bounds = bounds_Widget(w);
    draw_Widget(w);
    iDrawContext ctx = {
        .widget = d,
        .widgetBounds = /* omit scrollbar width */
            adjusted_Rect(bounds, zero_I2(), init_I2(-constAs_Widget(d->scroll)->rect.size.x, 0)),
        .bounds = documentBounds_DocumentWidget_(d)
    };
    init_Paint(&ctx.paint);
    fillRect_Paint(&ctx.paint, bounds, gray15_ColorId);
    setClip_Paint(&ctx.paint, bounds);
    render_GmDocument(d->doc, visibleRange_DocumentWidget_(d), drawRun_DrawContext_, &ctx);
    clearClip_Paint(&ctx.paint);
    draw_Widget(w);
}

iBeginDefineSubclass(DocumentWidget, Widget)
    .processEvent = (iAny *) processEvent_DocumentWidget_,
    .draw         = (iAny *) draw_DocumentWidget_,
iEndDefineSubclass(DocumentWidget)