summaryrefslogtreecommitdiff
path: root/src/ui/lookupwidget.c
blob: 7d6052e291b1a7b2474ed939d6a2c4cb595761e2 (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
/* Copyright 2020 Jaakko Keränen <jaakko.keranen@iki.fi>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "lookupwidget.h"

#include "app.h"
#include "bookmarks.h"
#include "command.h"
#include "documentwidget.h"
#include "feeds.h"
#include "gmcerts.h"
#include "gmutil.h"
#include "history.h"
#include "inputwidget.h"
#include "listwidget.h"
#include "lookup.h"
#include "util.h"
#include "visited.h"

#include <the_Foundation/mutex.h>
#include <the_Foundation/thread.h>
#include <the_Foundation/regexp.h>

iDeclareType(LookupJob)

struct Impl_LookupJob {
    iRegExp *term;
    iTime now;
    iObjectList *docs;
    iPtrArray results;
};

static void init_LookupJob(iLookupJob *d) {
    d->term = NULL;
    initCurrent_Time(&d->now);
    d->docs = NULL;
    init_PtrArray(&d->results);
}

static void deinit_LookupJob(iLookupJob *d) {
    iForEach(PtrArray, i, &d->results) {
        delete_LookupResult(i.ptr);
    }
    deinit_PtrArray(&d->results);
    iRelease(d->docs);
    iRelease(d->term);
}

iDefineTypeConstruction(LookupJob)

/*----------------------------------------------------------------------------------------------*/

iDeclareType(LookupItem)
typedef iListItemClass iLookupItemClass;

struct Impl_LookupItem {
    iListItem listItem;
    iLookupResult *result;
    int font;
    int fg;
    iString icon;
    iString text;
    iString command;
};

static void init_LookupItem(iLookupItem *d, const iLookupResult *res) {
    init_ListItem(&d->listItem);
    d->result = res ? copy_LookupResult(res) : NULL;
    d->font = uiContent_FontId;
    d->fg = uiText_ColorId;
    init_String(&d->icon);
    if (res && res->icon) {
        appendChar_String(&d->icon, res->icon);
    }
    init_String(&d->text);
    init_String(&d->command);
}

static void deinit_LookupItem(iLookupItem *d) {
    deinit_String(&d->command);
    deinit_String(&d->text);
    deinit_String(&d->icon);
    delete_LookupResult(d->result);
}

static void draw_LookupItem_(iLookupItem *d, iPaint *p, iRect rect, const iListWidget *list) {
    const iBool isPressing = isMouseDown_ListWidget(list);
    const iBool isHover    = isHover_Widget(list) && constHoverItem_ListWidget(list) == d;
    const iBool isCursor   = d->listItem.isSelected;
    if (isHover || isCursor) {
        fillRect_Paint(p,
                       rect,
                       isPressing || isCursor ? uiBackgroundPressed_ColorId
                                              : uiBackgroundFramelessHover_ColorId);
    }
    int fg = isHover || isCursor
                 ? permanent_ColorId | (isPressing || isCursor ? uiTextPressed_ColorId
                                                               : uiTextFramelessHover_ColorId)
                 : d->fg;
    const iInt2 size = measureRange_Text(d->font, range_String(&d->text));
    iInt2       pos  = init_I2(left_Rect(rect) + 3 * gap_UI, mid_Rect(rect).y - size.y / 2);
    if (d->listItem.isSeparator) {
        pos.y = bottom_Rect(rect) - lineHeight_Text(d->font);
    }
    if (!isEmpty_String(&d->icon)) {
        const iRect iconRect = { pos, init_I2(gap_UI * 5, height_Rect(rect)) };
        const iInt2 iconSize = measureRange_Text(d->font, range_String(&d->icon));
        drawRange_Text(d->font,
                       addX_I2(pos, width_Rect(iconRect) / 2 - iconSize.x / 2),
                       fg,
                       range_String(&d->icon));
        pos.x += width_Rect(iconRect) + gap_UI;
    }
    drawRange_Text(d->font, pos, fg, range_String(&d->text));
}

iBeginDefineSubclass(LookupItem, ListItem)
    .draw = (iAny *) draw_LookupItem_,
iEndDefineSubclass(LookupItem)

iDefineObjectConstructionArgs(LookupItem, (const iLookupResult *res), res)

/*----------------------------------------------------------------------------------------------*/

struct Impl_LookupWidget {
    iWidget      widget;
    iListWidget *list;
    size_t       cursor;
    iThread *    work;
    iCondition   jobAvailable; /* wakes up the work thread */
    iMutex *     mtx;
    iString      pendingTerm;
    iObjectList *pendingDocs;
    iLookupJob * finishedJob;
};

static float scoreMatch_(const iRegExp *pattern, iRangecc text) {
    float score = 0.0f;
    iRegExpMatch m;
    init_RegExpMatch(&m);
    while (matchRange_RegExp(pattern, text, &m)) {
        /* Match near the beginning is scored higher. */
        score += (float) size_Range(&m.range) / ((float) m.range.start + 1);
    }
    return score;
}

static float bookmarkRelevance_LookupJob_(const iLookupJob *d, const iBookmark *bm) {
    iUrl parts;
    init_Url(&parts, &bm->url);
    const float t = scoreMatch_(d->term, range_String(&bm->title));
    const float h = scoreMatch_(d->term, parts.host);
    const float p = scoreMatch_(d->term, parts.path);
    const float g = scoreMatch_(d->term, range_String(&bm->tags));
    return h + iMax(p, t) + 2 * g; /* extra weight for tags */
}

static float feedEntryRelevance_LookupJob_(const iLookupJob *d, const iFeedEntry *entry) {
    iUrl parts;
    init_Url(&parts, &entry->url);
    const float t = scoreMatch_(d->term, range_String(&entry->title));
    const float h = scoreMatch_(d->term, parts.host);
    const float p = scoreMatch_(d->term, parts.path);
    const double age = secondsSince_Time(&d->now, &entry->posted) / 3600.0 / 24.0; /* days */
    return (t * 3 + h + p) / (age + 1); /* extra weight for title, recency */
}

static float identityRelevance_LookupJob_(const iLookupJob *d, const iGmIdentity *identity) {
    iString *cn = subject_TlsCertificate(identity->cert);
    const float c = scoreMatch_(d->term, range_String(cn));
    const float n = scoreMatch_(d->term, range_String(&identity->notes));
    delete_String(cn);
    return c + 2 * n; /* extra weight for notes */
}

static float visitedRelevance_LookupJob_(const iLookupJob *d, const iVisitedUrl *vis) {
    iUrl parts;
    init_Url(&parts, &vis->url);
    const float h = scoreMatch_(d->term, parts.host);
    const float p = scoreMatch_(d->term, parts.path);
    const double age = secondsSince_Time(&d->now, &vis->when) / 3600.0 / 24.0; /* days */
    return iMax(h, p) / (age + 1); /* extra weight for recency */
}

static iBool matchBookmark_LookupJob_(void *context, const iBookmark *bm) {
    return bookmarkRelevance_LookupJob_(context, bm) > 0;
}

static iBool matchIdentity_LookupJob_(void *context, const iGmIdentity *identity) {
    return identityRelevance_LookupJob_(context, identity) > 0;
}

static void searchBookmarks_LookupJob_(iLookupJob *d) {
    /* Note: Called in a background thread. */
    /* TODO: Thread safety! What if a bookmark gets deleted while its being accessed here? */
    iConstForEach(PtrArray, i, list_Bookmarks(bookmarks_App(), NULL, matchBookmark_LookupJob_, d)) {
        const iBookmark *bm  = i.ptr;
        iLookupResult *  res = new_LookupResult();
        res->type            = bookmark_LookupResultType;
        res->when            = bm->when;
        res->relevance       = bookmarkRelevance_LookupJob_(d, bm);
        res->icon            = bm->icon;
        set_String(&res->label, &bm->title);
        set_String(&res->url, &bm->url);
        pushBack_PtrArray(&d->results, res);
    }
}

static void searchFeeds_LookupJob_(iLookupJob *d) {
    iConstForEach(PtrArray, i, listEntries_Feeds()) {
        const iFeedEntry *entry = i.ptr;
        const iBookmark *bm = get_Bookmarks(bookmarks_App(), entry->bookmarkId);
        if (!bm) {
            continue;
        }
        const float relevance = feedEntryRelevance_LookupJob_(d, entry);
        if (relevance > 0) {
            iLookupResult *res = new_LookupResult();
            res->type          = feedEntry_LookupResultType;
            res->when          = entry->posted;
            res->relevance     = relevance;
            set_String(&res->url, &entry->url);
            set_String(&res->meta, &bm->title);
            set_String(&res->label, &entry->title);
            res->icon = bm->icon;
            pushBack_PtrArray(&d->results, res);
        }
    }
}

static void searchVisited_LookupJob_(iLookupJob *d) {
    /* Note: Called in a background thread. */
    /* TODO: Thread safety! Visited URLs may be deleted while being accessed here. */
    iConstForEach(PtrArray, i, list_Visited(visited_App(), 0)) {
        const iVisitedUrl *vis = i.ptr;
        const float relevance = visitedRelevance_LookupJob_(d, vis);
        if (relevance > 0) {
            iLookupResult *res = new_LookupResult();
            res->type = history_LookupResultType;
            res->relevance = relevance;
            set_String(&res->label, &vis->url);
            set_String(&res->url, &vis->url);
            res->when = vis->when;
            pushBack_PtrArray(&d->results, res);
        }
    }
}

static void searchHistory_LookupJob_(iLookupJob *d) {
    /* Note: Called in a background thread. */
    size_t index = 0;
    iForEach(ObjectList, i, d->docs) {
        iConstForEach(StringArray, j,
                      searchContents_History(history_DocumentWidget(i.object), d->term)) {
            const char *match = cstr_String(j.value);
            const size_t matchLen = argLabel_Command(match, "len");
            iRangecc text;
            text.start = strstr(match, " str:") + 5;
            text.end = text.start + matchLen;
            const char *url = strstr(text.end, " url:") + 5;
            iLookupResult *res = new_LookupResult();
            res->type = content_LookupResultType;
            res->relevance = ++index; /* most recent comes last */
            setCStr_String(&res->label, "\"");
            appendRange_String(&res->label, text);
            appendCStr_String(&res->label, "\"");
            setCStr_String(&res->url, url);
            pushBack_PtrArray(&d->results, res);
        }
    }
}

static void searchIdentities_LookupJob_(iLookupJob *d) {
    /* Note: Called in a background thread. */
    iConstForEach(PtrArray, i, listIdentities_GmCerts(certs_App(), matchIdentity_LookupJob_, d)) {
        const iGmIdentity *identity = i.ptr;
        iLookupResult *res = new_LookupResult();
        res->type = identity_LookupResultType;
        res->relevance = identityRelevance_LookupJob_(d, identity);
        res->icon = identity->icon;
        iString *cn = subject_TlsCertificate(identity->cert);
        set_String(&res->label, cn);
        delete_String(cn);
        set_String(&res->meta,
                   collect_String(
                       hexEncode_Block(collect_Block(fingerprint_TlsCertificate(identity->cert)))));
        pushBack_PtrArray(&d->results, res);
    }
}

static iThreadResult worker_LookupWidget_(iThread *thread) {
    iLookupWidget *d = userData_Thread(thread);
//    printf("[LookupWidget] worker is running\n"); fflush(stdout);
    lock_Mutex(d->mtx);
    for (;;) {
        wait_Condition(&d->jobAvailable, d->mtx);
        if (isEmpty_String(&d->pendingTerm)) {
            break; /* Time to quit. */
        }
        iLookupJob *job = new_LookupJob();
        /* Make a regular expression to search for multiple alternative words. */ {
            iString *pattern = new_String();
            iRangecc word = iNullRange;
            iBool isFirst = iTrue;
            while (nextSplit_Rangecc(range_String(&d->pendingTerm), " ", &word)) {
                if (isEmpty_Range(&word)) continue;
                if (!isFirst) appendCStr_String(pattern, ".*");
                const iString wordStr = { iBlockLiteral(word.start,
                                                        word.end - word.start,
                                                        word.end - word.start) };
                iConstForEach(String, ch, &wordStr) {
                    /* Escape regular expression characters. */
                    if (isSyntaxChar_RegExp(ch.value)) {
                        appendChar_String(pattern, '\\');
                    }
                    appendChar_String(pattern, ch.value);
                }
                isFirst = iFalse;
            }
            iAssert(!isEmpty_String(pattern));
            job->term = new_RegExp(cstr_String(pattern), caseInsensitive_RegExpOption);
            delete_String(pattern);
        }
        const size_t termLen = length_String(&d->pendingTerm); /* characters */
        clear_String(&d->pendingTerm);
        job->docs = d->pendingDocs;
        d->pendingDocs = NULL;
        unlock_Mutex(d->mtx);
        /* Do the lookup. */ {
            searchBookmarks_LookupJob_(job);
            searchFeeds_LookupJob_(job);
            searchVisited_LookupJob_(job);
            if (termLen >= 3) {
                searchHistory_LookupJob_(job);
            }
            searchIdentities_LookupJob_(job);
        }
        /* Submit the result. */
        lock_Mutex(d->mtx);
        if (d->finishedJob) {
            /* Previous results haven't been taken yet. */
            delete_LookupJob(d->finishedJob);
        }
//        printf("[LookupWidget] worker has %zu results\n", size_PtrArray(&job->results));
        fflush(stdout);
        d->finishedJob = job;
        postCommand_Widget(as_Widget(d), "lookup.ready");
    }
    unlock_Mutex(d->mtx);
//    printf("[LookupWidget] worker has quit\n"); fflush(stdout);
    return 0;
}

iDefineObjectConstruction(LookupWidget)

void init_LookupWidget(iLookupWidget *d) {
    iWidget *w = as_Widget(d);
    init_Widget(w);
    setId_Widget(w, "lookup");
    setFlags_Widget(w, focusable_WidgetFlag | resizeChildren_WidgetFlag, iTrue);
#if defined (iPlatformAppleMobile)
    setFlags_Widget(w, unhittable_WidgetFlag, iTrue);
#endif
    d->list = addChild_Widget(w, iClob(new_ListWidget()));
    setItemHeight_ListWidget(d->list, lineHeight_Text(uiContent_FontId) * 1.25f);
    d->cursor = iInvalidPos;
    d->work = new_Thread(worker_LookupWidget_);
    setUserData_Thread(d->work, d);
    init_Condition(&d->jobAvailable);
    d->mtx = new_Mutex();
    init_String(&d->pendingTerm);
    d->pendingDocs = NULL;
    d->finishedJob = NULL;
    start_Thread(d->work);
}

void deinit_LookupWidget(iLookupWidget *d) {
    /* Stop the worker. */ {
        iGuardMutex(d->mtx, {
            iReleasePtr(&d->pendingDocs);
            clear_String(&d->pendingTerm);
            signal_Condition(&d->jobAvailable);
        });
        join_Thread(d->work);
        iRelease(d->work);
    }
    delete_LookupJob(d->finishedJob);
    deinit_String(&d->pendingTerm);
    delete_Mutex(d->mtx);
    deinit_Condition(&d->jobAvailable);
}

void submit_LookupWidget(iLookupWidget *d, const iString *term) {
    iGuardMutex(d->mtx, {
        set_String(&d->pendingTerm, term);
        trim_String(&d->pendingTerm);
        iReleasePtr(&d->pendingDocs);
        if (!isEmpty_String(&d->pendingTerm)) {
            d->pendingDocs = listDocuments_App(); /* holds reference to all open tabs */
            signal_Condition(&d->jobAvailable);
        }
        else {
            setFlags_Widget(as_Widget(d), hidden_WidgetFlag, iTrue);
        }
    });
}

static void draw_LookupWidget_(const iLookupWidget *d) {
    const iWidget *w = constAs_Widget(d);
    draw_Widget(w);
    /* Draw a frame. */ {
        iPaint p;
        init_Paint(&p);
        drawRect_Paint(&p,
                       bounds_Widget(w),
                       isFocused_Widget(w) ? uiInputFrameFocused_ColorId : uiSeparator_ColorId);
    }
}

static int cmpPtr_LookupResult_(const void *p1, const void *p2) {
    const iLookupResult *a = *(const iLookupResult **) p1;
    const iLookupResult *b = *(const iLookupResult **) p2;
    if (a->type != b->type) {
        return iCmp(a->type, b->type);
    }
    if (fabsf(a->relevance - b->relevance) < 0.0001f) {
        return cmpString_String(&a->url, &b->url);
    }
    return -iCmp(a->relevance, b->relevance);
}

static const char *cstr_LookupResultType(enum iLookupResultType d) {
    switch (d) {
        case bookmark_LookupResultType:
            return "BOOKMARKS";
        case feedEntry_LookupResultType:
            return "FEEDS";
        case history_LookupResultType:
            return "HISTORY";
        case content_LookupResultType:
            return "PAGE CONTENTS";
        case identity_LookupResultType:
            return "IDENTITIES";
        default:
            return "OTHER";
    }
}

static void presentResults_LookupWidget_(iLookupWidget *d) {
    iLookupJob *job;
    iGuardMutex(d->mtx, {
        job = d->finishedJob;
        d->finishedJob = NULL;
    });
    if (!job) return;
    clear_ListWidget(d->list);
    sort_Array(&job->results, cmpPtr_LookupResult_);
    enum iLookupResultType lastType = none_LookupResultType;
    const size_t maxPerType = 10; /* TODO: Setting? */
    size_t perType = 0;
    iConstForEach(PtrArray, i, &job->results) {
        const iLookupResult *res = i.ptr;
        if (lastType != res->type) {
            /* Heading separator. */
            iLookupItem *item = new_LookupItem(NULL);
            item->listItem.isSeparator = iTrue;
            item->fg = uiHeading_ColorId;
            item->font = uiLabel_FontId;
            format_String(&item->text, "%s", cstr_LookupResultType(res->type));
            addItem_ListWidget(d->list, item);
            iRelease(item);
            lastType = res->type;
            perType = 0;
        }
        if (perType > maxPerType) {
            continue;
        }
        if (res->type == identity_LookupResultType) {
            const iString *docUrl = url_DocumentWidget(document_App());
            iBlock *finger = hexDecode_Rangecc(range_String(&res->meta));
            const iGmIdentity *ident = findIdentity_GmCerts(certs_App(), finger);
            /* Sign in/out. */ {
                const iBool isUsed = isUsedOn_GmIdentity(ident, docUrl);
                iLookupItem *item  = new_LookupItem(res);
                item->fg           = uiText_ColorId;
                item->font         = uiContent_FontId;
                format_String(&item->text,
                              "%s \u2014 " uiTextStrong_ColorEscape "%s on this page",
                              cstr_String(&res->label),
                              isUsed ? "Stop using" : "Use");
                format_String(&item->command, "ident.sign%s ident:%s url:%s",
                              isUsed ? "out arg:0" : "in", cstr_String(&res->meta), cstr_String(docUrl));
                addItem_ListWidget(d->list, item);
                iRelease(item);
            }
            if (isUsed_GmIdentity(ident)) {
                iLookupItem *item  = new_LookupItem(res);
                item->fg           = uiText_ColorId;
                item->font         = uiContent_FontId;
                format_String(&item->text,
                              "%s \u2014 " uiTextStrong_ColorEscape "Stop using everywhere",
                              cstr_String(&res->label));
                format_String(&item->command, "ident.signout arg:1 ident:%s", cstr_String(&res->meta));
                addItem_ListWidget(d->list, item);
                iRelease(item);
            }
            delete_Block(finger);
            continue;
        }
        iLookupItem *item = new_LookupItem(res);
        const char *url = cstr_String(&res->url);
        if (startsWithCase_String(&res->url, "gemini://")) {
            url += 9;
        }
        switch (res->type) {
            case bookmark_LookupResultType: {
                item->fg = uiTextStrong_ColorId;
                item->font = uiLabel_FontId;
                format_String(&item->text,
                              "%s %s\u2014 %s",
                              cstr_String(&res->label),
                              uiText_ColorEscape,
                              url);
                format_String(&item->command, "open url:%s", cstr_String(&res->url));
                break;
            }
            case feedEntry_LookupResultType: {
                item->fg = uiTextStrong_ColorId;
                item->font = uiLabel_FontId;
                format_String(&item->text,
                              "%s %s\u2014 %s",
                              cstr_String(&res->label),
                              uiText_ColorEscape,
                              cstr_String(&res->meta));
                const iString *cmd = feedEntryOpenCommand_String(&res->url, 0);
                if (cmd) {
                    set_String(&item->command, cmd);
                }
                break;
            }
            case history_LookupResultType: {
                item->fg = uiText_ColorId;
                item->font = uiContent_FontId;
                format_String(&item->text, "%s \u2014 ", url);
                append_String(&item->text, collect_String(format_Time(&res->when, "%b %d, %Y")));
                format_String(&item->command, "open url:%s", cstr_String(&res->url));
                break;
            }
            case content_LookupResultType: {
                item->fg = uiText_ColorId;
                item->font = uiContent_FontId;
                format_String(&item->text, "%s \u2014 %s", url, cstr_String(&res->label));
                format_String(&item->command, "open url:%s", cstr_String(&res->url));
                break;
            }
            default:
                break;
        }
        addItem_ListWidget(d->list, item);
        iRelease(item);
        perType++;
    }
    delete_LookupJob(job);
    /* Re-select the item at the cursor. */
    if (d->cursor != iInvalidPos) {
        d->cursor = iMin(d->cursor, numItems_ListWidget(d->list) - 1);
        ((iListItem *) item_ListWidget(d->list, d->cursor))->isSelected = iTrue;
    }
    scrollOffset_ListWidget(d->list, 0);
    updateVisible_ListWidget(d->list);
    invalidate_ListWidget(d->list);
    setFlags_Widget(as_Widget(d), hidden_WidgetFlag, numItems_ListWidget(d->list) == 0);
}

static iLookupItem *item_LookupWidget_(iLookupWidget *d, size_t index) {
    return item_ListWidget(d->list, index);
}

static void setCursor_LookupWidget_(iLookupWidget *d, size_t index) {
    if (index != d->cursor) {
        iLookupItem *item = item_LookupWidget_(d, d->cursor);
        if (item) {
            item->listItem.isSelected = iFalse;
            invalidateItem_ListWidget(d->list, d->cursor);
        }
        d->cursor = index;
        if ((item = item_LookupWidget_(d, d->cursor)) != NULL) {
            item->listItem.isSelected = iTrue;
            invalidateItem_ListWidget(d->list, d->cursor);
        }
        scrollToItem_ListWidget(d->list, d->cursor);
    }
}

static iBool moveCursor_LookupWidget_(iLookupWidget *d, int delta) {
    const int dir  = iSign(delta);
    size_t    cur  = d->cursor;
    size_t    good = cur;
    while (delta && ((dir < 0 && cur > 0) || (dir > 0 && cur < numItems_ListWidget(d->list) - 1))) {
        cur += dir;
        if (!item_LookupWidget_(d, cur)->listItem.isSeparator) {
            delta -= dir;
            good = cur;
        }
    }
    setCursor_LookupWidget_(d, good);
    return delta == 0;
}

static iBool processEvent_LookupWidget_(iLookupWidget *d, const SDL_Event *ev) {
    iWidget *w = as_Widget(d);
    const char *cmd = command_UserEvent(ev);
    if (isCommand_Widget(w, ev, "lookup.ready")) {
        /* Take the results and present them in the list. */
        presentResults_LookupWidget_(d);
        return iTrue;
    }
    if (isResize_UserEvent(ev) || (equal_Command(cmd, "layout.changed") &&
                                   equal_Rangecc(range_Command(cmd, "id"), "navbar"))) {
        /* Position the lookup popup under the URL bar. */ {
            const iWindow *window = get_Window();
            const iInt2 rootSize = rootSize_Window(window);
            const iRect navBarBounds = bounds_Widget(findWidget_App("navbar"));
            setSize_Widget(w, init_I2(width_Widget(findWidget_App("url")),
                                      (rootSize.y - bottom_Rect(navBarBounds)) / 2));
            setPos_Widget(w, bottomLeft_Rect(bounds_Widget(findWidget_App("url"))));
#if defined (iPlatformAppleMobile)
            /* TODO: Ask the system how tall the keyboard is. */ {
                if (isLandscape_App()) {
                    w->rect.size.y = rootSize.y * 4 / 10;
                }
                else if (deviceType_App() == phone_AppDeviceType) {
                    w->rect.size.x = rootSize.x;
                    w->rect.pos.x  = 0;
                }
            }
#endif
            arrange_Widget(w);
        }
        updateVisible_ListWidget(d->list);
        invalidate_ListWidget(d->list);
    }
    if (equal_Command(cmd, "input.ended") && equal_Rangecc(range_Command(cmd, "id"), "url") &&
        !isFocused_Widget(w)) {
        setFlags_Widget(w, hidden_WidgetFlag, iTrue);
    }
    if (isCommand_Widget(w, ev, "focus.lost")) {
        setCursor_LookupWidget_(d, iInvalidPos);
    }
    if (isCommand_Widget(w, ev, "focus.gained")) {
        if (d->cursor == iInvalidPos) {
            setCursor_LookupWidget_(d, 1);
        }
    }
    if (isCommand_Widget(w, ev, "list.clicked")) {
        iInputWidget *url = findWidget_App("url");
        const iLookupItem *item = constItem_ListWidget(d->list, arg_Command(cmd));
        if (item && !isEmpty_String(&item->command)) {
            setText_InputWidget(url, url_DocumentWidget(document_App()));
            setFlags_Widget(w, hidden_WidgetFlag, iTrue);
            setCursor_LookupWidget_(d, iInvalidPos);
            postCommandString_App(&item->command);
            postCommand_App("focus.set id:"); /* unfocus */
        }
        return iTrue;
    }
    if (ev->type == SDL_KEYDOWN) {
        const int mods = keyMods_Sym(ev->key.keysym.mod);
        const int key = ev->key.keysym.sym;
        if (isFocused_Widget(d)) {
            iWidget *url = findWidget_App("url");
            switch (key) {
                case SDLK_ESCAPE:
                    setFlags_Widget(w, hidden_WidgetFlag, iTrue);
                    setCursor_LookupWidget_(d, iInvalidPos);
                    setFocus_Widget(url);
                    return iTrue;
                case SDLK_UP:
                    if (!moveCursor_LookupWidget_(d, -1)) {
                        setCursor_LookupWidget_(d, iInvalidPos);
                        setFocus_Widget(url);
                    }
                    return iTrue;
                case SDLK_DOWN:
                    moveCursor_LookupWidget_(d, +1);
                    return iTrue;
                case SDLK_PAGEUP:
                    moveCursor_LookupWidget_(d, -visCount_ListWidget(d->list) + 1);
                    return iTrue;
                case SDLK_PAGEDOWN:
                    moveCursor_LookupWidget_(d, visCount_ListWidget(d->list) - 1);
                    return iTrue;
                case SDLK_HOME:
                    setCursor_LookupWidget_(d, 1);
                    return iTrue;
                case SDLK_END:
                    setCursor_LookupWidget_(d, numItems_ListWidget(d->list) - 1);
                    return iTrue;
                case SDLK_KP_ENTER:
                case SDLK_SPACE:
                case SDLK_RETURN:
                    postCommand_Widget(w, "list.clicked arg:%zu", d->cursor);
                    return iTrue;
            }
        }
        if (key == SDLK_DOWN && !mods && focus_Widget() == findWidget_App("url") &&
            numItems_ListWidget(d->list)) {
            setCursor_LookupWidget_(d, 1); /* item 0 is always the first heading */
            setFocus_Widget(w);
            return iTrue;
        }
    }
    return processEvent_Widget(w, ev);
}

iBeginDefineSubclass(LookupWidget, Widget)
    .draw         = (iAny *) draw_LookupWidget_,
    .processEvent = (iAny *) processEvent_LookupWidget_,
iEndDefineSubclass(LookupWidget)