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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
|
/* 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 "window.h"
#include "../app.h"
#include "bookmarks.h"
#include "command.h"
#include "defs.h"
#include "embedded.h"
#include "keys.h"
#include "labelwidget.h"
#include "documentwidget.h"
#include "paint.h"
#include "root.h"
#include "touch.h"
#include "util.h"
#if defined (iPlatformMsys)
# include "../win32.h"
#endif
#if defined (iPlatformAppleDesktop)
# include "macos.h"
#endif
#if defined (iPlatformAppleMobile)
# include "ios.h"
#endif
#include <the_Foundation/file.h>
#include <the_Foundation/path.h>
#include <the_Foundation/regexp.h>
#include <SDL_hints.h>
#include <SDL_timer.h>
#include <SDL_syswm.h>
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image.h"
#include "stb_image_resize.h"
static iWindow *theWindow_ = NULL;
#if defined (iPlatformApple) || defined (iPlatformLinux) || defined (iPlatformOther)
static float initialUiScale_ = 1.0f;
#else
static float initialUiScale_ = 1.1f;
#endif
static iBool isOpenGLRenderer_;
iDefineTypeConstructionArgs(Window, (iRect rect), rect)
/* TODO: Define menus per platform. */
#if defined (iHaveNativeMenus)
/* Using native menus. */
static const iMenuItem fileMenuItems_[] = {
{ "${menu.newtab}", SDLK_t, KMOD_PRIMARY, "tabs.new" },
{ "${menu.openlocation}", SDLK_l, KMOD_PRIMARY, "navigate.focus" },
{ "---", 0, 0, NULL },
{ saveToDownloads_Label, SDLK_s, KMOD_PRIMARY, "document.save" },
{ "---", 0, 0, NULL },
{ "${menu.downloads}", 0, 0, "downloads.open" },
};
static const iMenuItem editMenuItems_[] = {
{ "${menu.cut}", SDLK_x, KMOD_PRIMARY, "input.copy cut:1" },
{ "${menu.copy}", SDLK_c, KMOD_PRIMARY, "copy" },
{ "${menu.paste}", SDLK_v, KMOD_PRIMARY, "input.paste" },
{ "---", 0, 0, NULL },
{ "${menu.copy.pagelink}", SDLK_c, KMOD_PRIMARY | KMOD_SHIFT, "document.copylink" },
{ "---", 0, 0, NULL },
{ "${macos.menu.find}", SDLK_f, KMOD_PRIMARY, "focus.set id:find.input" },
};
static const iMenuItem viewMenuItems_[] = {
{ "${menu.show.bookmarks}", '1', KMOD_PRIMARY, "sidebar.mode arg:0 toggle:1" },
{ "${menu.show.feeds}", '2', KMOD_PRIMARY, "sidebar.mode arg:1 toggle:1" },
{ "${menu.show.history}", '3', KMOD_PRIMARY, "sidebar.mode arg:2 toggle:1" },
{ "${menu.show.identities}", '4', KMOD_PRIMARY, "sidebar.mode arg:3 toggle:1" },
{ "${menu.show.outline}", '5', KMOD_PRIMARY, "sidebar.mode arg:4 toggle:1" },
{ "${menu.sidebar.left}", SDLK_l, KMOD_PRIMARY | KMOD_SHIFT, "sidebar.toggle" },
{ "${menu.sidebar.right}", SDLK_p, KMOD_PRIMARY | KMOD_SHIFT, "sidebar2.toggle" },
{ "---", 0, 0, NULL },
{ "${menu.back}", SDLK_LEFTBRACKET, KMOD_PRIMARY, "navigate.back" },
{ "${menu.forward}", SDLK_RIGHTBRACKET, KMOD_PRIMARY, "navigate.forward" },
{ "${menu.parent}", navigateParent_KeyShortcut, "navigate.parent" },
{ "${menu.root}", navigateRoot_KeyShortcut, "navigate.root" },
{ "${menu.reload}", reload_KeyShortcut, "navigate.reload" },
{ "---", 0, 0, NULL },
{ "${menu.zoom.in}", SDLK_EQUALS, KMOD_PRIMARY, "zoom.delta arg:10" },
{ "${menu.zoom.out}", SDLK_MINUS, KMOD_PRIMARY, "zoom.delta arg:-10" },
{ "${menu.zoom.reset}", SDLK_0, KMOD_PRIMARY, "zoom.set arg:100" },
{ "${menu.view.split}", SDLK_j, KMOD_PRIMARY, "splitmenu.open" },
};
static iMenuItem bookmarksMenuItems_[] = {
{ "${menu.page.bookmark}", SDLK_d, KMOD_PRIMARY, "bookmark.add" },
{ "${menu.page.subscribe}", subscribeToPage_KeyModifier, "feeds.subscribe" },
{ "---", 0, 0, NULL },
{ "${menu.import.links}", 0, 0, "bookmark.links confirm:1" },
{ "---", 0, 0, NULL },
{ "${macos.menu.bookmarks.list}", 0, 0, "open url:about:bookmarks" },
{ "${macos.menu.bookmarks.bytag}", 0, 0, "open url:about:bookmarks?tags" },
{ "${macos.menu.bookmarks.bytime}", 0, 0, "open url:about:bookmarks?created" },
{ "${menu.feeds.entrylist}", 0, 0, "open url:about:feeds" },
{ "---", 0, 0, NULL },
{ "${menu.bookmarks.refresh}", 0, 0, "bookmarks.reload.remote" },
{ "${menu.feeds.refresh}", SDLK_r, KMOD_PRIMARY | KMOD_SHIFT, "feeds.refresh" },
};
static const iMenuItem identityMenuItems_[] = {
{ "${menu.identity.new}", SDLK_n, KMOD_PRIMARY | KMOD_SHIFT, "ident.new" },
{ "---", 0, 0, NULL },
{ "${menu.identity.import}", SDLK_i, KMOD_PRIMARY | KMOD_SHIFT, "ident.import" },
};
static const iMenuItem helpMenuItems_[] = {
{ "${menu.help}", 0, 0, "!open url:about:help" },
{ "${menu.releasenotes}", 0, 0, "!open url:about:version" },
{ "---", 0, 0, NULL },
{ "${menu.aboutpages}", 0, 0, "!open url:about:about" },
{ "${menu.debug}", 0, 0, "!open url:about:debug" },
};
static void insertMacMenus_(void) {
insertMenuItems_MacOS("${menu.title.file}", 1, fileMenuItems_, iElemCount(fileMenuItems_));
insertMenuItems_MacOS("${menu.title.edit}", 2, editMenuItems_, iElemCount(editMenuItems_));
insertMenuItems_MacOS("${menu.title.view}", 3, viewMenuItems_, iElemCount(viewMenuItems_));
insertMenuItems_MacOS("${menu.title.bookmarks}", 4, bookmarksMenuItems_, iElemCount(bookmarksMenuItems_));
insertMenuItems_MacOS("${menu.title.identity}", 5, identityMenuItems_, iElemCount(identityMenuItems_));
insertMenuItems_MacOS("${menu.title.help}", 7, helpMenuItems_, iElemCount(helpMenuItems_));
}
static void removeMacMenus_(void) {
removeMenu_MacOS(7);
removeMenu_MacOS(5);
removeMenu_MacOS(4);
removeMenu_MacOS(3);
removeMenu_MacOS(2);
removeMenu_MacOS(1);
}
#endif
int numRoots_Window(const iWindow *d) {
int num = 0;
iForIndices(i, d->roots) {
if (d->roots[i]) num++;
}
return num;
}
static void windowSizeChanged_Window_(iWindow *d) {
const int numRoots = numRoots_Window(d);
const iInt2 rootSize = d->size;
const int weights[2] = {
d->roots[0] ? (d->splitMode & twoToOne_WindowSplit ? 2 : 1) : 0,
d->roots[1] ? (d->splitMode & oneToTwo_WindowSplit ? 2 : 1) : 0,
};
const int totalWeight = weights[0] + weights[1];
int w = 0;
iForIndices(i, d->roots) {
iRoot *root = d->roots[i];
if (root) {
iRect *rect = &root->widget->rect;
/* Horizontal split frame. */
if (d->splitMode & vertical_WindowSplit) {
rect->pos = init_I2(0, rootSize.y * w / totalWeight);
rect->size = init_I2(rootSize.x, rootSize.y * (w + weights[i]) / totalWeight - rect->pos.y);
}
else {
rect->pos = init_I2(rootSize.x * w / totalWeight, 0);
rect->size = init_I2(rootSize.x * (w + weights[i]) / totalWeight - rect->pos.x, rootSize.y);
}
w += weights[i];
root->widget->minSize = rect->size;
updatePadding_Root(root);
arrange_Widget(root->widget);
}
}
}
static void setupUserInterface_Window(iWindow *d) {
#if defined (iHaveNativeMenus)
insertMacMenus_();
#endif
/* One root is created by default. */
d->roots[0] = new_Root();
setCurrent_Root(d->roots[0]);
createUserInterface_Root(d->roots[0]);
setCurrent_Root(NULL);
/* One of the roots always has keyboard input focus. */
d->keyRoot = d->roots[0];
}
static void updateSize_Window_(iWindow *d, iBool notifyAlways) {
iInt2 *size = &d->size;
const iInt2 oldSize = *size;
SDL_GetRendererOutputSize(d->render, &size->x, &size->y);
size->y -= d->keyboardHeight;
if (notifyAlways || !isEqual_I2(oldSize, *size)) {
windowSizeChanged_Window_(d);
if (!isEqual_I2(*size, d->place.lastNotifiedSize)) {
const iBool isHoriz = (d->place.lastNotifiedSize.x != size->x);
const iBool isVert = (d->place.lastNotifiedSize.y != size->y);
postCommandf_App("window.resized width:%d height:%d horiz:%d vert:%d",
size->x,
size->y,
isHoriz,
isVert);
postCommand_App("widget.overflow"); /* check bounds with updated sizes */
}
postRefresh_App();
d->place.lastNotifiedSize = *size;
}
}
void drawWhileResizing_Window(iWindow *d, int w, int h) {
draw_Window(d);
}
static float pixelRatio_Window_(const iWindow *d) {
int dx, x;
SDL_GetRendererOutputSize(d->render, &dx, NULL);
SDL_GetWindowSize(d->win, &x, NULL);
return (float) dx / (float) x;
}
#if defined (iPlatformApple)
# define baseDPI_Window 113.5f
#else
# define baseDPI_Window 96.0f
#endif
static float displayScale_Window_(const iWindow *d) {
/* The environment variable LAGRANGE_OVERRIDE_DPI can be used to override the automatic
display DPI detection. If not set, or is an empty string, ignore it.
Note: the same value used for all displays. */
const char *LAGRANGE_OVERRIDE_DPI = getenv("LAGRANGE_OVERRIDE_DPI");
if (LAGRANGE_OVERRIDE_DPI && *LAGRANGE_OVERRIDE_DPI) {
/* If the user has set the env var, but it is not an int, atoi */
/* will return 0, in which case we just guess and return 96 DPI. */
const int envDpi = atoi(LAGRANGE_OVERRIDE_DPI);
if (envDpi > 0) {
return ((float) envDpi) / baseDPI_Window;
}
fprintf(stderr, "[Window] WARNING: failed to parse LAGRANGE_OVERRIDE_DPI='%s', "
"ignoring it\n", LAGRANGE_OVERRIDE_DPI);
/* To avoid showing the warning multiple times, overwrite
LAGRANGE_OVERRIDE_DPI with the empty string. */
setenv("LAGRANGE_OVERRIDE_DPI", "", 1);
}
#if defined (iPlatformApple)
iUnused(d);
/* Apple UI sizes are fixed and only scaled by pixel ratio. */
/* TODO: iOS text size setting? */
return 1.0f;
#elif defined (iPlatformMsys)
iUnused(d);
return desktopDPI_Win32();
#else
if (isRunningUnderWindowSystem_App()) {
float vdpi = 0.0f;
SDL_GetDisplayDPI(SDL_GetWindowDisplayIndex(d->win), NULL, NULL, &vdpi);
// printf("DPI: %f\n", vdpi);
const float factor = vdpi / baseDPI_Window / pixelRatio_Window_(d);
return iMax(1.0f, factor);
}
return 1.0f;
#endif
}
static void drawBlank_Window_(iWindow *d) {
// const iColor bg = get_Color(uiBackground_ColorId);
const iColor bg = { 128, 128, 128, 255 }; /* TODO: Have no root yet. */
SDL_SetRenderDrawColor(d->render, bg.r, bg.g, bg.b, 255);
SDL_RenderClear(d->render);
SDL_RenderPresent(d->render);
}
static iRoot *rootAt_Window_(const iWindow *d, iInt2 coord) {
iForIndices(i, d->roots) {
iRoot *root = d->roots[i];
if (root && contains_Rect(rect_Root(root), coord)) {
return root;
}
}
return d->roots[0];
}
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
static SDL_HitTestResult hitTest_Window_(SDL_Window *win, const SDL_Point *pos, void *data) {
iWindow *d = data;
iAssert(d->win == win);
if (SDL_GetWindowFlags(d->win) & (SDL_WINDOW_MOUSE_CAPTURE | SDL_WINDOW_FULLSCREEN_DESKTOP)) {
return SDL_HITTEST_NORMAL;
}
const int snap = snap_Window(d);
int w, h;
SDL_GetWindowSize(win, &w, &h);
/* TODO: Check if inside the caption label widget. */
const iBool isLeft = pos->x < gap_UI;
const iBool isRight = pos->x >= w - gap_UI;
const iBool isTop = pos->y < gap_UI && snap != yMaximized_WindowSnap;
const iBool isBottom = pos->y >= h - gap_UI && snap != yMaximized_WindowSnap;
const int captionHeight = lineHeight_Text(uiContent_FontId) + gap_UI * 2;
const int rightEdge = left_Rect(bounds_Widget(findChild_Widget(
rootAt_Window_(d, init_I2(pos->x, pos->y))->widget,
"winbar.min")));
d->place.lastHit = SDL_HITTEST_NORMAL;
if (snap != maximized_WindowSnap) {
if (isLeft) {
return pos->y < captionHeight ? SDL_HITTEST_RESIZE_TOPLEFT
: pos->y > h - captionHeight ? SDL_HITTEST_RESIZE_BOTTOMLEFT
: (d->place.lastHit = SDL_HITTEST_RESIZE_LEFT);
}
if (isRight) {
return pos->y < captionHeight ? SDL_HITTEST_RESIZE_TOPRIGHT
: pos->y > h - captionHeight ? SDL_HITTEST_RESIZE_BOTTOMRIGHT
: (d->place.lastHit = SDL_HITTEST_RESIZE_RIGHT);
}
if (isTop) {
return pos->x < captionHeight ? SDL_HITTEST_RESIZE_TOPLEFT
: pos->x > w - captionHeight ? SDL_HITTEST_RESIZE_TOPRIGHT
: (d->place.lastHit = SDL_HITTEST_RESIZE_TOP);
}
if (isBottom) {
return pos->x < captionHeight ? SDL_HITTEST_RESIZE_BOTTOMLEFT
: pos->x > w - captionHeight ? SDL_HITTEST_RESIZE_BOTTOMRIGHT
: (d->place.lastHit = SDL_HITTEST_RESIZE_BOTTOM);
}
}
if (pos->x < rightEdge && pos->y < captionHeight) {
return SDL_HITTEST_DRAGGABLE;
}
return SDL_HITTEST_NORMAL;
}
SDL_HitTestResult hitTest_Window(const iWindow *d, iInt2 pos) {
return hitTest_Window_(d->win, &(SDL_Point){ pos.x, pos.y }, iConstCast(void *, d));
}
#endif
iBool create_Window_(iWindow *d, iRect rect, uint32_t flags) {
flags |= SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_HIDDEN;
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
if (prefs_App()->customFrame) {
/* We are drawing a custom frame so hide the default one. */
flags |= SDL_WINDOW_BORDERLESS;
}
#endif
if (SDL_CreateWindowAndRenderer(
width_Rect(rect), height_Rect(rect), flags, &d->win, &d->render)) {
return iFalse;
}
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
if (prefs_App()->customFrame) {
/* Register a handler for window hit testing (drag, resize). */
SDL_SetWindowHitTest(d->win, hitTest_Window_, d);
SDL_SetWindowResizable(d->win, SDL_TRUE);
}
#endif
return iTrue;
}
static SDL_Surface *loadImage_(const iBlock *data, int resized) {
int w = 0, h = 0, num = 4;
stbi_uc *pixels = stbi_load_from_memory(
constData_Block(data), size_Block(data), &w, &h, &num, STBI_rgb_alpha);
if (resized) {
stbi_uc *rsPixels = malloc(num * resized * resized);
stbir_resize_uint8(pixels, w, h, 0, rsPixels, resized, resized, 0, num);
free(pixels);
pixels = rsPixels;
w = h = resized;
}
return SDL_CreateRGBSurfaceWithFormatFrom(
pixels, w, h, 8 * num, w * num, SDL_PIXELFORMAT_RGBA32);
}
void init_Window(iWindow *d, iRect rect) {
theWindow_ = d;
d->win = NULL;
d->size = zero_I2(); /* will be updated below */
iZap(d->roots);
d->splitMode = d->pendingSplitMode = 0;
d->pendingSplitUrl = new_String();
d->hover = NULL;
d->mouseGrab = NULL;
d->focus = NULL;
iZap(d->cursors);
d->place.initialPos = rect.pos;
d->place.normalRect = rect;
d->place.lastNotifiedSize = zero_I2();
d->place.snap = 0;
d->pendingCursor = NULL;
d->isDrawFrozen = iTrue;
d->isExposed = iFalse;
d->isMinimized = iFalse;
d->isInvalidated = iFalse; /* set when posting event, to avoid repeated events */
d->isMouseInside = iTrue;
d->ignoreClick = iFalse;
d->focusGainedAt = 0;
d->keyboardHeight = 0;
init_Anim(&d->rootOffset, 0.0f);
uint32_t flags = 0;
#if defined (iPlatformAppleDesktop)
SDL_SetHint(SDL_HINT_RENDER_DRIVER, shouldDefaultToMetalRenderer_MacOS() ? "metal" : "opengl");
#elif defined (iPlatformAppleMobile)
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal");
#else
flags |= SDL_WINDOW_OPENGL;
#endif
SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1");
/* First try SDL's default renderer that should be the best option. */
if (forceSoftwareRender_App() || !create_Window_(d, rect, flags)) {
/* No luck, maybe software only? This should always work as long as there is a display. */
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "software");
if (!create_Window_(d, rect, 0)) {
fprintf(stderr, "Error when creating window: %s\n", SDL_GetError());
exit(-2);
}
}
if (left_Rect(rect) >= 0 || top_Rect(rect) >= 0) {
SDL_SetWindowPosition(d->win, left_Rect(rect), top_Rect(rect));
}
#if defined (iPlatformMobile)
const iInt2 minSize = zero_I2(); /* windows aren't independently resizable */
#else
const iInt2 minSize = init_I2(425, 325);
#endif
SDL_SetWindowMinimumSize(d->win, minSize.x, minSize.y);
SDL_SetWindowTitle(d->win, "Lagrange");
/* Some info. */ {
SDL_RendererInfo info;
SDL_GetRendererInfo(d->render, &info);
isOpenGLRenderer_ = !iCmpStr(info.name, "opengl");
printf("[window] renderer: %s%s\n", info.name,
info.flags & SDL_RENDERER_ACCELERATED ? " (accelerated)" : "");
#if !defined (NDEBUG)
printf("[window] max texture size: %d x %d\n",
info.max_texture_width,
info.max_texture_height);
for (size_t i = 0; i < info.num_texture_formats; ++i) {
printf("[window] supported texture format: %s\n", SDL_GetPixelFormatName(
info.texture_formats[i]));
}
#endif
}
drawBlank_Window_(d);
d->pixelRatio = pixelRatio_Window_(d); /* point/pixel conversion */
d->displayScale = displayScale_Window_(d);
d->uiScale = initialUiScale_;
setScale_Metrics(d->pixelRatio * d->displayScale * d->uiScale);
#if defined (iPlatformMsys)
SDL_SetWindowMinimumSize(d->win, minSize.x * d->displayScale, minSize.y * d->displayScale);
useExecutableIconResource_SDLWindow(d->win);
#endif
#if defined (iPlatformLinux)
SDL_SetWindowMinimumSize(d->win, minSize.x * d->pixelRatio, minSize.y * d->pixelRatio);
/* Load the window icon. */ {
SDL_Surface *surf = loadImage_(&imageLagrange64_Embedded, 0);
SDL_SetWindowIcon(d->win, surf);
free(surf->pixels);
SDL_FreeSurface(surf);
}
#endif
#if defined (iPlatformAppleMobile)
setupWindow_iOS(d);
#endif
d->presentTime = 0.0;
d->frameTime = SDL_GetTicks();
d->loadAnimTimer = 0;
init_Text(d->render);
SDL_GetRendererOutputSize(d->render, &d->size.x, &d->size.y);
setupUserInterface_Window(d);
postCommand_App("~bindings.changed"); /* update from bindings */
//updateSize_Window_(d, iFalse);
/* Load the border shadow texture. */ {
SDL_Surface *surf = loadImage_(&imageShadow_Embedded, 0);
d->borderShadow = SDL_CreateTextureFromSurface(d->render, surf);
SDL_SetTextureBlendMode(d->borderShadow, SDL_BLENDMODE_BLEND);
free(surf->pixels);
SDL_FreeSurface(surf);
}
d->appIcon = NULL;
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
/* Load the app icon for drawing in the title bar. */
if (prefs_App()->customFrame) {
SDL_Surface *surf = loadImage_(&imageLagrange64_Embedded, appIconSize_Root());
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
d->appIcon = SDL_CreateTextureFromSurface(d->render, surf);
free(surf->pixels);
SDL_FreeSurface(surf);
/* We need to observe non-client-area events. */
SDL_EventState(SDL_SYSWMEVENT, SDL_TRUE);
}
#endif
}
void deinit_Window(iWindow *d) {
iRecycle();
iForIndices(i, d->roots) {
if (d->roots[i]) {
setCurrent_Root(d->roots[i]);
deinit_Root(d->roots[i]);
}
}
if (theWindow_ == d) {
theWindow_ = NULL;
}
setCurrent_Root(NULL);
delete_String(d->pendingSplitUrl);
deinit_Text();
SDL_DestroyRenderer(d->render);
SDL_DestroyWindow(d->win);
iForIndices(i, d->cursors) {
if (d->cursors[i]) {
SDL_FreeCursor(d->cursors[i]);
}
}
}
SDL_Renderer *renderer_Window(const iWindow *d) {
return d->render;
}
iInt2 maxTextureSize_Window(const iWindow *d) {
SDL_RendererInfo info;
SDL_GetRendererInfo(d->render, &info);
return init_I2(info.max_texture_width, info.max_texture_height);
}
iBool isFullscreen_Window(const iWindow *d) {
return snap_Window(d) == fullscreen_WindowSnap;
}
iRoot *findRoot_Window(const iWindow *d, const iWidget *widget) {
while (widget->parent) {
widget = widget->parent;
}
iForIndices(i, d->roots) {
if (d->roots[i] && d->roots[i]->widget == widget) {
return d->roots[i];
}
}
return NULL;
}
iRoot *otherRoot_Window(const iWindow *d, iRoot *root) {
return root == d->roots[0] && d->roots[1] ? d->roots[1] : d->roots[0];
}
static void invalidate_Window_(iWindow *d, iBool forced) {
if (d && (!d->isInvalidated || forced)) {
d->isInvalidated = iTrue;
resetFonts_Text();
postCommand_App("theme.changed auto:1"); /* forces UI invalidation */
}
}
void invalidate_Window(iWindow *d) {
invalidate_Window_(d, iFalse);
}
static iBool isNormalPlacement_Window_(const iWindow *d) {
if (d->isDrawFrozen) return iFalse;
#if defined (iPlatformApple)
/* Maximized mode is not special on macOS. */
if (snap_Window(d) == maximized_WindowSnap) {
return iTrue;
}
#endif
if (snap_Window(d)) return iFalse;
return !(SDL_GetWindowFlags(d->win) & SDL_WINDOW_MINIMIZED);
}
static iBool unsnap_Window_(iWindow *d, const iInt2 *newPos) {
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
if (!prefs_App()->customFrame) {
return iFalse;
}
const int snap = snap_Window(d);
if (snap == yMaximized_WindowSnap || snap == left_WindowSnap || snap == right_WindowSnap) {
if (!newPos || (d->place.lastHit == SDL_HITTEST_RESIZE_LEFT ||
d->place.lastHit == SDL_HITTEST_RESIZE_RIGHT)) {
return iFalse;
}
if (newPos) {
SDL_Rect usable;
SDL_GetDisplayUsableBounds(SDL_GetWindowDisplayIndex(d->win), &usable);
/* Snap to top. */
if (snap == yMaximized_WindowSnap &&
iAbs(newPos->y - usable.y) < lineHeight_Text(uiContent_FontId) * 2) {
setSnap_Window(d, redo_WindowSnap | yMaximized_WindowSnap);
return iFalse;
}
}
}
if (snap && snap != fullscreen_WindowSnap) {
if (snap_Window(d) == yMaximized_WindowSnap && newPos) {
d->place.normalRect.pos = *newPos;
}
//printf("unsnap\n"); fflush(stdout);
setSnap_Window(d, none_WindowSnap);
return iTrue;
}
#endif
return iFalse;
}
static void notifyMetricsChange_Window_(const iWindow *d) {
/* Dynamic UI metrics change. Widgets need to update themselves. */
setScale_Metrics(d->pixelRatio * d->displayScale * d->uiScale);
resetFonts_Text();
postCommand_App("metrics.changed");
}
static void checkPixelRatioChange_Window_(iWindow *d) {
iBool wasChanged = iFalse;
const float ratio = pixelRatio_Window_(d);
if (iAbs(ratio - d->pixelRatio) > 0.001f) {
d->pixelRatio = ratio;
wasChanged = iTrue;
}
const float scale = displayScale_Window_(d);
if (iAbs(scale - d->displayScale) > 0.001f) {
d->displayScale = scale;
wasChanged = iTrue;
}
if (wasChanged) {
notifyMetricsChange_Window_(d);
}
}
static iBool handleWindowEvent_Window_(iWindow *d, const SDL_WindowEvent *ev) {
switch (ev->event) {
#if defined (iPlatformDesktop)
case SDL_WINDOWEVENT_EXPOSED:
if (!d->isExposed) {
drawBlank_Window_(d); /* avoid showing system-provided contents */
d->isExposed = iTrue;
}
/* Since we are manually controlling when to redraw the window, we are responsible
for ensuring that window contents get redrawn after expose events. Under certain
circumstances (e.g., under openbox), not doing this would mean that the window
is missing contents until other events trigger a refresh. */
postRefresh_App();
#if defined (LAGRANGE_ENABLE_WINDOWPOS_FIX)
if (d->place.initialPos.x >= 0) {
int bx, by;
SDL_GetWindowBordersSize(d->win, &by, &bx, NULL, NULL);
SDL_SetWindowPosition(d->win, d->place.initialPos.x + bx, d->place.initialPos.y + by);
d->place.initialPos = init1_I2(-1);
}
#endif
return iFalse;
case SDL_WINDOWEVENT_MOVED: {
if (d->isMinimized) {
return iFalse;
}
checkPixelRatioChange_Window_(d);
const iInt2 newPos = init_I2(ev->data1, ev->data2);
if (isEqual_I2(newPos, init1_I2(-32000))) { /* magic! */
/* Maybe minimized? Seems like a Windows constant of some kind. */
d->isMinimized = iTrue;
return iFalse;
}
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
/* Set the snap position depending on where the mouse cursor is. */
if (prefs_App()->customFrame) {
SDL_Rect usable;
iInt2 mouse = cursor_Win32(); /* SDL is unaware of the current cursor pos */
SDL_GetDisplayUsableBounds(SDL_GetWindowDisplayIndex(d->win), &usable);
const iBool isTop = iAbs(mouse.y - usable.y) < gap_UI * 20;
const iBool isBottom = iAbs(usable.y + usable.h - mouse.y) < gap_UI * 20;
if (iAbs(mouse.x - usable.x) < gap_UI) {
setSnap_Window(d,
redo_WindowSnap | left_WindowSnap |
(isTop ? topBit_WindowSnap : 0) |
(isBottom ? bottomBit_WindowSnap : 0));
return iTrue;
}
if (iAbs(mouse.x - usable.x - usable.w) < gap_UI) {
setSnap_Window(d,
redo_WindowSnap | right_WindowSnap |
(isTop ? topBit_WindowSnap : 0) |
(isBottom ? bottomBit_WindowSnap : 0));
return iTrue;
}
if (iAbs(mouse.y - usable.y) < 2) {
setSnap_Window(d,
redo_WindowSnap | (d->place.lastHit == SDL_HITTEST_RESIZE_TOP
? yMaximized_WindowSnap
: maximized_WindowSnap));
return iTrue;
}
}
#endif /* defined LAGRANGE_ENABLE_CUSTOM_FRAME */
if (unsnap_Window_(d, &newPos)) {
return iTrue;
}
if (isNormalPlacement_Window_(d)) {
d->place.normalRect.pos = newPos;
//printf("normal rect set (move)\n"); fflush(stdout);
iInt2 border = zero_I2();
#if !defined (iPlatformApple)
SDL_GetWindowBordersSize(d->win, &border.y, &border.x, NULL, NULL);
#endif
d->place.normalRect.pos = max_I2(zero_I2(), sub_I2(d->place.normalRect.pos, border));
}
return iTrue;
}
case SDL_WINDOWEVENT_RESIZED:
if (d->isMinimized) {
//updateSize_Window_(d, iTrue);
return iTrue;
}
if (unsnap_Window_(d, NULL)) {
return iTrue;
}
if (isNormalPlacement_Window_(d)) {
d->place.normalRect.size = init_I2(ev->data1, ev->data2);
//printf("normal rect set (resize)\n"); fflush(stdout);
}
checkPixelRatioChange_Window_(d);
//updateSize_Window_(d, iTrue /* we were already redrawing during the resize */);
postRefresh_App();
return iTrue;
case SDL_WINDOWEVENT_RESTORED:
case SDL_WINDOWEVENT_SHOWN:
updateSize_Window_(d, iTrue);
invalidate_Window_(d, iTrue);
d->isMinimized = iFalse;
postRefresh_App();
return iTrue;
case SDL_WINDOWEVENT_MINIMIZED:
d->isMinimized = iTrue;
return iTrue;
#else /* if defined (!iPlatformDesktop) */
case SDL_WINDOWEVENT_RESIZED:
/* On mobile, this occurs when the display is rotated. */
invalidate_Window(d);
postRefresh_App();
return iTrue;
#endif
case SDL_WINDOWEVENT_LEAVE:
unhover_Widget();
d->isMouseInside = iFalse;
postCommand_App("window.mouse.exited");
return iTrue;
case SDL_WINDOWEVENT_ENTER:
d->isMouseInside = iTrue;
postCommand_App("window.mouse.entered");
return iTrue;
case SDL_WINDOWEVENT_FOCUS_GAINED:
d->focusGainedAt = SDL_GetTicks();
setCapsLockDown_Keys(iFalse);
postCommand_App("window.focus.gained");
d->isExposed = iTrue;
#if !defined (iPlatformDesktop)
/* Returned to foreground, may have lost buffered content. */
invalidate_Window_(d, iTrue);
postCommand_App("window.unfreeze");
#endif
return iFalse;
case SDL_WINDOWEVENT_FOCUS_LOST:
postCommand_App("window.focus.lost");
#if !defined (iPlatformDesktop)
setFreezeDraw_Window(d, iTrue);
#endif
return iFalse;
case SDL_WINDOWEVENT_TAKE_FOCUS:
SDL_SetWindowInputFocus(d->win);
postRefresh_App();
return iTrue;
default:
break;
}
return iFalse;
}
static void applyCursor_Window_(iWindow *d) {
if (d->pendingCursor) {
SDL_SetCursor(d->pendingCursor);
d->pendingCursor = NULL;
}
}
iBool processEvent_Window(iWindow *d, const SDL_Event *ev) {
switch (ev->type) {
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
case SDL_SYSWMEVENT: {
/* We observe native Win32 messages for better user interaction with the
window frame. Mouse clicks especially will not generate normal SDL
events if they happen on the custom hit-tested regions. These events
are processed only there; the UI widgets do not get involved. */
processNativeEvent_Win32(ev->syswm.msg, d);
break;
}
#endif
case SDL_WINDOWEVENT: {
return handleWindowEvent_Window_(d, &ev->window);
}
case SDL_RENDER_TARGETS_RESET:
case SDL_RENDER_DEVICE_RESET: {
invalidate_Window_(d, iTrue /* force full reset */);
break;
}
default: {
SDL_Event event = *ev;
if (event.type == SDL_USEREVENT && isCommand_UserEvent(ev, "window.unfreeze")) {
d->isDrawFrozen = iFalse;
if (SDL_GetWindowFlags(d->win) & SDL_WINDOW_HIDDEN) {
SDL_ShowWindow(d->win);
}
postRefresh_App();
postCommand_App("media.player.update"); /* in case a player needs updating */
return iTrue;
}
if (processEvent_Touch(&event)) {
return iTrue;
}
if (event.type == SDL_KEYDOWN && SDL_GetTicks() - d->focusGainedAt < 10) {
/* Suspiciously close to when input focus was received. For example under openbox,
closing xterm with Ctrl+D will cause the keydown event to "spill" over to us.
As a workaround, ignore these events. */
return iTrue; /* won't go to bindings, either */
}
if (event.type == SDL_MOUSEBUTTONDOWN && d->ignoreClick) {
d->ignoreClick = iFalse;
return iTrue;
}
/* Map mouse pointer coordinate to our coordinate system. */
if (event.type == SDL_MOUSEMOTION) {
setCursor_Window(d, SDL_SYSTEM_CURSOR_ARROW); /* default cursor */
const iInt2 pos = coord_Window(d, event.motion.x, event.motion.y);
event.motion.x = pos.x;
event.motion.y = pos.y;
}
else if (event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEBUTTONDOWN) {
const iInt2 pos = coord_Window(d, event.button.x, event.button.y);
event.button.x = pos.x;
event.button.y = pos.y;
if (event.type == SDL_MOUSEBUTTONDOWN) {
/* Button clicks will change keyroot. */
if (numRoots_Window(d) > 1) {
const iInt2 click = init_I2(event.button.x, event.button.y);
iForIndices(i, d->roots) {
iRoot *root = d->roots[i];
if (root != d->keyRoot && contains_Rect(rect_Root(root), click)) {
setKeyRoot_Window(d, root);
break;
}
}
}
}
}
const iWidget *oldHover = d->hover;
iBool wasUsed = iFalse;
/* Dispatch first to the mouse-grabbed widget. */
// iWidget *widget = d->root.widget;
if (event.type == SDL_MOUSEMOTION || event.type == SDL_MOUSEWHEEL ||
event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEBUTTONDOWN) {
if (mouseGrab_Widget()) {
iWidget *grabbed = mouseGrab_Widget();
setCurrent_Root(findRoot_Window(d, grabbed));
wasUsed = dispatchEvent_Widget(grabbed, &event);
}
}
/* Dispatch the event to the tree of widgets. */
if (!wasUsed) {
wasUsed = dispatchEvent_Window(d, &event);
}
if (!wasUsed) {
/* As a special case, clicking the middle mouse button can be used for pasting
from the clipboard. */
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_MIDDLE) {
SDL_Event paste;
iZap(paste);
paste.type = SDL_KEYDOWN;
paste.key.keysym.sym = SDLK_v;
paste.key.keysym.mod = KMOD_PRIMARY;
paste.key.state = SDL_PRESSED;
paste.key.timestamp = SDL_GetTicks();
wasUsed = dispatchEvent_Window(d, &paste);
}
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_RIGHT) {
if (postContextClick_Window(d, &event.button)) {
wasUsed = iTrue;
}
}
}
if (isMetricsChange_UserEvent(&event)) {
iForIndices(i, d->roots) {
updateMetrics_Root(d->roots[i]);
}
}
if (isCommand_UserEvent(&event, "lang.changed")) {
#if defined (iHaveNativeMenus)
/* Retranslate the menus. */
removeMacMenus_();
insertMacMenus_();
#endif
invalidate_Window(d);
iForIndices(i, d->roots) {
if (d->roots[i]) {
updatePreferencesLayout_Widget(findChild_Widget(d->roots[i]->widget, "prefs"));
arrange_Widget(d->roots[i]->widget);
}
}
}
if (oldHover != d->hover) {
postRefresh_App();
}
if (event.type == SDL_MOUSEMOTION) {
applyCursor_Window_(d);
}
return wasUsed;
}
}
return iFalse;
}
iBool setKeyRoot_Window(iWindow *d, iRoot *root) {
if (d->keyRoot != root) {
d->keyRoot = root;
postCommand_App("keyroot.changed");
postRefresh_App();
return iTrue;
}
return iFalse;
}
iLocalDef iBool isEscapeKeypress_(const SDL_Event *ev) {
return (ev->type == SDL_KEYDOWN || ev->type == SDL_KEYUP) && ev->key.keysym.sym == SDLK_ESCAPE;
}
iBool dispatchEvent_Window(iWindow *d, const SDL_Event *ev) {
if (ev->type == SDL_MOUSEMOTION) {
/* Hover widget may change. */
setHover_Widget(NULL);
}
iRoot *order[2];
rootOrder_App(order);
iForIndices(i, order) {
iRoot *root = order[i];
if (root) {
if (isCommand_SDLEvent(ev) && ev->user.data2 && ev->user.data2 != root) {
continue; /* Not meant for this root. */
}
if ((ev->type == SDL_KEYDOWN || ev->type == SDL_KEYUP || ev->type == SDL_TEXTINPUT)
&& d->keyRoot != root) {
if (!isEscapeKeypress_(ev)) {
/* Key events go only to the root with keyboard focus, with the exception
of Escape that will also affect the entire window. */
continue;
}
}
if (ev->type == SDL_MOUSEWHEEL && !contains_Rect(rect_Root(root),
coord_MouseWheelEvent(&ev->wheel))) {
continue; /* Only process the event in the relevant split. */
}
setCurrent_Root(root);
const iBool wasUsed = dispatchEvent_Widget(root->widget, ev);
if (wasUsed) {
if (ev->type == SDL_MOUSEBUTTONDOWN ||
ev->type == SDL_MOUSEWHEEL) {
setKeyRoot_Window(d, root);
}
return iTrue;
}
}
}
return iFalse;
}
iAnyObject *hitChild_Window(const iWindow *d, iInt2 coord) {
iForIndices(i, d->roots) {
if (d->roots[i]) {
iAnyObject *hit = hitChild_Widget(d->roots[i]->widget, coord);
if (hit) {
return hit;
}
}
}
return NULL;
}
iBool postContextClick_Window(iWindow *d, const SDL_MouseButtonEvent *ev) {
/* A context menu may still get triggered here. */
const iWidget *hit = hitChild_Window(d, init_I2(ev->x, ev->y));
while (hit && isEmpty_String(id_Widget(hit))) {
hit = parent_Widget(hit);
}
if (hit) {
postCommandf_App("contextclick id:%s ptr:%p coord:%d %d",
cstr_String(id_Widget(hit)), hit,
ev->x, ev->y);
return iTrue;
}
return iFalse;
}
void draw_Window(iWindow *d) {
if (d->isDrawFrozen) {
return;
}
/* Check if root needs resizing. */ {
iInt2 renderSize;
SDL_GetRendererOutputSize(d->render, &renderSize.x, &renderSize.y);
if (!isEqual_I2(renderSize, d->size)) {
updateSize_Window_(d, iTrue);
processEvents_App(postedEventsOnly_AppEventMode);
}
}
const int winFlags = SDL_GetWindowFlags(d->win);
const iBool gotFocus = (winFlags & SDL_WINDOW_INPUT_FOCUS) != 0;
iPaint p;
init_Paint(&p);
/* Clear the window. The clear color is visible as a border around the window
when the custom frame is being used. */ {
setCurrent_Root(d->roots[0]);
#if defined (iPlatformMobile)
iColor back = get_Color(uiBackground_ColorId);
if (deviceType_App() == phone_AppDeviceType) {
/* Page background extends to safe area, so fill it completely. */
back = get_Color(tmBackground_ColorId);
}
#else
const iColor back = get_Color(gotFocus && d->place.snap != maximized_WindowSnap &&
~winFlags & SDL_WINDOW_FULLSCREEN_DESKTOP
? uiAnnotation_ColorId
: uiSeparator_ColorId);
#endif
unsetClip_Paint(&p); /* update clip to full window */
SDL_SetRenderDrawColor(d->render, back.r, back.g, back.b, 255);
SDL_RenderClear(d->render);
}
/* Draw widgets. */
d->frameTime = SDL_GetTicks();
if (isExposed_Window(d)) {
d->isInvalidated = iFalse;
extern int drawCount_;
iForIndices(i, d->roots) {
iRoot *root = d->roots[i];
if (root) {
setCurrent_Root(root);
unsetClip_Paint(&p); /* update clip to current root */
drawRoot_Widget(root->widget);
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
/* App icon. */
const iWidget *appIcon = findChild_Widget(root->widget, "winbar.icon");
if (isVisible_Widget(appIcon)) {
const int size = appIconSize_Root();
const iRect rect = bounds_Widget(appIcon);
const iInt2 mid = mid_Rect(rect);
const iBool isLight = isLight_ColorTheme(colorTheme_App());
iColor iconColor = get_Color(gotFocus || isLight ? white_ColorId : uiAnnotation_ColorId);
SDL_SetTextureColorMod(d->appIcon, iconColor.r, iconColor.g, iconColor.b);
SDL_SetTextureAlphaMod(d->appIcon, gotFocus || !isLight ? 255 : 92);
SDL_RenderCopy(
d->render,
d->appIcon,
NULL,
&(SDL_Rect){ left_Rect(rect) + gap_UI * 1.25f, mid.y - size / 2, size, size });
}
#endif
/* Root separator and keyboard focus indicator. */
if (numRoots_Window(d) > 1){
const iRect bounds = bounds_Widget(root->widget);
if (i == 1) {
fillRect_Paint(&p, (iRect){
addX_I2(topLeft_Rect(bounds), -gap_UI / 8),
init_I2(gap_UI / 4, height_Rect(bounds))
}, uiSeparator_ColorId);
}
if (root == d->keyRoot) {
const iBool isDark = isDark_ColorTheme(colorTheme_App());
fillRect_Paint(&p, (iRect){
topLeft_Rect(bounds),
init_I2(width_Rect(bounds), gap_UI / 2)
}, isDark ? uiBackgroundSelected_ColorId
: uiIcon_ColorId);
}
}
}
}
setCurrent_Root(NULL);
#if !defined (NDEBUG)
draw_Text(defaultBold_FontId, zero_I2(), red_ColorId, "%d", drawCount_);
drawCount_ = 0;
#endif
}
#if 0
/* Text cache debugging. */ {
SDL_Rect rect = { d->roots[0]->widget->rect.size.x - 640, 0, 640, 2.5 * 640 };
SDL_SetRenderDrawColor(d->render, 0, 0, 0, 255);
SDL_RenderFillRect(d->render, &rect);
SDL_RenderCopy(d->render, glyphCache_Text(), NULL, &rect);
}
#endif
SDL_RenderPresent(d->render);
}
void resize_Window(iWindow *d, int w, int h) {
if (w > 0 && h > 0) {
SDL_SetWindowSize(d->win, w, h);
updateSize_Window_(d, iFalse);
}
else {
updateSize_Window_(d, iTrue); /* notify always */
}
}
void setTitle_Window(iWindow *d, const iString *title) {
SDL_SetWindowTitle(d->win, cstr_String(title));
iLabelWidget *bar = findChild_Widget(get_Root()->widget, "winbar.title");
if (bar) {
updateText_LabelWidget(bar, title);
}
}
void setUiScale_Window(iWindow *d, float uiScale) {
if (uiScale <= 0.0f) {
uiScale = 1.0f;
}
uiScale = iClamp(uiScale, 0.5f, 4.0f);
if (d) {
if (iAbs(d->uiScale - uiScale) > 0.0001f) {
d->uiScale = uiScale;
notifyMetricsChange_Window_(d);
}
}
else {
initialUiScale_ = uiScale;
}
}
void setFreezeDraw_Window(iWindow *d, iBool freezeDraw) {
d->isDrawFrozen = freezeDraw;
}
void setCursor_Window(iWindow *d, int cursor) {
if (!d->cursors[cursor]) {
d->cursors[cursor] = SDL_CreateSystemCursor(cursor);
}
d->pendingCursor = d->cursors[cursor];
}
uint32_t id_Window(const iWindow *d) {
return d && d->win ? SDL_GetWindowID(d->win) : 0;
}
iInt2 size_Window(const iWindow *d) {
return d ? d->size : zero_I2();
}
iInt2 coord_Window(const iWindow *d, int x, int y) {
return mulf_I2(init_I2(x, y), d->pixelRatio);
}
iInt2 mouseCoord_Window(const iWindow *d, int whichDevice) {
if (whichDevice == SDL_TOUCH_MOUSEID) {
/* At least on iOS the coordinates returned by SDL_GetMouseState() do no match up with
our touch coordinates on the Y axis (?). Maybe a pixel ratio thing? */
iUnused(d);
return latestPosition_Touch();
}
if (!d->isMouseInside) {
return init_I2(-1000000, -1000000);
}
int x, y;
SDL_GetMouseState(&x, &y);
return coord_Window(d, x, y);
}
float uiScale_Window(const iWindow *d) {
return d->uiScale;
}
uint32_t frameTime_Window(const iWindow *d) {
return d->frameTime;
}
iWindow *get_Window(void) {
/* TODO: This should be thread-specific. */
return theWindow_;
}
iBool isOpenGLRenderer_Window(void) {
return isOpenGLRenderer_;
}
void setKeyboardHeight_Window(iWindow *d, int height) {
if (d->keyboardHeight != height) {
d->keyboardHeight = height;
if (height == 0) {
setFlags_Anim(&d->rootOffset, easeBoth_AnimFlag, iTrue);
setValue_Anim(&d->rootOffset, 0, 250);
}
postCommandf_App("keyboard.changed arg:%d", height);
postRefresh_App();
}
}
void checkPendingSplit_Window(iWindow *d) {
if (d->splitMode != d->pendingSplitMode) {
setSplitMode_Window(d, d->pendingSplitMode);
}
}
void swapRoots_Window(iWindow *d) {
if (numRoots_Window(d) == 2) {
iSwap(iRoot *, d->roots[0], d->roots[1]);
updateSize_Window_(d, iTrue);
}
}
void setSplitMode_Window(iWindow *d, int splitFlags) {
const int splitMode = splitFlags & mode_WindowSplit;
if (deviceType_App() == phone_AppDeviceType) {
/* There isn't enough room on the phone. */
/* TODO: Maybe in landscape only? */
return;
}
iAssert(current_Root() == NULL);
if (d->splitMode != splitMode) {
int oldCount = numRoots_Window(d);
setFreezeDraw_Window(d, iTrue);
if (oldCount == 2 && splitMode == 0) {
/* Keep references to the tabs of the second root. */
const iDocumentWidget *curPage = document_Root(d->keyRoot);
if (!curPage) {
/* All tabs closed on that side. */
curPage = document_Root(otherRoot_Window(d, d->keyRoot));
}
iObjectList *tabs = listDocuments_App(d->roots[1]);
iForEach(ObjectList, i, tabs) {
setRoot_Widget(i.object, d->roots[0]);
}
setFocus_Widget(NULL);
delete_Root(d->roots[1]);
d->roots[1] = NULL;
d->keyRoot = d->roots[0];
/* Move the deleted root's tabs to the first root. */
setCurrent_Root(d->roots[0]);
iWidget *docTabs = findWidget_Root("doctabs");
iForEach(ObjectList, j, tabs) {
appendTabPage_Widget(docTabs, j.object, "", 0, 0);
}
/* The last child is the [+] button for adding a tab. */
moveTabButtonToEnd_Widget(findChild_Widget(docTabs, "newtab"));
iRelease(tabs);
postCommandf_App("tabs.switch id:%s", cstr_String(id_Widget(constAs_Widget(curPage))));
}
else if (splitMode && oldCount == 1) {
/* Add a second root. */
iDocumentWidget *moved = document_Root(d->roots[0]);
iAssert(d->roots[1] == NULL);
const iBool addToLeft = (prefs_App()->pinSplit == 2);
size_t newRootIndex = 1;
if (addToLeft) {
iSwap(iRoot *, d->roots[0], d->roots[1]);
newRootIndex = 0;
}
d->roots[newRootIndex] = new_Root();
d->keyRoot = d->roots[newRootIndex];
setCurrent_Root(d->roots[newRootIndex]);
createUserInterface_Root(d->roots[newRootIndex]);
if (!isEmpty_String(d->pendingSplitUrl)) {
postCommandf_Root(d->roots[newRootIndex], "open url:%s",
cstr_String(d->pendingSplitUrl));
clear_String(d->pendingSplitUrl);
}
else if (~splitFlags & noEvents_WindowSplit) {
iWidget *docTabs0 = findChild_Widget(d->roots[newRootIndex ^ 1]->widget, "doctabs");
iWidget *docTabs1 = findChild_Widget(d->roots[newRootIndex]->widget, "doctabs");
/* If the old root has multiple tabs, move the current one to the new split. */
if (tabCount_Widget(docTabs0) >= 2) {
int movedIndex = tabPageIndex_Widget(docTabs0, moved);
removeTabPage_Widget(docTabs0, movedIndex);
showTabPage_Widget(docTabs0, tabPage_Widget(docTabs0, iMax(movedIndex - 1, 0)));
iRelease(removeTabPage_Widget(docTabs1, 0)); /* delete the default tab */
setRoot_Widget(as_Widget(moved), d->roots[newRootIndex]);
prependTabPage_Widget(docTabs1, iClob(moved), "", 0, 0);
postCommandf_App("tabs.switch page:%p", moved);
}
else {
postCommand_Root(d->roots[newRootIndex], "navigate.home");
}
}
setCurrent_Root(NULL);
}
d->splitMode = splitMode;
postCommand_App("window.resized");
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
/* Update custom frame controls. */{
const iBool hideCtl0 = numRoots_Window(d) != 1;
iWidget *winBar = findChild_Widget(d->roots[0]->widget, "winbar");
if (winBar) {
setFlags_Widget(
findChild_Widget(winBar, "winbar.min"), hidden_WidgetFlag, hideCtl0);
setFlags_Widget(
findChild_Widget(winBar, "winbar.max"), hidden_WidgetFlag, hideCtl0);
setFlags_Widget(
findChild_Widget(winBar, "winbar.close"), hidden_WidgetFlag, hideCtl0);
if (d->roots[1]) {
winBar = findChild_Widget(d->roots[1]->widget, "winbar");
setFlags_Widget(
findChild_Widget(winBar, "winbar.icon"), hidden_WidgetFlag, iTrue);
setFlags_Widget(
findChild_Widget(winBar, "winbar.app"), hidden_WidgetFlag, iTrue);
}
}
}
#endif
if (~splitFlags & noEvents_WindowSplit) {
updateSize_Window_(d, iTrue);
postCommand_App("window.unfreeze");
}
}
}
void setSnap_Window(iWindow *d, int snapMode) {
if (!prefs_App()->customFrame) {
if (snapMode == maximized_WindowSnap) {
SDL_MaximizeWindow(d->win);
}
else if (snapMode == fullscreen_WindowSnap) {
SDL_SetWindowFullscreen(d->win, SDL_WINDOW_FULLSCREEN_DESKTOP);
}
else {
if (snap_Window(d) == fullscreen_WindowSnap) {
SDL_SetWindowFullscreen(d->win, 0);
}
else {
SDL_RestoreWindow(d->win);
}
}
return;
}
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
if (d->place.snap == snapMode) {
return;
}
const int snapDist = gap_UI * 4;
iRect newRect = zero_Rect();
SDL_Rect usable;
SDL_GetDisplayUsableBounds(SDL_GetWindowDisplayIndex(d->win), &usable);
if (d->place.snap == fullscreen_WindowSnap) {
SDL_SetWindowFullscreen(d->win, 0);
}
d->place.snap = snapMode & ~redo_WindowSnap;
switch (snapMode & mask_WindowSnap) {
case none_WindowSnap:
newRect = intersect_Rect(d->place.normalRect,
init_Rect(usable.x, usable.y, usable.w, usable.h));
break;
case left_WindowSnap:
newRect = init_Rect(usable.x, usable.y, usable.w / 2, usable.h);
break;
case right_WindowSnap:
newRect =
init_Rect(usable.x + usable.w / 2, usable.y, usable.w - usable.w / 2, usable.h);
break;
case maximized_WindowSnap:
newRect = init_Rect(usable.x, usable.y, usable.w, usable.h);
break;
case yMaximized_WindowSnap:
newRect.pos.y = 0;
newRect.size.y = usable.h;
SDL_GetWindowSize(d->win, &newRect.size.x, NULL);
SDL_GetWindowPosition(d->win, &newRect.pos.x, NULL);
/* Snap the window to left/right edges, if close by. */
if (iAbs(right_Rect(newRect) - (usable.x + usable.w)) < snapDist) {
newRect.pos.x = usable.x + usable.w - width_Rect(newRect);
}
if (iAbs(newRect.pos.x - usable.x) < snapDist) {
newRect.pos.x = usable.x;
}
break;
case fullscreen_WindowSnap:
SDL_SetWindowFullscreen(d->win, SDL_WINDOW_FULLSCREEN_DESKTOP);
break;
}
if (snapMode & (topBit_WindowSnap | bottomBit_WindowSnap)) {
newRect.size.y /= 2;
}
if (snapMode & bottomBit_WindowSnap) {
newRect.pos.y += newRect.size.y;
}
/* Update window controls. */
iForIndices(rootIndex, d->roots) {
iRoot *root = d->roots[rootIndex];
if (!root) continue;
iWidget *winBar = findChild_Widget(root->widget, "winbar");
updateTextCStr_LabelWidget(findChild_Widget(winBar, "winbar.max"),
d->place.snap == maximized_WindowSnap ? "\u25a2" : "\u25a1");
/* Show and hide the title bar. */
const iBool wasVisible = isVisible_Widget(winBar);
setFlags_Widget(winBar, hidden_WidgetFlag, d->place.snap == fullscreen_WindowSnap);
if (newRect.size.x) {
SDL_SetWindowPosition(d->win, newRect.pos.x, newRect.pos.y);
SDL_SetWindowSize(d->win, newRect.size.x, newRect.size.y);
postCommand_App("window.resized");
}
if (wasVisible != isVisible_Widget(winBar)) {
arrange_Widget(root->widget);
postRefresh_App();
}
}
#endif /* defined (LAGRANGE_ENABLE_CUSTOM_FRAME) */
}
int snap_Window(const iWindow *d) {
if (!prefs_App()->customFrame) {
const int flags = SDL_GetWindowFlags(d->win);
if (flags & SDL_WINDOW_FULLSCREEN_DESKTOP) {
return fullscreen_WindowSnap;
}
else if (flags & SDL_WINDOW_MAXIMIZED) {
return maximized_WindowSnap;
}
return none_WindowSnap;
}
return d->place.snap;
}
|