Repository navigation
Expand file tree
/
Copy pathtinybrowser.cpp
More file actions
6225 lines (5921 loc) · 262 KB
/
Copy pathtinybrowser.cpp
File metadata and controls
6225 lines (5921 loc) · 262 KB
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
// tinybrowser: a 160x90 frameless, always-on-top browser window (Win32 + WebView2).
//
// The address bar IS the window's start page. It is rendered with NavigateToString
// and talks to the host through chrome.webview.postMessage using one-letter commands,
// so there is no local server, no temporary files and no scripting layer. WebView2
// requires every engine call on the UI thread; this file never touches it elsewhere.
#define WIN32_LEAN_AND_MEAN
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <commdlg.h>
#include <d3d11.h>
#include <dcomp.h>
#include <objbase.h>
#include <shlobj.h>
#include <shellapi.h>
#include <windowsx.h>
#include <strsafe.h>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cwchar>
#include <cwctype>
#include <string>
#include <vector>
#include <wrl.h>
#include "WebView2.h"
#include "tinyversion.h"
using Microsoft::WRL::Callback;
using Microsoft::WRL::ComPtr;
namespace {
constexpr int kWidth = 160; // page size: what a loaded page needs to be readable
constexpr int kHeight = 90;
// The bar has its own size: at 141 px wide the magnifier button lands exactly on top of the close
// button (measured: 0.0 px apart), and 66 px tall is the two rows of controls plus the room the
// brand line needs under them. Navigating switches the window to the page size and showing the bar
// switches it back here, so the layout the user asked for is the one the start page always has.
constexpr int kBarWidth = 141;
constexpr int kBarHeight = 66;
constexpr int kMinWidth = 60; // the window can be resized down to this and no further
constexpr int kMinHeight = 60;
constexpr int kMargin = 24; // gap to the right and bottom edges of the desktop
constexpr UINT_PTR kFitTimer = 1; // one-shot: measure the page after it settles
constexpr UINT_PTR kResizeTimer = 2; // one-shot: re-fit once the resize drag settles
constexpr UINT_PTR kTopmostTimer = 3; // short retries while the bar takes the foreground
constexpr UINT kResizeSettle = 180; // ms of quiet before that happens
constexpr double kMinZoom = 0.10;
constexpr double kMaxZoom = 1.0;
// Crisp route: the page is drawn one to one into screen pixels, with grey antialiasing
// instead of ClearType fringes, and the zoom is picked so the site's font lands on a whole
// number of physical pixels. A fractional ppem is what leaves the rasterizer unable to fit
// stems to the pixel grid, and a 160 px wide window is exactly where that shows.
constexpr bool kCrispText = true;
constexpr wchar_t kCrispArgs[] = L"--disable-lcd-text --font-render-hinting=full";
// WebView2 reads extra browser arguments from this variable in the host process, which is
// cheaper and less fragile than handing it a custom ICoreWebView2EnvironmentOptions.
constexpr wchar_t kCrispArgsVar[] = L"WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS";
constexpr UINT kHotkeyBar = 1; // Ctrl+Alt+S
constexpr UINT kHotkeyQuit = 2; // Ctrl+Alt+X
constexpr UINT kHotkeyDuplicate = 3; // Ctrl+Alt+D
constexpr UINT kHotkeyBack = 4; // Ctrl+Alt+Z
constexpr UINT kHotkeyHide = 5; // Ctrl+Alt+C
constexpr UINT kHotkeyPick = 6; // Ctrl+Alt+A
constexpr UINT kHotkeyState = 7; // Ctrl+Alt+G
constexpr UINT kHotkeyOne = 8; // Ctrl+Alt+W
// No chord of its own: the forward button of the mouse is what sends it.
constexpr UINT kHotkeyForward = 20;
// What the hook -- and the close path -- posts to the window: wparam is one of the ids above.
constexpr UINT kHotkeyMessage = WM_APP + 1;
// CTRL+ALT+C is app-wide, so the instance that owns it posts one of these to every copy instead of
// toggling each window on its own: all of them follow the same command on the same press.
constexpr UINT kCommandHideAll = 10;
constexpr UINT kCommandShowAll = 11;
constexpr UINT kCommandSettings = 12; // a switch changed in another copy
constexpr UINT kPickTimer = 8; // keeps the pipette's bulb on the colour under the tip
constexpr UINT kCommandPick = 13; // the eyedropper was clicked
constexpr UINT kCommandPickCancel = 14; // ... or given up
constexpr UINT kCommandTrayTake = 15; // the copy that held the icon is gone: take it over
constexpr UINT kCommandTrayTip = 16; // a copy started or closed: the tooltip counts again
constexpr UINT kCommandHideOne = 17; // Ctrl+Alt+W: hide this copy
constexpr UINT kCommandShowOne = 18; // ... and bring it back
// This window moved to another container: the engine that has to be replaced is the one asking, so
// the teardown waits for the message loop instead of running inside the engine's own callback.
constexpr UINT kCommandContainer = 19;
// The listener found this window still unused: come forward with a fresh start page and the caret in
// the address field, which is what Ctrl+Alt+T gives when it has to open one.
constexpr UINT kCommandReused = 21;
// The window hid itself on WM_CLOSE and asks the loop to take the engines down: closing them from
// inside WM_DESTROY is a synchronous, message-pumping call in a window that no longer exists.
constexpr UINT kCommandClosed = 22;
// Asked with SendMessage by the copy that owns the chord: the answer is the flag above.
constexpr UINT kAskHiddenByW = WM_APP + 3;
// Asked by the listener before Ctrl+Alt+T opens anything: does this window still have nothing but its
// empty start page? The one that says yes is reused instead of opening another window just like it.
constexpr UINT kAskPristine = WM_APP + 4;
// The icon answers on its own message, away from the chords' kHotkeyMessage.
constexpr UINT kTrayMessage = WM_APP + 2;
constexpr UINT kTrayId = 1; // one icon per window handle, and this app has one
// The switches are kept in a file next to the exe so every copy starts with the same answers.
constexpr wchar_t kSettingsFile[] = L"tinybrowser.ini";
constexpr wchar_t kSettingsSection[] = L"options";
// The containers the machine has opened, one key each, in the order the menu shows them. The profile
// itself lives in its folder; this section is only the menu, because WebView2 cannot list profiles.
constexpr wchar_t kContainersSection[] = L"containers";
constexpr wchar_t kTitle[] = L"tinybrowser";
constexpr wchar_t kWindowClass[] = L"TinyBrowserWindow";
constexpr int kIconId = 1; // resource id of the donut in tinybrowser.rc
constexpr wchar_t kSearchPrefix[] = L"https://www.google.com/search?q=";
constexpr wchar_t kRuntimeUrl[] = L"https://go.microsoft.com/fwlink/p/?LinkId=2124703";
constexpr wchar_t kBootstrapperName[] = L"MicrosoftEdgeWebview2Setup.exe";
HWND g_window = nullptr;
bool g_picking = false; // eyedropper armed, waiting for the click
// The colours this window is keying, in the order they were picked. An empty list is the plain
// window; picking a colour that is already here takes it out, so one can go without clearing the rest.
std::vector<COLORREF> g_keyColours;
// Sin colores keyed el motor va en hosting con ventana (ahi el arrastre de archivos funciona);
// con transparencia obliga a composicion. Cambiar de modo recrea el motor y recarga la pagina,
// conservando el sitio y el zoom que tenia.
std::wstring g_pendingTarget; // lo que hay que cargar al recrear el motor
bool g_pendingSet = false; // ... y si hay algo pendiente (la barra es un pendiente vacio)
double g_restoreZoom = 1.0; // ... y el zoom que tenia la pagina
// Each colour costs a handful of filter primitives and the script travels to the page as one string:
// past this many the filter stops being cheap, and a page never needs more.
constexpr size_t kKeyColourMax = 12;
HCURSOR g_pickCursor = nullptr;
COLORREF g_pickPreview = CLR_INVALID; // colour shown in the pipette's bulb
POINT g_pickAt = {}; // where the eyedropper was clicked
bool g_blockOverlap = true; // option: a window never ends up on top of another one
bool g_pushOthers = false; // option: the window being dragged moves its neighbours aside
// Option: the window lives in the notification area instead of the taskbar. One icon answers for the
// whole app -- the copy that owns Ctrl+Alt+C holds it -- because the taskbar grouped the copies into
// a single button and one icon per window would be worse than the button it replaces.
bool g_trayOnly = true;
// Per window, and on by default: pinned means it stays over every other window, which is what tiny
// has always done. Unpinned it behaves like any window -- it can be covered. It is not an app option:
// each window has its own answer, and a .to carries it.
bool g_pinned = true;
// Per window, like the pin: 0 leaves the rectangle, 100 rounds every corner as far as the shorter
// side allows (a capsule), and anything in between is that share of the maximum radius. It is not an
// app option and nothing is written to the options file; a .to carries it.
int g_cornerRadius = 0;
// Option: the floating strip stays where it is after one of its buttons is pressed. On by default;
// with it off the strip goes away on every press, as it did first.
bool g_stripStays = true;
bool g_trayIconAdded = false; // this copy is the one holding the icon
HICON g_trayIcon = nullptr; // the small icon the notification area shows
UINT g_taskbarCreated = 0; // "TaskbarCreated": explorer restarted and wants the icon back
bool g_heldTrayIcon = false; // this copy held the icon when it was closed
// How far around the picked colour the key still reaches, in 8-bit levels per channel. 0 keys only
// the exact value; the eyedropper reads a screen pixel that may differ by a level or two from what
// the page painted, so some margin is what makes it usable at all.
int g_keyRange = 5;
constexpr int kKeyRangeMax = 40;
// The margin a .to brought with it belongs to that snapshot, not to the app: it stays in this window
// and never reaches the options file the other copies read. Moving the slider is what makes the
// margin the shared one again.
bool g_keyRangeLocal = false;
HHOOK g_keyboardHook = nullptr;
HHOOK g_mouseHook = nullptr;
// The bar is topmost too, and the window being activated sits at the top of that band: a click
// on the bar brings it over this window, and this hook is what puts the window back on top.
HWINEVENTHOOK g_foregroundHook = nullptr;
HWINEVENTHOOK g_minimizeHook = nullptr;
int g_topmostRetries = 0; // how many more passes KeepOverBar still owes
// Composition hosting: the engine draws into this DirectComposition tree instead of a child HWND.
// It is the only mode where a page can have per-pixel alpha, which is what lets a colour be made
// transparent to the desktop. The price is that pointer input has to be forwarded by hand.
ComPtr<ICoreWebView2CompositionController> g_composition;
ComPtr<IDCompositionDevice> g_dcompDevice;
ComPtr<IDCompositionTarget> g_dcompTarget;
ComPtr<IDCompositionVisual> g_dcompRoot;
HCURSOR g_pageCursor = nullptr; // what the page wants under the pointer (links, text fields)
ComPtr<ICoreWebView2Controller> g_controller;
ComPtr<ICoreWebView2> g_webview;
// One browser process serves both engines: the window's and the strip's. The environment is kept
// from the first creation and reused, instead of starting a second one on the same profile.
ComPtr<ICoreWebView2Environment> g_environment;
// The profile this window's engine runs in, empty for the Default one. A container is a profile
// inside the same data folder -- cookies, storage, cache and history apart -- and not a second
// browser process. The name is also the profile's folder, so it carries only what a file name takes:
// see SanitiseContainerName.
std::wstring g_container;
// Kept until the create call that asked for it has returned: the engine reads the options after the
// handler ends, and the next engine replaces it.
ComPtr<ICoreWebView2ControllerOptions> g_controllerOptions;
// Resizing and moving the window are driven from HERE, never from the page. Over a scrollbar the
// engine hands the drag to the scrollbar and the page stops seeing the mouse entirely (measured:
// no movement arrived, and not even the hover cursor), so a page-side resize cannot cover that
// strip. A low level mouse hook sees the input before anything can take it -- the same trick the
// global shortcuts use -- and the page is left with nothing to do about window geometry.
std::wstring g_url;
// How many documents this window has really put on screen. The engine's own "can go back" is true as
// soon as a page touches its history while it loads -- WhatsApp Web does -- and going back there is a
// step into the same page, not to anywhere the user has been. From the second document on, going back
// always means a page that was really there.
int g_documents = 0;
std::wstring g_startTarget; // URL given on the command line, if any
RECT g_placedRect = {}; // --place x y width height, when a duplicate asks for its spot
bool g_hasPlacedRect = false;
wchar_t g_resizeEdge[3] = {}; // edges being dragged ("", "n", "se", ...), empty when idle
POINT g_lastMove = {}; // pointer position of the previous step: a step is a step, so a
// window held back by a neighbour never stores up distance
bool g_dragActive = false; // a hook-driven drag is in progress
bool g_dragMoves = false; // ... and it moves the window instead of resizing it (Alt)
// A real Ctrl+click landed on this window, and the page has not answered yet. The engine turns that
// gesture into NewWindowRequested; the flag is what tells a link the user asked for from a page
// calling window.open on its own, and it is spent on the first answer.
bool g_ctrlClickArmed = false;
ULONGLONG g_ctrlClickTick = 0;
constexpr ULONGLONG kCtrlClickWindow = 1500; // milliseconds between the press and its answer
bool g_showingBar = false; // the document on screen is our own bar, not a page
bool g_setupPanel = false; // one-shot: the next bar comes up with the setup panel open
bool g_settingsPanel = false; // ... and the same for the options panel, opened from the strip
bool g_commandsPanel = false; // ... and for the help panel, likewise
// Which panel is open OVER the page, if any: options, setup or commands. Empty when none. A panel
// lives in the page itself, so opening one does not navigate, and closing it leaves the page exactly
// as it was -- same scroll, same state, no reload.
std::wstring g_pagePanel;
// Ctrl+Alt+W hid this copy, so the next press brings it back instead of hiding another one. Each
// copy keeps its own answer and the chord owner asks for it; nothing is shared between processes.
bool g_hiddenByW = false;
// This window is on its way out. From the press that closes it until the process ends nothing else is
// obeyed: Close() pumps the message queue, so a command dispatched in the middle of the teardown would
// re-enter a window that is being taken apart.
bool g_closing = false;
int g_fitPass = 0; // measurements taken for the current page
int g_widestSeen = 0; // widest layout seen for the current page, in CSS pixels
double g_bodyFont = 0.0; // body font size of the page, in CSS pixels
// Zoom a .to brought in. While it is set the fit keeps its hands off the page: a window restored
// from a snapshot has to keep the zoom it was saved with, not the one its width would imply.
int g_stateZoom = 0; // thousandths of the factor, 0 when the page is fitted as usual
void ResetFit(); // defined next to the fit helpers below
// Commands the bar page sends over chrome.webview.postMessage:
// 'G'+url navigate, 'B' back, 'F' forward, 'R' reload, 'X' close, 'S' show the bar,
// 'M'+dx+','+dy move the window by that many pixels (dragging).
constexpr wchar_t kBarTemplate[] = LR"HTML(<!doctype html>
<html><head><meta charset="utf-8"><style>
:root{color-scheme:dark}
*{box-sizing:border-box;margin:0;padding:0;font-family:"Segoe UI",sans-serif}
html,body{height:100%;background:#0f141b;color:#d7e1ea;overflow:hidden}
body{display:flex;flex-direction:column;gap:3px;padding:3px;user-select:none;cursor:default}
.row{display:flex;gap:3px;align-items:center}
#url{flex:1;min-width:0;height:20px;padding:0 4px;font-size:11px;color:#eaf2f8;background:#060a0f;border:1px solid #2b3644;border-radius:4px}
#url:focus{outline:none;border-color:#4a90c2}
button{flex:0 0 20px;height:20px;font-size:11px;line-height:1;cursor:pointer;color:#9db2c6;background:#1a2330;border:1px solid #2b3644;border-radius:4px}
button:hover{color:#fff;background:#253141}
#go{display:inline-flex;align-items:center;justify-content:center}
button:disabled{color:#46586a;background:#141c26;border-color:#1e2833;cursor:default}
button:disabled:hover{color:#46586a;background:#141c26}
kbd{color:#9db2c6;background:#1a2330;border-radius:3px;padding:0 3px;font:inherit}
#brand{position:absolute;right:5px;bottom:4px;font-size:9px;letter-spacing:.3px;color:#33455a;
white-space:nowrap}
#brand .dot{display:inline-block;width:6px;height:6px;border-radius:50%;margin-right:3px;
vertical-align:1px}
#commands{position:absolute;left:3px;right:3px;top:3px;bottom:3px;z-index:5;padding:4px 6px;
background:#0c1219;border:1px solid #2b3644;border-radius:4px;font-size:10px;line-height:1.25;
color:#9db2c6;overflow:auto}
#commands[hidden]{display:none}
#commands .k{display:inline-block;min-width:58px;color:#7fb3d5}
#closepanel{font-size:9px;color:#5b6b7d;margin-top:1px}
#options{display:inline-flex;align-items:center;justify-content:center}
#settings{position:absolute;left:3px;right:3px;top:3px;bottom:3px;z-index:6;padding:2px 5px;
background:#0c1219;border:1px solid #2b3644;border-radius:4px;font-size:10px;line-height:1;
color:#9db2c6;overflow:auto}
#settings[hidden]{display:none}
#settings .title{display:flex;align-items:center;gap:4px;color:#7fb3d5;margin-bottom:1px}
#settings select{flex:0 1 auto;min-width:0;max-width:78px;height:13px;font:inherit;
font-size:9px;color:#eaf2f8;background:#060a0f;border:1px solid #2b3644;border-radius:3px;
cursor:pointer}
#settings select:focus{outline:none;border-color:#4a90c2}
#settings #containernew{flex:1 1 auto;min-width:0;height:13px;padding:0 3px;font:inherit;
font-size:9px;color:#eaf2f8;background:#060a0f;border:1px solid #4a90c2;border-radius:3px}
#settings #containernew:focus{outline:none}
#settings label{display:flex;align-items:center;gap:4px;margin:0;cursor:pointer}
#settings input[type=checkbox]{flex:0 0 auto;width:11px;height:11px;margin:0;
accent-color:#4a90c2;cursor:pointer}
#settings input[type=checkbox]:disabled{cursor:default}
#settings .range{display:flex;align-items:center;justify-content:space-between;cursor:default}
#settings input[type=range]{display:block;width:100%;height:10px;margin:0;padding:0;
-webkit-appearance:none;appearance:none;background:transparent;cursor:pointer}
#settings input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:2px;
background:#2b3644}
#settings input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;
width:9px;height:9px;margin-top:-2.5px;border-radius:50%;background:#4a90c2}
#settings .value{flex:0 0 12px;text-align:right;color:#7fb3d5}
#settings .inline{cursor:default}
#settings .inline input[type=range]{flex:1 1 auto;width:auto;min-width:0}
#closepanel2{font-size:9px;color:#5b6b7d;margin-top:1px}
#setup{position:absolute;left:3px;right:3px;top:3px;bottom:3px;z-index:7;padding:3px 5px;
background:#0c1219;border:1px solid #2b3644;border-radius:4px;font-size:10px;line-height:1.1;
color:#9db2c6;overflow:hidden}
#setup[hidden]{display:none}
#setup .title{color:#7fb3d5;margin-bottom:3px}
#setup .actions{display:flex;gap:3px;margin-bottom:3px}
#setup button{flex:none;width:100%;height:18px;margin-bottom:3px;font-size:10px}
#setup .actions button{flex:1 1 0;width:auto;min-width:0;margin:0;padding:0 2px;overflow:hidden;
white-space:nowrap;text-overflow:ellipsis}
#setup label{display:flex;align-items:center;gap:4px;margin:0;cursor:pointer}
#setup input[type=checkbox]{flex:0 0 auto;width:11px;height:11px;margin:0;
accent-color:#4a90c2;cursor:pointer}
#setup input[type=checkbox]:disabled{cursor:default}
#setup .note{color:#5b6b7d;margin-top:3px;white-space:nowrap;overflow:hidden;
text-overflow:ellipsis}
</style></head><body>
<div class="row"><input id="url" type="text" spellcheck="false" autocomplete="off" placeholder="url o busqueda" value="%URL%"><button id="go" title="Go"><svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="6.8" cy="6.8" r="5"/><path d="M10.1 10.1 15 15"/></svg></button></div>
<div class="row"><button id="back" title="Back"%DISABLED%>‹</button><button id="fwd" title="Forward"%DISABLED%>›</button><button id="setupbtn" title="Instalar tinybrowser"><svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2v6.5"/><path d="M5 5.8 8 8.8 11 5.8"/><path d="M2.5 11.5v2h11v-2"/></svg></button><button id="options" title="Opciones"><svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M2 4h12M2 8h12M2 12h12"/><path d="M6 2v4M10 6v4M5 10v4"/></svg></button><button id="help" title="Comandos y atajos">?</button><button id="close" title="Close (Ctrl+Alt+X)">✕</button></div>
<div id="brand">%CONTAINER_BRAND%tinybrowser 2026</div>
<div id="commands"%COMMANDS_HIDDEN%>
<div><span class="k">Ctrl+Alt+S</span> barra</div>
<div><span class="k">Ctrl+Alt+D</span> duplicar</div>
<div><span class="k">Ctrl+Alt+G</span> guardar / cargar</div>
<div><span class="k">Ctrl+Alt+Z</span> atrás</div>
<div><span class="k">Ctrl+Alt+C</span> ocultar</div>
<div><span class="k">Ctrl+Alt+W</span> ocultar una</div>
<div><span class="k">Ctrl+Alt+A</span> gotero</div>
<div><span class="k">Ctrl+Alt+X</span> cerrar</div>
<div><span class="k">Alt+arrastrar</span> mover</div>
<div id="closepanel">clic para cerrar</div>
</div>
)HTML" LR"HTML(
<div id="settings"%SETTINGS_HIDDEN%>
<div class="title">Contenedor<select id="container" title="Contenedor">%CONTAINER_OPTIONS%</select><input id="containernew" type="text" maxlength="24" spellcheck="false" autocomplete="off" placeholder="nombre" hidden></div>
<label class="inline" title="Solo esta ventana"><span>Esquinas</span><input type="range" id="corner" min="0" max="100" step="1" value="%CORNER_RADIUS%"><span class="value" id="cornervalue">%CORNER_RADIUS%</span></label>
<label><input type="checkbox" id="nooverlap"%CHECKED_OVERLAP%><span>No solapar ventanas</span></label>
<label><input type="checkbox" id="push"%CHECKED_PUSH%%PUSH_DISABLED%><span>Al arrastrar, empujar otras</span></label>
<label><input type="checkbox" id="trayonly"%CHECKED_TRAY%><span>Solo en notificaciones</span></label>
<label><input type="checkbox" id="stripstays"%CHECKED_STAYS%><span>La tira queda abierta</span></label>
<label class="range"><span>Rango del color</span><span class="value" id="keyrangevalue">%KEY_RANGE%</span></label>
<input type="range" id="keyrange" min="0" max="40" step="1" value="%KEY_RANGE%">
</div>
<div id="setup"%SETUP_HIDDEN%>
<div class="title">Instalación</div>
<div class="actions"><button id="setupaction" data-cmd="I">%SETUP_ACTION%</button><button id="setupremove" data-cmd="U"%SETUP_REMOVE_DISABLED% title="Desinstalar del equipo">Quitar</button></div>
<label><input type="checkbox" id="desktopicon"%DESKTOP_CHECKED%%DESKTOP_DISABLED%><span>Icono en el escritorio</span></label>
<div class="note">%SETUP_STATUS%</div>
</div>
<script>
(function () {
function send(message) { try { window.chrome.webview.postMessage(message); } catch (e) { } }
function submit() {
var value = document.getElementById("url").value.trim();
if (value) { send("G" + value); }
}
document.getElementById("go").onclick = submit;
document.getElementById("url").onkeydown = function (e) {
if (e.key === "Enter") { e.preventDefault(); submit(); }
};
document.getElementById("back").onclick = function () { send("B"); };
document.getElementById("fwd").onclick = function () { send("F"); };
document.getElementById("close").onclick = function () { send("X"); };
// Both panels cover the whole bar, so they fit at any window size, and only one is open at once.
var commands = document.getElementById("commands");
var settings = document.getElementById("settings");
document.getElementById("help").onclick = function () {
settings.hidden = true;
setupPanel.hidden = true;
commands.hidden = !commands.hidden;
};
commands.onclick = function () { commands.hidden = true; };
document.getElementById("options").onclick = function () {
commands.hidden = true;
setupPanel.hidden = true;
settings.hidden = !settings.hidden;
};
settings.onclick = function (e) {
// Only the empty area closes it: a click on a switch or its label must reach the checkbox.
if (e.target === settings) { settings.hidden = true; }
};
document.addEventListener("keydown", function (e) {
if (e.key === "Escape") {
commands.hidden = true;
settings.hidden = true;
setupPanel.hidden = true;
}
}, true);
// The switches belong to the host: the page only reports the new value. Pushing needs the rule
// above it to mean anything, so it stays disabled in its place while that one is off.
var noOverlap = document.getElementById("nooverlap");
var pushOthers = document.getElementById("push");
noOverlap.onchange = function () {
send("N" + (noOverlap.checked ? "1" : "0"));
pushOthers.disabled = !noOverlap.checked;
};
pushOthers.onchange = function () { send("P" + (pushOthers.checked ? "1" : "0")); };
var trayOnly = document.getElementById("trayonly");
trayOnly.onchange = function () { send("Y" + (trayOnly.checked ? "1" : "0")); };
var stripStays = document.getElementById("stripstays");
stripStays.onchange = function () { send("Q" + (stripStays.checked ? "1" : "0")); };
// The range only travels on release: dragging would otherwise rewrite the settings file and
// re-filter every window on each pixel of the slider.
var keyRange = document.getElementById("keyrange");
var keyRangeValue = document.getElementById("keyrangevalue");
keyRange.oninput = function () { keyRangeValue.textContent = keyRange.value; };
keyRange.onchange = function () { send("T" + keyRange.value); };
// The corners travel on every step: no file is written and the window only reshapes itself, so the
// slider can be seen while it moves.
var corner = document.getElementById("corner");
var cornerValue = document.getElementById("cornervalue");
corner.oninput = function () {
cornerValue.textContent = corner.value;
send("R" + corner.value);
};
// The container menu is the list the host keeps in the options file; a name that is not there yet
// is typed on the same line, so the panel never grows and no dialog is needed.
var container = document.getElementById("container");
var containerNew = document.getElementById("containernew");
function leaveNewName() {
containerNew.hidden = true;
container.hidden = false;
containerNew.value = "";
}
container.onchange = function () {
if (container.value !== "*") { send("V" + container.value); return; }
container.hidden = true;
containerNew.hidden = false;
containerNew.focus();
};
containerNew.onkeydown = function (e) {
if (e.key === "Enter") {
e.preventDefault();
var name = containerNew.value.trim();
if (name) { send("V" + name); return; }
leaveNewName();
} else if (e.key === "Escape") {
leaveNewName();
}
};
containerNew.onblur = leaveNewName;
// The setup panel: the host does the work (copy the exe, the PATH, the .to association) and rebuilds
// the bar afterwards, so every label here shows the state the machine is really in.
var setupPanel = document.getElementById("setup");
document.getElementById("setupbtn").onclick = function () {
commands.hidden = true;
settings.hidden = true;
setupPanel.hidden = !setupPanel.hidden;
};
setupPanel.onclick = function (e) {
if (e.target === setupPanel) { setupPanel.hidden = true; }
};
var setupAction = document.getElementById("setupaction");
setupAction.onclick = function () { send(setupAction.getAttribute("data-cmd")); };
document.getElementById("setupremove").onclick = function () { send("U"); };
document.getElementById("desktopicon").onchange = function () {
send("K" + (this.checked ? "1" : "0"));
};
// The engine swallows mouse input before it reaches the host window, so dragging has to
// start inside the page: the bar reports pixel deltas and the host moves itself. Anything that
// is not a control or a panel is a handle, so the empty room of the line -- the brand, the gaps
// between buttons -- moves the window, like the title bar of a normal window.
function startDrag(element) {
element.addEventListener("mousedown", function (e) {
if (e.button !== 0) { return; }
if (e.target && e.target.closest &&
e.target.closest("button, input, select, label, a, #settings, #commands, #setup")) {
return;
}
e.preventDefault();
var lastX = e.screenX;
var lastY = e.screenY;
function move(ev) {
send("M" + (ev.screenX - lastX) + "," + (ev.screenY - lastY));
lastX = ev.screenX;
lastY = ev.screenY;
}
function stop() {
document.removeEventListener("mousemove", move, true);
document.removeEventListener("mouseup", stop, true);
}
document.addEventListener("mousemove", move, true);
document.addEventListener("mouseup", stop, true);
});
}
startDrag(document.body);
var input = document.getElementById("url");
input.focus();
input.select();
})();
</script></body></html>
)HTML";
// Document-start script for every page: keep the bar reachable, stop target=_blank from
// asking for a popup window the host does not have, and move the window on Alt+drag (the
// host never sees mouse input that the engine already consumed).
// Document-start script for every page: keep the bar reachable, and stop target=_blank from
// asking for a popup window the host does not have. Window geometry is the HOST's job, not the
// page's: over a scrollbar the engine stops sending the page any mouse at all, so a page-side
// resize could never cover that strip (see the mouse hook above).
constexpr wchar_t kPageScript[] = LR"JS((function () {
function post(message) {
try { window.chrome.webview.postMessage(message); } catch (err) { }
}
document.addEventListener("click", function (e) {
var link = e.target && e.target.closest ? e.target.closest("a") : null;
// A plain click on target=_blank stays in this window. Ctrl+click is the gesture that becomes
// another tiny window, so the host's NewWindowRequested handler has to see it: rewriting the
// target here would turn it into an ordinary navigation.
if (link && !e.ctrlKey && (link.target || "").toLowerCase() === "_blank") {
link.target = "_self";
}
}, true);
document.addEventListener("keydown", function (e) {
if (e.ctrlKey && e.altKey && (e.key === "s" || e.key === "S")) {
e.preventDefault();
post("S");
}
}, true);
// The cursor on the window's edges belongs to the page, because CSS is the one thing the engine
// obeys: the host cannot set it (the engine's own cursor handling wins), which was measured. The
// host still owns the drag itself -- over a scrollbar the page never sees the mouse.
//
// The state is a stylesheet of our own and never a class on <html>: every framework owns that
// attribute and rewrites it on each render, and the class was gone before the pointer moved again
// (measured: with the class rewritten the resize cursor never came back).
var cursorStyle = null;
var cursorEdge = "";
function applyCursor() {
if (!document.head) { return; }
if (!cursorStyle) {
cursorStyle = document.createElement("style");
cursorStyle.id = "tiny-edge-cursor";
}
if (!cursorStyle.isConnected) { document.head.appendChild(cursorStyle); }
if (!cursorEdge) {
if (cursorStyle.textContent) { cursorStyle.textContent = ""; }
return;
}
var shape = (cursorEdge === "n" || cursorEdge === "s") ? "ns-resize"
: (cursorEdge === "w" || cursorEdge === "e") ? "ew-resize"
: (cursorEdge === "nw" || cursorEdge === "se") ? "nwse-resize" : "nesw-resize";
// Every element, plus the scrollbar the engine draws itself: over one of those strips the page is
// never told where the pointer is, and the resize cursor used to vanish exactly there.
var targets = ["html", "html *", "html::-webkit-scrollbar", "html ::-webkit-scrollbar",
"html::-webkit-scrollbar-thumb", "html ::-webkit-scrollbar-thumb"];
var out = "";
for (var i = 0; i < targets.length; i++) {
out += targets[i] + "{cursor:" + shape + " !important}";
}
if (cursorStyle.textContent !== out) { cursorStyle.textContent = out; }
}
// A re-render of the whole document can take the stylesheet with it; the pointer over the edge puts
// it back. No timer: while the pointer is anywhere else this costs nothing.
document.addEventListener("pointermove", function () {
if (cursorEdge && (!cursorStyle || !cursorStyle.isConnected)) { applyCursor(); }
}, true);
// Only the host decides this. It sees the mouse everywhere -- including over a scrollbar, which the
// page is never told about -- and it knows where the corners reach; the page's own version of that
// sum could disagree and fight it.
window.__tinybrowserSetEdge = function (edge) { cursorEdge = edge || ""; applyCursor(); };
})();)JS";
std::wstring Trim(const std::wstring& text) {
const size_t first = text.find_first_not_of(L" \t\r\n");
if (first == std::wstring::npos) {
return std::wstring();
}
return text.substr(first, text.find_last_not_of(L" \t\r\n") - first + 1);
}
bool StartsWith(const std::wstring& text, const std::wstring& prefix) {
return text.size() >= prefix.size() && text.compare(0, prefix.size(), prefix) == 0;
}
// The only schemes a link may hand to a new window: a separate process has to be able to load it as
// a page. javascript:, mailto:, blob:, data: and file: stay in the window that had them.
bool IsWebAddress(const wchar_t* text) {
return text && (_wcsnicmp(text, L"http://", 7) == 0 || _wcsnicmp(text, L"https://", 8) == 0);
}
std::wstring EncodeQuery(const std::wstring& text) {
int size = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), (int)text.size(), nullptr, 0, nullptr, nullptr);
std::string utf8(size, '\0');
WideCharToMultiByte(CP_UTF8, 0, text.c_str(), (int)text.size(), &utf8[0], size, nullptr, nullptr);
const wchar_t* hex = L"0123456789ABCDEF";
std::wstring encoded;
for (unsigned char byte : utf8) {
if (std::isalnum(byte) || byte == '-' || byte == '_' || byte == '.' || byte == '~') {
encoded += (wchar_t)byte;
} else {
encoded += L'%';
encoded += hex[byte >> 4];
encoded += hex[byte & 0x0F];
}
}
return encoded;
}
// Bar text to URL: scheme passthrough, http for local hosts, https when the first
// segment looks like a host, otherwise a web search.
std::wstring Normalize(const std::wstring& raw) {
const std::wstring text = Trim(raw);
if (text.empty()) {
return text;
}
if (text.find(L"://") != std::wstring::npos || StartsWith(text, L"about:") || StartsWith(text, L"view-source:")) {
return text;
}
const std::wstring host = text.substr(0, text.find(L'/'));
const bool localHost = StartsWith(host, L"localhost") || StartsWith(host, L"127.0.0.1");
const bool ipLike = !host.empty() && std::iswdigit(host[0]) && host.find(L'.') != std::wstring::npos;
if (localHost || ipLike) {
return L"http://" + text;
}
if (host.find(L'.') != std::wstring::npos) {
return L"https://" + text;
}
return std::wstring(kSearchPrefix) + EncodeQuery(text);
}
std::wstring EscapeAttribute(const std::wstring& text) {
std::wstring escaped;
for (wchar_t ch : text) {
switch (ch) {
case L'&': escaped += L"&"; break;
case L'<': escaped += L"<"; break;
case L'>': escaped += L">"; break;
case L'"': escaped += L"""; break;
default: escaped += ch;
}
}
return escaped;
}
std::wstring UserDataFolder() {
wchar_t path[MAX_PATH] = {};
DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", path, MAX_PATH);
if (length == 0 || length >= MAX_PATH) {
return std::wstring();
}
std::wstring folder(path);
folder += L"\\tinybrowser";
CreateDirectoryW(folder.c_str(), nullptr);
return folder;
}
void ResizeIfCanonical(int width, int height); // defined with the placement helpers below
void PublishEdgeCursor(int edges); // tells the page which edge the pointer is on
// Ctrl+wheel zoom is a feature on a page and a nuisance on the bar: it would shrink the bar's
// own controls by hand, which is exactly what we just stopped the fit from doing.
void SetPageZoomControl(bool enabled) {
if (!g_webview) {
return;
}
ICoreWebView2Settings* settings = nullptr;
if (SUCCEEDED(g_webview->get_Settings(&settings)) && settings) {
settings->put_IsZoomControlEnabled(enabled ? TRUE : FALSE);
settings->Release();
}
}
// Single-use placeholders in the bar page: the value goes in once and the token disappears.
// Every occurrence: one token can be needed in more than one place (the range shows its value twice).
void ReplaceToken(std::wstring* html, const wchar_t* token, const wchar_t* value) {
const size_t length = std::wcslen(token);
const size_t grown = std::wcslen(value);
for (size_t at = html->find(token); at != std::wstring::npos;
at = html->find(token, at + grown)) {
html->replace(at, length, value);
}
}
// The same, for a value built at run time (a version, a path) instead of a literal.
void ReplaceToken(std::wstring* html, const wchar_t* token, const std::wstring& value) {
ReplaceToken(html, token, value.c_str());
}
// The setup panel: copy this exe into the user's folder, put that folder on the PATH and point the
// .to association at the copy. The bar asks about the installed copy on every redraw, so the readers
// are here next to it.
// What the setup panel offers and what it can say about the copy this machine holds.
struct SetupInfo {
bool installed = false;
std::wstring action; // the word on the button: install, update, reinstall or replace
std::wstring note; // the versions behind that word
};
SetupInfo DescribeSetup();
bool IsInstalled();
bool FileExists(const std::wstring& path);
std::wstring DesktopShortcutPath();
bool EnsureAssociation();
bool CreateDesktopShortcut();
void RemoveDesktopShortcut();
void RemoveAssociation();
void DoInstall();
void DoUninstall();
void ToggleStartSurface(); // Ctrl+Alt+S: the strip over a page, the start page without one
void HideStrip(); // the strip in its own window, shared with WindowProc
void RepositionStripIfShown(); // the strip follows its window, edge and gap included
void RefreshStripAddress(); // the strip's field follows the page while the strip stays open
void RefreshStripHistory(); // ... and so do its back and forward buttons
void ShowPagePanel(const wchar_t* which); // options over the page, without leaving it
void SetPinned(bool on); // per window: over every other window, or an ordinary one
void DestroyStrip();
// Containers: one WebView2 profile per container inside the one data folder. The window's container
// is a property of the window, like the pin: no option row, no .ini switch, a field in the .to.
std::wstring SanitiseContainerName(const std::wstring& text);
bool SameContainer(const std::wstring& left, const std::wstring& right);
std::vector<std::wstring> ReadContainers();
std::wstring ContainerOptions();
std::wstring ContainerBrand();
COLORREF ContainerColour(const std::wstring& name);
void RememberContainer(const std::wstring& name);
void SwitchContainer(const std::wstring& name);
void TeardownEngine();
void CreateWebView();
// How round this window is right now, in physical pixels. The percentage is a share of the largest
// radius four equal corners can take: half the shorter side, where the arcs meet and the rectangle
// becomes a capsule. The start bar is capped, because at full rounding its address field and buttons
// would be cut by the same shape the page wants.
constexpr int kBarCornerMax = 10;
int CornerRadiusPx() {
if (!g_window || g_cornerRadius <= 0) {
return 0;
}
RECT client = {};
if (!GetClientRect(g_window, &client)) {
return 0;
}
const int width = client.right - client.left;
const int height = client.bottom - client.top;
const int shortest = width < height ? width : height;
int radius = (shortest * g_cornerRadius + 100) / 200;
const int most = shortest / 2;
if (radius > most) {
radius = most;
}
if (g_showingBar && radius > kBarCornerMax) {
radius = kBarCornerMax;
}
return radius;
}
// The window's shape, in window coordinates: the whole rectangle at 0, a rounded rectangle after.
// The system owns the region once SetWindowRgn takes it, so it is never deleted here. The last shape
// is remembered: a resize redraws the same region many times, and SetWindowRgn invalidates the whole
// window even when the answer has not changed.
bool g_hasCornerRegion = false;
int g_cornerRegionRadius = 0;
int g_cornerRegionWidth = 0;
int g_cornerRegionHeight = 0;
void ApplyCornerRegion() {
if (!g_window) {
return;
}
// The common case is a square window: nothing to measure and nothing to clear.
if (g_cornerRadius <= 0 && !g_hasCornerRegion) {
return;
}
RECT client = {};
if (!GetClientRect(g_window, &client)) {
return;
}
const int width = client.right - client.left;
const int height = client.bottom - client.top;
const int radius = CornerRadiusPx();
if (radius <= 0) {
if (g_hasCornerRegion) {
SetWindowRgn(g_window, nullptr, TRUE);
g_hasCornerRegion = false;
}
return;
}
if (g_hasCornerRegion && radius == g_cornerRegionRadius && width == g_cornerRegionWidth &&
height == g_cornerRegionHeight) {
return;
}
HRGN region = CreateRoundRectRgn(0, 0, width + 1, height + 1, radius * 2, radius * 2);
if (!region) {
return;
}
if (SetWindowRgn(g_window, region, TRUE)) {
g_hasCornerRegion = true;
g_cornerRegionRadius = radius;
g_cornerRegionWidth = width;
g_cornerRegionHeight = height;
} else {
DeleteObject(region); // the system did not take it
}
}
void ShowBar() {
if (!g_webview) {
return;
}
std::wstring html(kBarTemplate);
const size_t at = html.find(L"%URL%");
if (at != std::wstring::npos) {
html.replace(at, 5, EscapeAttribute(g_url));
}
// Nothing to go back to, reload or duplicate until a page has been loaded: those buttons say so
// instead of doing nothing or, worse, reloading the bar itself into a blank window.
const std::wstring disabled = g_url.empty() ? L" disabled" : L"";
for (size_t slot = html.find(L"%DISABLED%"); slot != std::wstring::npos;
slot = html.find(L"%DISABLED%", slot)) {
html.replace(slot, 10, disabled);
slot += disabled.size(); // every button has its own placeholder, not just the first
}
ReplaceToken(&html, L"%CHECKED_OVERLAP%", g_blockOverlap ? L" checked" : L"");
ReplaceToken(&html, L"%CHECKED_PUSH%", g_pushOthers ? L" checked" : L"");
ReplaceToken(&html, L"%CHECKED_TRAY%", g_trayOnly ? L" checked" : L"");
ReplaceToken(&html, L"%CHECKED_STAYS%", g_stripStays ? L" checked" : L"");
wchar_t rangeValue[8] = {};
wsprintfW(rangeValue, L"%d", g_keyRange);
ReplaceToken(&html, L"%KEY_RANGE%", rangeValue);
wchar_t corners[8] = {};
wsprintfW(corners, L"%d", g_cornerRadius);
ReplaceToken(&html, L"%CORNER_RADIUS%", corners);
// Which container this window is in: the brand line says it with a dot, and the options panel
// lists the ones the machine already knows.
ReplaceToken(&html, L"%CONTAINER_BRAND%", ContainerBrand());
ReplaceToken(&html, L"%CONTAINER_OPTIONS%", ContainerOptions());
// Pushing without the rule above it makes no sense, so it is disabled in place, not hidden.
ReplaceToken(&html, L"%PUSH_DISABLED%", g_blockOverlap ? L"" : L" disabled");
// The setup panel speaks about the machine, not about this window, so every bar reads the same
// answer: which button it offers, whether the copy is there and whether the icon exists.
const SetupInfo setup = DescribeSetup();
ReplaceToken(&html, L"%SETUP_HIDDEN%", g_setupPanel ? L"" : L" hidden");
g_setupPanel = false;
// Opened from the strip, which has no room for a panel: the bar comes up with it already open.
ReplaceToken(&html, L"%SETTINGS_HIDDEN%", g_settingsPanel ? L"" : L" hidden");
g_settingsPanel = false;
ReplaceToken(&html, L"%COMMANDS_HIDDEN%", g_commandsPanel ? L"" : L" hidden");
g_commandsPanel = false;
ReplaceToken(&html, L"%SETUP_ACTION%", setup.action);
ReplaceToken(&html, L"%SETUP_STATUS%", setup.note);
ReplaceToken(&html, L"%SETUP_REMOVE_DISABLED%", setup.installed ? L"" : L" disabled");
ReplaceToken(&html, L"%DESKTOP_CHECKED%", FileExists(DesktopShortcutPath()) ? L" checked" : L"");
ReplaceToken(&html, L"%DESKTOP_DISABLED%", setup.installed ? L"" : L" disabled");
g_showingBar = true;
ResetFit();
ResizeIfCanonical(kBarWidth, kBarHeight);
ApplyCornerRegion(); // the bar's own shape, capped so its controls stay inside
if (g_controller) {
g_controller->put_ZoomFactor(1.0); // the bar page is sized for the raw window
}
SetPageZoomControl(false);
g_webview->NavigateToString(html.c_str());
}
void Navigate(const std::wstring& target) {
if (!g_webview) {
return;
}
const std::wstring url = Normalize(target);
if (url.empty()) {
return;
}
g_url = url;
g_showingBar = false;
g_stateZoom = 0; // a page that is opened is fitted; only a .to says otherwise
ResetFit();
SetPageZoomControl(true);
ResizeIfCanonical(kWidth, kHeight); // a page needs the room
ApplyCornerRegion(); // ... and the window's full shape, without the bar's cap
g_webview->Navigate(url.c_str());
}
void RunInPage(const wchar_t* script) {
if (g_webview) {
g_webview->ExecuteScript(script, nullptr);
}
}
// One step in the page's own history, which is what the bar's arrows and the side buttons of a mouse
// do. Nothing to walk while the bar itself is on screen: its document is a single entry, and stepping
// it would leave the start page blank instead of doing nothing.
void StepHistory(bool forward) {
if (g_url.empty() || g_showingBar) {
return;
}
RunInPage(forward ? L"history.forward()" : L"history.back()");
}
void DuplicateInNewInstance(); // defined with the placement helpers below
void StateChord(); // Ctrl+Alt+G: freezes a page into a .to file, or brings one back
// Windows ships no eyedropper cursor, and a crosshair does not say "pick a colour". The pipette is
// drawn here: a shaft with a round bulb at the end, black over a white halo so it reads on any
// background, and nothing anywhere else (fully transparent pixels). The tip has to sit on (0,0):
// a cursor built with CreateIconIndirect always has that hotspot, so a tip drawn anywhere else makes
// the pixel that gets picked land far from the pixel the user is aiming at.
HCURSOR CreatePickCursor(COLORREF preview, bool hasPreview) {
const int size = 32;
BITMAPV5HEADER header = {};
header.bV5Size = sizeof(header);
header.bV5Width = size;
header.bV5Height = -size;
header.bV5Planes = 1;
header.bV5BitCount = 32;
header.bV5Compression = BI_BITFIELDS;
header.bV5RedMask = 0x00FF0000;
header.bV5GreenMask = 0x0000FF00;
header.bV5BlueMask = 0x000000FF;
header.bV5AlphaMask = 0xFF000000;
void* pixels = nullptr;
HDC screen = GetDC(nullptr);
HBITMAP colour = CreateDIBSection(screen, (BITMAPINFO*)&header, DIB_RGB_COLORS, &pixels,
nullptr, 0);
ReleaseDC(nullptr, screen);
if (!colour || !pixels) {
return nullptr;
}
HBITMAP mask = CreateBitmap(size, size, 1, 1, nullptr); // all zero: use the colour bitmap
// The pipette: tip at (0,0), shaft to (12,12), bulb at (17,17).
const int shaftX0 = 0, shaftY0 = 0, shaftX1 = 12, shaftY1 = 12;
const int bulbX = 17, bulbY = 17;
const double shaftDx = (double)(shaftX1 - shaftX0);
const double shaftDy = (double)(shaftY1 - shaftY0);
const double shaftLen = shaftDx * shaftDx + shaftDy * shaftDy;
auto distanceToShaft = [&](int x, int y) {
const double t = ((x - shaftX0) * shaftDx + (y - shaftY0) * shaftDy) / shaftLen;
const double clamped = t < 0 ? 0 : (t > 1 ? 1 : t);
const double px = shaftX0 + clamped * shaftDx;
const double py = shaftY0 + clamped * shaftDy;
const double dx = x - px;
const double dy = y - py;
return dx * dx + dy * dy;
};
auto distanceToBulb = [&](int x, int y) {
const double dx = x - bulbX;
const double dy = y - bulbY;
return dx * dx + dy * dy;
};
DWORD* buffer = (DWORD*)pixels;
// Two passes: the white halo first, the black body on top of it.
for (int pass = 0; pass < 2; ++pass) {
const double shaftRadius = pass == 0 ? 4.0 : 2.0;
const double bulbRadius = pass == 0 ? 9.5 : 6.5;
const DWORD paint = pass == 0 ? 0xFFFFFFFF : 0xFF000000;
for (int y = 0; y < size; ++y) {
for (int x = 0; x < size; ++x) {
if (x == 0 && y == 0) {
continue; // never paint the pixel that is being read
}
if (distanceToShaft(x, y) <= shaftRadius * shaftRadius ||
distanceToBulb(x, y) <= bulbRadius * bulbRadius) {
buffer[y * size + x] = paint;
}
}
}
}
// The bulb shows the colour that is about to go: what the tip is pointing at.
if (hasPreview) {
const DWORD shown = 0xFF000000 | ((DWORD)GetRValue(preview) << 16) |
((DWORD)GetGValue(preview) << 8) | GetBValue(preview);
for (int y = 0; y < size; ++y) {
for (int x = 0; x < size; ++x) {
if (distanceToBulb(x, y) <= 4.0 * 4.0) {
buffer[y * size + x] = shown;
}
}
}
}
ICONINFO info = {};
info.fIcon = FALSE;
info.hbmMask = mask;
info.hbmColor = colour;
HCURSOR cursor = (HCURSOR)CreateIconIndirect(&info);
DeleteObject(colour);
DeleteObject(mask);
return cursor;
}
// The pixel under the tip, read from the desktop itself so it works over any window, not only ours.
COLORREF ScreenPixel(POINT point) {
HDC screen = GetDC(nullptr);
const COLORREF colour = GetPixel(screen, point.x, point.y);
ReleaseDC(nullptr, screen);
return colour;
}