/
backend.zig
1612 lines (1402 loc) 路 63.2 KB
/
backend.zig
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
const std = @import("std");
const lib = @import("../../main.zig");
const shared = @import("../shared.zig");
const os = @import("builtin").target.os;
const log = std.log.scoped(.win32);
const EventFunctions = shared.EventFunctions(@This());
const EventType = shared.BackendEventType;
const win32Backend = @import("win32.zig");
const zigwin32 = @import("zigwin32");
const win32 = zigwin32.everything;
const gdi = @import("gdip.zig");
const HWND = win32.HWND;
const HMENU = win32.HMENU;
const HINSTANCE = win32.HINSTANCE;
const RECT = win32.RECT;
const MSG = win32.MSG;
const WPARAM = win32.WPARAM;
const LPARAM = win32.LPARAM;
const LRESULT = win32.LRESULT;
const WINAPI = std.os.windows.WINAPI;
// Common Control: Tabs
const TCM_FIRST = 0x1300;
pub const TCM_GETITEMCOUNT = TCM_FIRST + 4;
pub const TCM_GETITEMA = TCM_FIRST + 5;
pub const TCM_GETITEMW = TCM_FIRST + 60;
pub const TCM_SETITEMA = TCM_FIRST + 6;
pub const TCM_SETITEMW = TCM_FIRST + 61;
pub const TCM_INSERTITEMA = TCM_FIRST + 7;
pub const TCM_INSERTITEMW = TCM_FIRST + 62;
const TCN_FIRST = @as(std.os.windows.UINT, 0) -% 550;
pub const TCN_SELCHANGE = TCN_FIRST - 1;
pub const TCN_SELCHANGING = TCN_FIRST - 2;
pub const TCIF_TEXT = 0x0001;
pub const TCIF_IMAGE = 0x0002;
pub const TCIF_RTLLEADING = 0x0004;
pub const TCIF_PARAM = 0x0008;
pub const TCIF_STATE = 0x0010;
const _T = zigwin32.zig._T;
const L = zigwin32.zig.L;
const Win32Error = error{ UnknownError, InitializationError };
pub const Capabilities = .{ .useEventLoop = true };
pub const PeerType = HWND;
var hInst: HINSTANCE = undefined;
/// By default, win32 controls use DEFAULT_GUI_FONT which is an outdated
/// font from Windows 95 days, by default it doesn't even use ClearType
/// anti-aliasing. So we take the real default caption font from
/// NONFCLIENTEMETRICS and apply it manually to every widget.
var captionFont: win32.HFONT = undefined;
var monospaceFont: win32.HFONT = undefined;
/// Default arrow cursor used to avoid components keeping the last cursor icon
/// that's been set (which is usually the resize cursor or loading cursor)
var defaultCursor: win32.HCURSOR = undefined;
var d2dFactory: *win32.ID2D1Factory = undefined;
var hasInit: bool = false;
fn transWinError(win32_error: win32.WIN32_ERROR) std.os.windows.Win32Error {
return @as(std.os.windows.Win32Error, @enumFromInt(@intFromEnum(win32_error)));
}
pub fn init() !void {
if (!hasInit) {
hasInit = true;
const hInstance = @as(win32.HINSTANCE, @ptrCast(@alignCast(win32.GetModuleHandleW(null).?)));
hInst = hInstance;
if (os.isAtLeast(.windows, .win10_rs2) orelse false) {
// tell Windows that we support high-dpi
if (win32.SetProcessDpiAwarenessContext(win32.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) == 0) {
log.debug("could not set dpi awareness mode; windows might look blurry on high-dpi screens", .{});
}
}
const initEx = win32.INITCOMMONCONTROLSEX{
.dwSize = @sizeOf(win32.INITCOMMONCONTROLSEX),
.dwICC = win32.INITCOMMONCONTROLSEX_ICC.initFlags(.{ .STANDARD_CLASSES = 1, .WIN95_CLASSES = 1 }),
};
const code = win32.InitCommonControlsEx(&initEx);
if (code == 0) {
log.err("Failed to initialize Common Controls", .{});
}
// var input = win32Backend.GdiplusStartupInput{};
// try gdi.gdipWrap(win32Backend.GdiplusStartup(&gdi.token, &input, null));
var ncMetrics: win32.NONCLIENTMETRICSW = undefined;
ncMetrics.cbSize = @sizeOf(win32.NONCLIENTMETRICSW);
_ = win32.SystemParametersInfoW(
win32.SPI_GETNONCLIENTMETRICS,
@sizeOf(win32.NONCLIENTMETRICSW),
&ncMetrics,
win32.SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS.initFlags(.{}),
);
captionFont = win32.CreateFontIndirectW(&ncMetrics.lfCaptionFont).?;
monospaceFont = @ptrCast(win32.GetStockObject(win32.ANSI_FIXED_FONT));
monospaceFont = win32.CreateFontW(
ncMetrics.lfCaptionFont.lfHeight,
ncMetrics.lfCaptionFont.lfWidth,
0,
0,
win32.FW_REGULAR,
0,
0,
0,
win32.DEFAULT_CHARSET,
win32.OUT_DEFAULT_PRECIS,
win32.CLIP_DEFAULT_PRECIS,
win32.DEFAULT_QUALITY,
.MODERN,
_T("Courier"),
).?;
// Load the default arrow cursor so that components can use it
// This avoids components keeping the last cursor (resize cursor or loading cursor)
defaultCursor = zigwin32.ui.windows_and_messaging.LoadCursor(null, win32.IDC_ARROW).?;
std.debug.assert(win32.D2D1CreateFactory(
win32.D2D1_FACTORY_TYPE_SINGLE_THREADED,
zigwin32.graphics.direct2d.IID_ID2D1Factory,
null,
@as(**anyopaque, @ptrCast(&d2dFactory)),
) == 0);
}
}
pub const MessageType = enum { Information, Warning, Error };
pub fn showNativeMessageDialog(msgType: MessageType, comptime fmt: []const u8, args: anytype) void {
const msg = std.fmt.allocPrint(lib.internal.scratch_allocator, fmt, args) catch {
std.log.err("Could not launch message dialog, original text: " ++ fmt, args);
return;
};
defer lib.internal.scratch_allocator.free(msg);
const msg_utf16 = std.unicode.utf8ToUtf16LeWithNull(lib.internal.scratch_allocator, msg) catch {
std.log.err("Could not launch message dialog, original text: " ++ fmt, args);
return;
};
defer lib.internal.scratch_allocator.free(msg_utf16);
const icon = switch (msgType) {
.Information => win32.MB_ICONINFORMATION,
.Warning => win32.MB_ICONWARNING,
.Error => win32.MB_ICONERROR,
};
_ = win32.MessageBoxW(null, msg_utf16, _T("Dialog"), icon);
}
var defaultWHWND: HWND = undefined;
pub const Window = struct {
hwnd: HWND,
source_dpi: u32 = 96,
root_menu: ?HMENU,
/// List of menu item callbacks, where the index is the menu item ID
menu_item_callbacks: std.ArrayList(?*const fn () void),
const className = _T("capyWClass");
pub usingnamespace Events(Window);
fn relayoutChild(hwnd: HWND, lp: LPARAM) callconv(WINAPI) c_int {
const parent = @as(HWND, @ptrFromInt(@as(usize, @bitCast(lp))));
if (win32.GetParent(hwnd) != parent) {
return 1; // ignore recursive childrens
}
var rect: RECT = undefined;
_ = win32.GetClientRect(parent, &rect);
_ = win32.MoveWindow(hwnd, 0, 0, rect.right - rect.left, rect.bottom - rect.top, 1);
return 1;
}
pub fn onResize(data: *EventUserData, hwnd: HWND) void {
_ = data;
_ = win32.EnumChildWindows(hwnd, relayoutChild, @as(isize, @bitCast(@intFromPtr(hwnd))));
}
pub fn onDpiChanged(self: *EventUserData, hwnd: HWND) void {
_ = hwnd;
_ = self;
// TODO: update scale factor
}
pub fn create() !Window {
var wc: win32.WNDCLASSEXW = .{
.cbSize = @sizeOf(win32.WNDCLASSEXW),
.style = win32.WNDCLASS_STYLES.initFlags(.{ .HREDRAW = 1, .VREDRAW = 1 }),
.lpfnWndProc = Window.process,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = hInst,
.hIcon = null, // TODO: LoadIcon
.hCursor = defaultCursor,
.hbrBackground = win32.GetSysColorBrush(@intFromEnum(win32.COLOR_3DFACE)),
.lpszMenuName = null,
.lpszClassName = className,
.hIconSm = null,
};
if ((win32.RegisterClassExW(&wc)) == 0) {
showNativeMessageDialog(.Error, "Could not register window class {s}", .{"capyWClass"});
return Win32Error.InitializationError;
}
// Layered windows sometimes fail on Wine and fresh install of Windows
// See https://stackoverflow.com/questions/19951379/ws-ex-layered-invisible-window-and-a-fresh-install-of-windows
const layered = false;
const hwnd = win32.CreateWindowExW(
// layered don't work in wine for some reason, but only in wine
win32.WINDOW_EX_STYLE.initFlags(.{
.COMPOSITED = 1,
.LAYERED = @intFromBool(layered),
.APPWINDOW = 1,
}), className, // lpClassName
_T(""), // lpWindowName
win32.WS_OVERLAPPEDWINDOW, // dwStyle
win32.CW_USEDEFAULT, // X
win32.CW_USEDEFAULT, // Y
win32.CW_USEDEFAULT, // nWidth
win32.CW_USEDEFAULT, // nHeight
null, // hWindParent
null, // hMenu
hInst, // hInstance
null // lpParam
) orelse return Win32Error.InitializationError;
try Window.setupEvents(hwnd);
if (layered) {
_ = win32.UpdateLayeredWindow(
hwnd,
null,
null,
null,
null,
null,
0xFFFFFFFF,
null,
win32.ULW_OPAQUE,
);
}
defaultWHWND = hwnd;
return Window{
.hwnd = hwnd,
.root_menu = null,
.menu_item_callbacks = std.ArrayList(?*const fn () void).init(
lib.internal.lasting_allocator,
),
};
}
// TODO: handle the fact that ONLY the root child must forcibly draw a background
pub fn setChild(self: *Window, hwnd: ?HWND) void {
// TODO: if null, remove child
_ = win32.SetParent(hwnd.?, self.hwnd);
const style = win32Backend.getWindowLongPtr(hwnd.?, win32.GWL_STYLE);
_ = win32Backend.setWindowLongPtr(hwnd.?, win32.GWL_STYLE, style | @intFromEnum(win32.WS_CHILD));
_ = win32.ShowWindow(hwnd.?, win32.SW_SHOWDEFAULT);
_ = win32.UpdateWindow(hwnd.?);
}
pub fn resize(self: *Window, width: c_int, height: c_int) void {
var rect: RECT = undefined;
_ = win32.GetWindowRect(self.hwnd, &rect);
_ = win32.MoveWindow(self.hwnd, rect.left, rect.top, @as(c_int, @intCast(width)), @as(c_int, @intCast(height)), 1);
}
pub fn setTitle(self: *Window, title: [*:0]const u8) void {
const utf16 = std.unicode.utf8ToUtf16LeWithNull(lib.internal.scratch_allocator, std.mem.span(title)) catch return;
defer lib.internal.scratch_allocator.free(utf16);
_ = win32.SetWindowTextW(self.hwnd, utf16);
}
fn initMenu(self: *Window, menu: HMENU, items: []const lib.MenuItem) !void {
for (items) |item| {
if (item.items.len > 0) {
const submenu = win32.CreateMenu().?;
_ = win32.AppendMenuA(
menu,
win32.MENU_ITEM_FLAGS.initFlags(.{ .POPUP = 1 }),
@intFromPtr(submenu),
item.config.label,
);
try initMenu(self, submenu, item.items);
} else {
_ = win32.AppendMenuA(
menu,
win32.MENU_ITEM_FLAGS.initFlags(.{}),
self.menu_item_callbacks.items.len,
item.config.label,
);
try self.menu_item_callbacks.append(item.config.onClick);
}
}
}
fn clearAndFreeMenus(self: *Window) void {
_ = win32.DestroyMenu(self.root_menu);
self.menu_item_callbacks.clearAndFree();
self.root_menu = null;
}
pub fn setMenuBar(self: *Window, bar: lib.MenuBar) void {
// Detach and free current menu (if exists) from window first.
_ = win32.SetMenu(self.hwnd, null);
self.clearAndFreeMenus();
const root_menu = win32.CreateMenu().?;
self.initMenu(root_menu, bar.menus) catch {
// TODO: Handle error in appropriate way
};
if (win32.SetMenu(self.hwnd, root_menu) != 0) {
self.root_menu = root_menu;
} else {
self.menu_item_callbacks.clearAndFree();
}
}
pub fn setSourceDpi(self: *Window, dpi: u32) void {
self.source_dpi = dpi;
}
pub fn show(self: *Window) void {
_ = win32.ShowWindow(self.hwnd, win32.SW_SHOWDEFAULT);
_ = win32.UpdateWindow(self.hwnd);
}
pub fn close(self: *Window) void {
_ = win32.ShowWindow(self.hwnd, win32.SW_HIDE);
_ = win32.UpdateWindow(self.hwnd);
}
};
const EventUserData = struct {
user: EventFunctions = .{},
class: EventFunctions = .{},
userdata: usize = 0,
peerPtr: ?*anyopaque = null,
classUserdata: usize = 0,
// (very) weak method to detect if a text box's text has actually changed
last_text_len: std.os.windows.INT = 0,
};
inline fn getEventUserData(peer: HWND) *EventUserData {
return @as(*EventUserData, @ptrFromInt(@as(usize, @bitCast(win32Backend.getWindowLongPtr(peer, win32.GWL_USERDATA)))));
}
pub fn Events(comptime T: type) type {
return struct {
const Self = @This();
pub fn process(hwnd: HWND, wm: c_uint, wp: WPARAM, lp: LPARAM) callconv(WINAPI) LRESULT {
switch (wm) {
win32.WM_NOTIFY => {
const nmhdr = @as(*const win32.NMHDR, @ptrFromInt(@as(usize, @bitCast(lp))));
//std.log.info("code = {d} vs {d}", .{ nmhdr.code, win32.TCN_SELCHANGING });
switch (nmhdr.code) {
TCN_SELCHANGING => {
return 0;
},
else => {},
}
},
else => {},
}
if (win32Backend.getWindowLongPtr(hwnd, win32.GWL_USERDATA) == 0) return win32.DefWindowProcW(hwnd, wm, wp, lp);
switch (wm) {
win32.WM_COMMAND => {
const code = @as(u16, @intCast(wp >> 16));
if (lp != 0) {
const data = getEventUserData(@as(HWND, @ptrFromInt(@as(usize, @bitCast(lp)))));
switch (code) {
win32.BN_CLICKED => {
if (data.user.clickHandler) |handler|
handler(data.userdata);
},
win32.EN_CHANGE => {
// Doesn't appear to work.
if (data.user.changedTextHandler) |handler|
handler(data.userdata);
},
else => {},
}
}
// For menubar item events, HIWORD(wp) and lp are set to 0.
else if (code == 0) {
const data = getEventUserData(hwnd);
const window_ptr: ?*Window = @ptrCast(@alignCast(data.peerPtr));
const id: u16 = @intCast(wp & 0xFFFF);
if (window_ptr) |window| {
if (id < window.menu_item_callbacks.items.len) {
if (window.menu_item_callbacks.items[id]) |callback| {
callback();
}
}
}
}
},
win32.WM_CTLCOLOREDIT => {
const data = getEventUserData(@as(HWND, @ptrFromInt(@as(usize, @bitCast(lp)))));
const len = win32.GetWindowTextLengthW(@as(HWND, @ptrFromInt(@as(usize, @bitCast(lp)))));
// The text box may have changed
// TODO: send the event only when the text truly changed
if (data.last_text_len != len) {
if (data.user.changedTextHandler) |handler|
handler(data.userdata);
data.last_text_len = len;
}
},
win32.WM_NOTIFY => {
const nmhdr = @as(*const win32.NMHDR, @ptrFromInt(@as(usize, @bitCast(lp))));
//std.log.info("code = {d} vs {d}", .{ nmhdr.code, win32.TCN_SELCHANGING });
switch (nmhdr.code) {
TCN_SELCHANGING => {
return 0;
},
TCN_SELCHANGE => {
if (@hasDecl(T, "onSelChange")) {
const data = getEventUserData(hwnd);
const sel = win32Backend.TabCtrl_GetCurSelW(nmhdr.hwndFrom.?);
T.onSelChange(data, hwnd, @as(usize, @intCast(sel)));
}
},
else => {},
}
},
win32.WM_SIZE => {
const data = getEventUserData(hwnd);
if (@hasDecl(T, "onResize")) {
T.onResize(data, hwnd);
}
var rect: RECT = undefined;
_ = win32.GetWindowRect(hwnd, &rect);
if (data.class.resizeHandler) |handler|
handler(@as(u32, @intCast(rect.right - rect.left)), @as(u32, @intCast(rect.bottom - rect.top)), data.userdata);
if (data.user.resizeHandler) |handler|
handler(@as(u32, @intCast(rect.right - rect.left)), @as(u32, @intCast(rect.bottom - rect.top)), data.userdata);
},
win32.WM_HSCROLL => {
const data = getEventUserData(hwnd);
var scrollInfo = std.mem.zeroInit(win32.SCROLLINFO, .{
.cbSize = @sizeOf(win32.SCROLLINFO),
.fMask = win32.SIF_POS,
});
_ = win32.GetScrollInfo(hwnd, win32.SB_HORZ, &scrollInfo);
const currentScroll = @as(u32, @intCast(scrollInfo.nPos));
const newPos = switch (@as(u16, @truncate(wp))) {
win32.SB_PAGEUP => currentScroll -| 50,
win32.SB_PAGEDOWN => currentScroll + 50,
win32.SB_LINEUP => currentScroll -| 5,
win32.SB_LINEDOWN => currentScroll + 5,
win32.SB_THUMBPOSITION, win32.SB_THUMBTRACK => wp >> 16,
else => currentScroll,
};
if (newPos != currentScroll) {
var horizontalScrollInfo = std.mem.zeroInit(win32.SCROLLINFO, .{
.cbSize = @sizeOf(win32.SCROLLINFO),
.fMask = win32.SIF_POS,
.nPos = @as(c_int, @intCast(newPos)),
});
_ = win32.SetScrollInfo(hwnd, win32.SB_HORZ, &horizontalScrollInfo, 1);
if (@hasDecl(T, "onHScroll")) {
T.onHScroll(data, hwnd, newPos);
}
}
},
win32.WM_VSCROLL => {
const data = getEventUserData(hwnd);
var scrollInfo = std.mem.zeroInit(win32.SCROLLINFO, .{ .fMask = win32.SIF_POS });
_ = win32.GetScrollInfo(hwnd, win32.SB_VERT, &scrollInfo);
const currentScroll = @as(u32, @intCast(scrollInfo.nPos));
const newPos = switch (@as(u16, @truncate(wp))) {
win32.SB_PAGEUP => currentScroll -| 50,
win32.SB_PAGEDOWN => currentScroll + 50,
win32.SB_LINEUP => currentScroll -| 5,
win32.SB_LINEDOWN => currentScroll + 5,
win32.SB_THUMBPOSITION, win32.SB_THUMBTRACK => wp >> 16,
else => currentScroll,
};
if (newPos != currentScroll) {
var verticalScrollInfo = std.mem.zeroInit(win32.SCROLLINFO, .{
.fMask = win32.SIF_POS,
.nPos = @as(c_int, @intCast(newPos)),
});
_ = win32.SetScrollInfo(hwnd, win32.SB_VERT, &verticalScrollInfo, 1);
if (@hasDecl(T, "onVScroll")) {
T.onVScroll(data, hwnd, newPos);
}
}
},
win32.WM_PAINT => blk: {
const data = getEventUserData(hwnd);
if (data.class.drawHandler == null and data.user.drawHandler == null) break :blk;
var rc: win32.RECT = undefined;
_ = win32.GetClientRect(hwnd, &rc);
var render_target: ?*win32.ID2D1HwndRenderTarget = null;
var hresult = d2dFactory.ID2D1Factory_CreateHwndRenderTarget(
&win32.D2D1_RENDER_TARGET_PROPERTIES{
.type = win32.D2D1_RENDER_TARGET_TYPE_DEFAULT,
.pixelFormat = .{
.format = win32.DXGI_FORMAT_UNKNOWN,
.alphaMode = win32.D2D1_ALPHA_MODE_UNKNOWN,
},
.dpiX = 0.0,
.dpiY = 0.0,
.usage = win32.D2D1_RENDER_TARGET_USAGE_NONE,
.minLevel = win32.D2D1_FEATURE_LEVEL_DEFAULT,
},
&win32.D2D1_HWND_RENDER_TARGET_PROPERTIES{
.hwnd = hwnd,
.pixelSize = .{
.width = @as(u32, @intCast(rc.right - rc.left)),
.height = @as(u32, @intCast(rc.bottom - rc.top)),
},
.presentOptions = win32.D2D1_PRESENT_OPTIONS_NONE,
},
&render_target,
);
std.debug.assert(hresult == 0);
// defer win32.SafeRelease(render_target);
var default_brush: ?*win32.ID2D1SolidColorBrush = null;
std.debug.assert(render_target.?.ID2D1RenderTarget_CreateSolidColorBrush(
&win32.D2D1_COLOR_F{ .r = 0, .g = 0, .b = 0, .a = 1 },
null,
&default_brush,
) == 0);
var dc = Canvas.DrawContext{
.render_target = render_target.?,
.brush = default_brush.?,
.path = std.ArrayList(Canvas.DrawContext.PathElement)
.init(lib.internal.scratch_allocator),
};
defer dc.path.deinit();
render_target.?.ID2D1RenderTarget_BeginDraw();
render_target.?.ID2D1RenderTarget_Clear(&win32.D2D1_COLOR_F{ .r = 1, .g = 1, .b = 1, .a = 0 });
defer _ = render_target.?.ID2D1RenderTarget_EndDraw(null, null);
if (data.class.drawHandler) |handler|
handler(&dc, data.userdata);
if (data.user.drawHandler) |handler|
handler(&dc, data.userdata);
},
win32.WM_SETFOCUS => {
if (@hasDecl(T, "onGotFocus")) {
T.onGotFocus(hwnd);
}
},
win32.WM_DESTROY => win32.PostQuitMessage(0),
else => {},
}
return win32.DefWindowProcW(hwnd, wm, wp, lp);
}
pub fn setupEvents(peer: HWND) !void {
var data = try lib.internal.lasting_allocator.create(EventUserData);
data.* = EventUserData{}; // ensure that it uses default values
_ = win32Backend.setWindowLongPtr(peer, win32.GWL_USERDATA, @intFromPtr(data));
}
pub inline fn setUserData(self: *T, data: anytype) void {
comptime {
if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) {
@compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))}));
}
}
if (@TypeOf(self) == *Window) {
getEventUserData(self.hwnd).peerPtr = self;
getEventUserData(self.hwnd).userdata = @intFromPtr(data);
} else {
getEventUserData(self.peer).peerPtr = self;
getEventUserData(self.peer).userdata = @intFromPtr(data);
}
}
pub inline fn setCallback(self: *T, comptime eType: EventType, cb: anytype) !void {
const data = if (@TypeOf(self) == *Window) &getEventUserData(self.hwnd).user else &getEventUserData(self.peer).user;
switch (eType) {
.Click => data.clickHandler = cb,
.Draw => data.drawHandler = cb,
// TODO: implement mouse button
.MouseButton => data.mouseButtonHandler = cb,
// TODO: implement mouse motion
.MouseMotion => data.mouseMotionHandler = cb,
// TODO: implement scroll
.Scroll => data.scrollHandler = cb,
.TextChanged => data.changedTextHandler = cb,
.Resize => data.resizeHandler = cb,
// TODO: implement key type
.KeyType => data.keyTypeHandler = cb,
// TODO: implement key press
.KeyPress => data.keyPressHandler = cb,
.PropertyChange => data.propertyChangeHandler = cb,
}
}
/// Requests a redraw
pub fn requestDraw(self: *T) !void {
var updateRect: RECT = undefined;
updateRect = .{ .left = 0, .top = 0, .right = 10000, .bottom = 10000 };
if (win32.InvalidateRect(self.peer, &updateRect, 0) == 0) {
return Win32Error.UnknownError;
}
if (win32.UpdateWindow(self.peer) == 0) {
return Win32Error.UnknownError;
}
}
pub fn getWidth(self: *const T) c_int {
var rect: RECT = undefined;
_ = win32.GetWindowRect(self.peer, &rect);
return rect.right - rect.left;
}
pub fn getHeight(self: *const T) c_int {
var rect: RECT = undefined;
_ = win32.GetWindowRect(self.peer, &rect);
return rect.bottom - rect.top;
}
pub fn getPreferredSize(self: *const T) lib.Size {
// TODO
_ = self;
return lib.Size.init(100, 50);
}
pub fn setOpacity(self: *const T, opacity: f64) void {
_ = self;
_ = opacity;
// TODO
}
pub fn deinit(self: *const T) void {
_ = self;
// TODO
}
};
}
pub const MouseButton = enum { Left, Middle, Right };
pub const Canvas = struct {
peer: HWND,
data: usize = 0,
pub usingnamespace Events(Canvas);
pub const DrawContext = struct {
path: std.ArrayList(PathElement),
render_target: *win32.ID2D1HwndRenderTarget,
brush: *win32.ID2D1SolidColorBrush,
const PathElement = union(enum) {
Rectangle: struct { left: c_int, top: c_int, right: c_int, bottom: c_int },
};
pub const TextLayout = struct {
font: win32.HFONT,
/// HDC only used for getting text metrics
hdc: win32.HDC,
/// If null, no text wrapping is applied, otherwise the text is wrapping as if this was the maximum width.
/// TODO: this is not yet implemented in the win32 backend
wrap: ?f64 = null,
pub const Font = struct {
face: [:0]const u8,
size: f64,
};
pub const TextSize = struct { width: u32, height: u32 };
pub fn init() TextLayout {
// creates an HDC for the current screen, whatever it means given we can have windows on different screens
const hdc = win32.CreateCompatibleDC(null);
const defaultFont = @as(win32.HFONT, @ptrCast(win32.GetStockObject(win32.DEFAULT_GUI_FONT)));
_ = win32.SelectObject(hdc, @as(win32.HGDIOBJ, @ptrCast(defaultFont)));
return TextLayout{ .font = defaultFont, .hdc = hdc };
}
pub fn setFont(self: *TextLayout, font: Font) void {
// _ = win32.DeleteObject(@ptrCast(win32.HGDIOBJ, self.font)); // delete old font
const allocator = lib.internal.scratch_allocator;
const wideFace = std.unicode.utf8ToUtf16LeWithNull(allocator, font.face) catch return; // invalid utf8 or not enough memory
defer allocator.free(wideFace);
if (win32.CreateFontW(0, // cWidth
0, // cHeight
0, // cEscapement,
0, // cOrientation,
win32.FW_NORMAL, // cWeight
0, // bItalic
0, // bUnderline
0, // bStrikeOut
0, // iCharSet
win32.FONT_OUTPUT_PRECISION.DEFAULT_PRECIS, // iOutPrecision
win32.FONT_CLIP_PRECISION.DEFAULT_PRECIS, // iClipPrecision
win32.FONT_QUALITY.DEFAULT_QUALITY, // iQuality
win32.FONT_PITCH_AND_FAMILY.DONTCARE, // iPitchAndFamily
wideFace // pszFaceName
)) |winFont| {
_ = win32.DeleteObject(@as(win32.HGDIOBJ, @ptrCast(self.font)));
self.font = winFont;
}
_ = win32.SelectObject(self.hdc, @as(win32.HGDIOBJ, @ptrCast(self.font)));
}
pub fn getTextSize(self: *TextLayout, str: []const u8) TextSize {
var size: win32.SIZE = undefined;
const allocator = lib.internal.scratch_allocator;
const wide = std.unicode.utf8ToUtf16LeWithNull(allocator, str) catch return; // invalid utf8 or not enough memory
defer allocator.free(wide);
_ = win32.GetTextExtentPoint32W(self.hdc, wide.ptr, @as(c_int, @intCast(str.len)), &size);
return TextSize{ .width = @as(u32, @intCast(size.cx)), .height = @as(u32, @intCast(size.cy)) };
}
pub fn deinit(self: *TextLayout) void {
_ = win32.DeleteObject(@as(win32.HGDIOBJ, @ptrCast(self.hdc)));
_ = win32.DeleteObject(@as(win32.HGDIOBJ, @ptrCast(self.font)));
}
};
// TODO: transparency support using https://docs.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-alphablend
// or use GDI+ and https://docs.microsoft.com/en-us/windows/win32/gdiplus/-gdiplus-drawing-with-opaque-and-semitransparent-brushes-use
pub fn setColorByte(self: *DrawContext, color: lib.Color) void {
_ = self;
const colorref = (@as(u32, color.blue) << 16) |
(@as(u32, color.green) << 8) | color.red;
_ = colorref;
// _ = win32.SetDCBrushColor(self.hdc, colorref);
}
pub fn setColor(self: *DrawContext, r: f32, g: f32, b: f32) void {
self.setColorRGBA(r, g, b, 1);
}
pub fn setColorRGBA(self: *DrawContext, r: f32, g: f32, b: f32, a: f32) void {
const color = lib.Color{
.red = @as(u8, @intFromFloat(std.math.clamp(r, 0, 1) * 255)),
.green = @as(u8, @intFromFloat(std.math.clamp(g, 0, 1) * 255)),
.blue = @as(u8, @intFromFloat(std.math.clamp(b, 0, 1) * 255)),
.alpha = @as(u8, @intFromFloat(std.math.clamp(a, 0, 1) * 255)),
};
self.setColorByte(color);
}
pub fn rectangle(self: *DrawContext, x: i32, y: i32, w: u32, h: u32) void {
_ = h;
_ = w;
_ = y;
_ = x;
_ = self;
// _ = win32.Rectangle(self.hdc, @intCast(c_int, x), @intCast(c_int, y), x + @intCast(c_int, w), y + @intCast(c_int, h));
}
pub fn ellipse(self: *DrawContext, x: i32, y: i32, w: u32, h: u32) void {
_ = y;
_ = x;
_ = self;
const cw = @as(c_int, @intCast(w));
_ = cw;
const ch = @as(c_int, @intCast(h));
_ = ch;
// _ = win32.Ellipse(self.hdc, @intCast(c_int, x), @intCast(c_int, y), @intCast(c_int, x) + cw, @intCast(c_int, y) + ch);
}
pub fn text(self: *DrawContext, x: i32, y: i32, layout: TextLayout, str: []const u8) void {
_ = str;
_ = layout;
_ = y;
_ = x;
_ = self;
// select current color
// const color = win32.GetDCBrushColor(self.hdc);
// _ = win32.SetTextColor(self.hdc, color);
// select the font
// win32.SelectObject(self.hdc, @ptrCast(win32.HGDIOBJ, layout.font));
// and draw
// _ = win32.ExtTextOutA(self.hdc, @intCast(c_int, x), @intCast(c_int, y), 0, null, str.ptr, @intCast(std.os.windows.UINT, str.len), null);
}
pub fn line(self: *DrawContext, x1: i32, y1: i32, x2: i32, y2: i32) void {
_ = y2;
_ = x2;
_ = y1;
_ = x1;
_ = self;
// _ = win32.MoveToEx(self.hdc, @intCast(c_int, x1), @intCast(c_int, y1), null);
// _ = win32.LineTo(self.hdc, @intCast(c_int, x2), @intCast(c_int, y2));
}
pub fn fill(self: *DrawContext) void {
self.path.clearRetainingCapacity();
}
pub fn stroke(self: *DrawContext) void {
self.path.clearRetainingCapacity();
}
};
var classRegistered = false;
pub fn create() !Canvas {
if (!classRegistered) {
var wc: win32.WNDCLASSEXW = .{
.cbSize = @sizeOf(win32.WNDCLASSEXW),
.style = win32.WNDCLASS_STYLES.initFlags(.{ .VREDRAW = 1, .HREDRAW = 1 }),
.lpfnWndProc = Canvas.process,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = hInst,
.hIcon = null, // TODO: LoadIcon
.hCursor = defaultCursor,
.hbrBackground = null,
.lpszMenuName = null,
.lpszClassName = L("capyCanvasClass"),
.hIconSm = null,
};
if ((win32.RegisterClassExW(&wc)) == 0) {
showNativeMessageDialog(.Error, "Could not register window class {s}", .{"capyCanvasClass"});
return Win32Error.InitializationError;
}
classRegistered = true;
}
const hwnd = win32.CreateWindowExW(win32.WS_EX_LEFT, // dwExtStyle
L("capyCanvasClass"), // lpClassName
L(""), // lpWindowName
win32.WINDOW_STYLE.initFlags(.{ .TABSTOP = 1, .CHILD = 1 }), // dwStyle
0, // X
0, // Y
100, // nWidth
100, // nHeight
defaultWHWND, // hWindParent
null, // hMenu
hInst, // hInstance
null // lpParam
) orelse return Win32Error.InitializationError;
try Canvas.setupEvents(hwnd);
return Canvas{ .peer = hwnd };
}
};
pub const TextField = struct {
peer: HWND,
arena: std.heap.ArenaAllocator,
pub usingnamespace Events(TextField);
pub fn create() !TextField {
const hwnd = win32.CreateWindowExW(win32.WS_EX_LEFT, // dwExtStyle
_T("EDIT"), // lpClassName
_T(""), // lpWindowName
@as(win32.WINDOW_STYLE, @enumFromInt(@intFromEnum(win32.WS_TABSTOP) | @intFromEnum(win32.WS_CHILD) | @intFromEnum(win32.WS_BORDER))), // dwStyle
0, // X
0, // Y
100, // nWidth
100, // nHeight
defaultWHWND, // hWindParent
null, // hMenu
hInst, // hInstance
null // lpParam
) orelse return Win32Error.InitializationError;
try TextField.setupEvents(hwnd);
_ = win32.SendMessageW(hwnd, win32.WM_SETFONT, @intFromPtr(captionFont), 1);
return TextField{ .peer = hwnd, .arena = std.heap.ArenaAllocator.init(lib.internal.lasting_allocator) };
}
pub fn setText(self: *TextField, text: []const u8) void {
const allocator = lib.internal.scratch_allocator;
const wide = std.unicode.utf8ToUtf16LeWithNull(allocator, text) catch return; // invalid utf8 or not enough memory
defer allocator.free(wide);
if (win32.SetWindowTextW(self.peer, wide) == 0) {
std.os.windows.unexpectedError(transWinError(win32.GetLastError())) catch {};
}
const len = win32.GetWindowTextLengthW(self.peer);
getEventUserData(self.peer).last_text_len = len;
}
pub fn getText(self: *TextField) [:0]const u8 {
const allocator = self.arena.allocator();
const len = win32.GetWindowTextLengthW(self.peer);
var buf = allocator.allocSentinel(u16, @as(usize, @intCast(len)), 0) catch unreachable; // TODO return error
defer allocator.free(buf);
const realLen = @as(usize, @intCast(win32.GetWindowTextW(self.peer, buf.ptr, len + 1)));
const utf16Slice = buf[0..realLen];
const text = std.unicode.utf16leToUtf8AllocZ(allocator, utf16Slice) catch unreachable; // TODO return error
return text;
}
pub fn setReadOnly(self: *TextField, readOnly: bool) void {
_ = win32.SendMessageW(self.peer, win32.EM_SETREADONLY, @intFromBool(readOnly), undefined);
}
};
pub const TextArea = struct {
peer: HWND,
arena: std.heap.ArenaAllocator,
pub usingnamespace Events(TextArea);
pub fn create() !TextArea {
const hwnd = win32.CreateWindowExW(win32.WS_EX_LEFT, // dwExtStyle
_T("EDIT"), // lpClassName
_T(""), // lpWindowName
@as(win32.WINDOW_STYLE, @enumFromInt(@intFromEnum(win32.WS_TABSTOP) | @intFromEnum(win32.WS_CHILD) | @intFromEnum(win32.WS_BORDER) | win32.ES_MULTILINE | win32.ES_AUTOVSCROLL | win32.ES_WANTRETURN)), // dwStyle
0, // X
0, // Y
100, // nWidth
100, // nHeight
defaultWHWND, // hWindParent
null, // hMenu
hInst, // hInstance
null // lpParam
) orelse return Win32Error.InitializationError;
try TextArea.setupEvents(hwnd);
_ = win32.SendMessageW(hwnd, win32.WM_SETFONT, @intFromPtr(captionFont), 1);
return TextArea{ .peer = hwnd, .arena = std.heap.ArenaAllocator.init(lib.internal.lasting_allocator) };
}
pub fn setText(self: *TextArea, text: []const u8) void {
const allocator = lib.internal.scratch_allocator;
const wide = std.unicode.utf8ToUtf16LeWithNull(allocator, text) catch return; // invalid utf8 or not enough memory
defer allocator.free(wide);
if (win32.SetWindowTextW(self.peer, wide) == 0) {
std.os.windows.unexpectedError(transWinError(win32.GetLastError())) catch {};
}
const len = win32.GetWindowTextLengthW(self.peer);
getEventUserData(self.peer).last_text_len = len;
}
pub fn getText(self: *TextArea) [:0]const u8 {
const allocator = self.arena.allocator();
const len = win32.GetWindowTextLengthW(self.peer);
var buf = allocator.allocSentinel(u16, @as(usize, @intCast(len)), 0) catch unreachable; // TODO return error
defer allocator.free(buf);
const realLen = @as(usize, @intCast(win32.GetWindowTextW(self.peer, buf.ptr, len + 1)));
const utf16Slice = buf[0..realLen];
const text = std.unicode.utf16leToUtf8AllocZ(allocator, utf16Slice) catch unreachable; // TODO return error
return text;
}
pub fn setReadOnly(self: *TextArea, readOnly: bool) void {
_ = win32.SendMessageW(self.peer, win32.EM_SETREADONLY, @intFromBool(readOnly), undefined);
}
pub fn setMonospaced(self: *TextArea, monospaced: bool) void {
if (monospaced) {
_ = win32.SendMessageW(self.peer, win32.WM_SETFONT, @intFromPtr(monospaceFont), 1);
} else {
_ = win32.SendMessageW(self.peer, win32.WM_SETFONT, @intFromPtr(captionFont), 1);
}
}
};
pub const Button = struct {
peer: HWND,
arena: std.heap.ArenaAllocator,
pub usingnamespace Events(Button);
pub fn create() !Button {
const hwnd = win32.CreateWindowExW(win32.WS_EX_LEFT, // dwExtStyle
_T("BUTTON"), // lpClassName
_T(""), // lpWindowName
@as(win32.WINDOW_STYLE, @enumFromInt(@intFromEnum(win32.WS_TABSTOP) | @intFromEnum(win32.WS_CHILD) | win32.BS_PUSHBUTTON | win32.BS_FLAT)), // dwStyle
0, // X
0, // Y