forked from david-vanderson/dvui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdvui.zig
10454 lines (8825 loc) · 377 KB
/
dvui.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 builtin = @import("builtin");
const std = @import("std");
const math = std.math;
const tvg = @import("tinyvg/tinyvg.zig");
const fnv = std.hash.Fnv1a_32;
pub const icons = @import("icons.zig");
pub const fonts = @import("fonts.zig");
pub const enums = @import("enums.zig");
const c = @cImport({
@cInclude("freetype/ftadvanc.h");
@cInclude("freetype/ftbbox.h");
@cInclude("freetype/ftbitmap.h");
@cInclude("freetype/ftcolor.h");
@cInclude("freetype/ftlcdfil.h");
@cInclude("freetype/ftsizes.h");
@cInclude("freetype/ftstroke.h");
@cInclude("freetype/fttrigon.h");
});
pub const Error = error{ OutOfMemory, InvalidUtf8, freetypeError, tvgError };
const log = std.log.scoped(.dvui);
const dvui = @This();
var current_window: ?*Window = null;
pub fn currentWindow() *Window {
return current_window orelse unreachable;
}
pub var log_debug: bool = false;
pub fn debug(comptime str: []const u8, args: anytype) void {
if (log_debug) {
log.debug(str, args);
}
}
pub const Theme = struct {
pub const ColorStyle = enum {
content, // default
accent,
control,
window,
success,
err,
};
pub const StyleColors = struct {
// used to show focus
accent: ?Color = null,
text: ?Color = null,
// background color contrasting the most with the text color, used when
// displaying lots of text
fill: ?Color = null,
border: ?Color = null,
hover: ?Color = null,
press: ?Color = null,
};
name: []const u8,
dark: bool,
alpha: f32 = 1.0,
// Options.color_style selects between these
// content is default and must have all fields non-null
style_content: StyleColors,
// any null fields in these will use .content fields
style_accent: StyleColors,
style_control: StyleColors,
style_window: StyleColors,
style_success: StyleColors,
style_err: StyleColors,
font_body: Font,
font_heading: Font,
font_caption: Font,
font_caption_heading: Font,
font_title: Font,
font_title_1: Font,
font_title_2: Font,
font_title_3: Font,
font_title_4: Font,
};
pub const Adwaita = struct {
const accent = Color{ .r = 0x35, .g = 0x84, .b = 0xe4 };
const success = Color{ .r = 0x2e, .g = 0xc2, .b = 0x7e };
const err = Color{ .r = 0xe0, .g = 0x1b, .b = 0x24 };
pub var light = Theme{
.name = "Adwaita",
.dark = false,
.font_body = Font{ .size = 11, .name = "Vera", .ttf_bytes = fonts.bitstream_vera.Vera },
.font_heading = Font{ .size = 11, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_caption = Font{ .size = 9, .name = "Vera", .ttf_bytes = fonts.bitstream_vera.Vera },
.font_caption_heading = Font{ .size = 9, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title = Font{ .size = 24, .name = "Vera", .ttf_bytes = fonts.bitstream_vera.Vera },
.font_title_1 = Font{ .size = 20, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title_2 = Font{ .size = 17, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title_3 = Font{ .size = 15, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title_4 = Font{ .size = 13, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.style_content = .{
.accent = accent,
.text = Color.black,
.fill = Color.white,
.border = Color.lerp(Color.white, 0.4, Color.black),
.hover = Color.lerp(Color.white, 0.2, Color.black),
.press = Color.lerp(Color.white, 0.3, Color.black),
},
.style_control = .{ .fill = Color{ .r = 0xe0, .g = 0xe0, .b = 0xe0 } },
.style_window = .{ .fill = Color{ .r = 0xf0, .g = 0xf0, .b = 0xf0 } },
.style_accent = .{
.accent = accent.darken(0.3),
.fill = accent,
.text = Color.white,
.border = Color.lerp(accent, 0.4, Color.black),
.hover = Color.lerp(accent, 0.2, Color.black),
.press = Color.lerp(accent, 0.3, Color.black),
},
.style_success = .{
.accent = success.darken(0.3),
.fill = success,
.text = Color.white,
.border = Color.lerp(success, 0.4, Color.black),
.hover = Color.lerp(success, 0.2, Color.black),
.press = Color.lerp(success, 0.3, Color.black),
},
.style_err = .{
.accent = err.darken(0.3),
.fill = err,
.text = Color.white,
.border = Color.lerp(err, 0.4, Color.black),
.hover = Color.lerp(err, 0.2, Color.black),
.press = Color.lerp(err, 0.3, Color.black),
},
};
const dark_fill = Color{ .r = 0x1e, .g = 0x1e, .b = 0x1e };
const dark_success = Color{ .r = 0x26, .g = 0xa2, .b = 0x69 };
const dark_err = Color{ .r = 0xc0, .g = 0x1c, .b = 0x28 };
pub var dark = Theme{
.name = "Adwaita Dark",
.dark = true,
.font_body = Font{ .size = 11, .name = "Vera", .ttf_bytes = fonts.bitstream_vera.Vera },
.font_heading = Font{ .size = 11, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_caption = Font{ .size = 9, .name = "Vera", .ttf_bytes = fonts.bitstream_vera.Vera },
.font_caption_heading = Font{ .size = 9, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title = Font{ .size = 24, .name = "Vera", .ttf_bytes = fonts.bitstream_vera.Vera },
.font_title_1 = Font{ .size = 20, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title_2 = Font{ .size = 17, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title_3 = Font{ .size = 15, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.font_title_4 = Font{ .size = 13, .name = "VeraBd", .ttf_bytes = fonts.bitstream_vera.VeraBd },
.style_content = .{
.accent = accent,
.text = Color.white,
.fill = dark_fill,
.border = Color.lerp(dark_fill, 0.4, Color.white),
.hover = Color.lerp(dark_fill, 0.2, Color.white),
.press = Color.lerp(dark_fill, 0.3, Color.white),
},
.style_control = .{ .fill = Color{ .r = 0x40, .g = 0x40, .b = 0x40 } },
.style_window = .{ .fill = Color{ .r = 0x2b, .g = 0x2b, .b = 0x2b } },
.style_accent = .{
.accent = accent.lighten(0.3),
.fill = accent,
.text = Color.white,
.border = Color.lerp(accent, 0.4, Color.white),
.hover = Color.lerp(accent, 0.2, Color.white),
.press = Color.lerp(accent, 0.3, Color.white),
},
.style_success = .{
.accent = dark_success.lighten(0.3),
.fill = dark_success,
.text = Color.white,
.border = Color.lerp(success, 0.4, Color.white),
.hover = Color.lerp(success, 0.2, Color.white),
.press = Color.lerp(success, 0.3, Color.white),
},
.style_err = .{
.accent = dark_err.lighten(0.3),
.fill = dark_err,
.text = Color.white,
.border = Color.lerp(err, 0.4, Color.white),
.hover = Color.lerp(err, 0.2, Color.white),
.press = Color.lerp(err, 0.3, Color.white),
},
};
};
pub const Options = struct {
pub const Expand = enum {
none,
horizontal,
vertical,
both,
pub fn horizontal(self: Expand) bool {
return (self == .horizontal or self == .both);
}
pub fn vertical(self: Expand) bool {
return (self == .vertical or self == .both);
}
pub fn removeHorizontal(self: Expand) Expand {
return switch (self) {
.none => .none,
.horizontal => .none,
.vertical => .vertical,
.both => .vertical,
};
}
pub fn removeVertical(self: Expand) Expand {
return switch (self) {
.none => .none,
.horizontal => .horizontal,
.vertical => .none,
.both => .horizontal,
};
}
};
pub const Gravity = struct {
// wraps Options.gravity_x and Options.gravity_y
x: f32,
y: f32,
};
pub const FontStyle = enum {
body,
heading,
caption,
caption_heading,
title,
title_1,
title_2,
title_3,
title_4,
};
// used to adjust widget id when @src() is not enough (like in a loop)
id_extra: ?usize = null,
// used in debugging to give widgets a name, especially in compound widgets
name: ?[]const u8 = null,
debug: ?bool = null,
// null is normal, meaning parent picks a rect for the child widget. If
// non-null, child widget is choosing its own place, meaning its not being
// placed normally. w and h will still be expanded if expand is set.
// Example is ScrollArea, where user code chooses widget placement. If
// non-null, should not call rectFor or minSizeForChild.
rect: ?Rect = null,
// default is .none
expand: ?Expand = null,
// [0, 1] default is 0 (left)
gravity_x: ?f32 = null,
// [0, 1] default is 0 (top)
gravity_y: ?f32 = null,
// used to override the tab order, lower numbers first, null means highest
// possible number, same tab_index goes in install() order
tab_index: ?u16 = null,
// used to override widget and theme defaults
color_accent: ?Color = null,
color_text: ?Color = null,
color_fill: ?Color = null,
color_border: ?Color = null,
color_hover: ?Color = null,
color_press: ?Color = null,
// use to override font_style
font: ?Font = null,
// only used for icons, rotates around center, only rotates drawing, radians counterclockwise
rotation: ?f32 = null,
// For the rest of these fields, if null, each widget uses its defaults
// x left, y top, w right, h bottom
margin: ?Rect = null,
border: ?Rect = null,
padding: ?Rect = null,
// x topleft, y topright, w botright, h botleft
corner_radius: ?Rect = null,
// padding/border/margin will be added to this
min_size_content: ?Size = null,
// whether to fill the background
background: ?bool = null,
// use to pick a font from the theme
font_style: ?FontStyle = null,
// use to pick a color from the theme
color_style: ?Theme.ColorStyle = null,
pub const ColorKind = enum {
accent,
text,
fill,
border,
hover,
press,
};
pub fn color(self: *const Options, kind: ColorKind) Color {
var ret: ?Color = switch (kind) {
.accent => self.color_accent,
.text => self.color_text,
.fill => self.color_fill,
.border => self.color_border,
.hover => self.color_hover,
.press => self.color_press,
};
// if we have a custom color, return it
if (ret) |r| {
return r.transparent(themeGet().alpha);
}
// find the colors in our style
const cs: Theme.StyleColors = switch (self.color_style orelse .content) {
.content => themeGet().style_content,
.accent => themeGet().style_accent,
.window => themeGet().style_window,
.control => themeGet().style_control,
.success => themeGet().style_success,
.err => themeGet().style_err,
};
// return color from style or default
switch (kind) {
.accent => ret = cs.accent orelse themeGet().style_content.accent orelse unreachable,
.text => ret = cs.text orelse themeGet().style_content.text orelse unreachable,
.fill => ret = cs.fill orelse themeGet().style_content.fill orelse unreachable,
.border => ret = cs.border orelse themeGet().style_content.border orelse unreachable,
.hover => ret = cs.hover orelse themeGet().style_content.hover orelse unreachable,
.press => ret = cs.press orelse themeGet().style_content.press orelse unreachable,
}
return (ret orelse unreachable).transparent(themeGet().alpha);
}
pub fn fontGet(self: *const Options) Font {
if (self.font) |ff| {
return ff;
}
return switch (self.font_style orelse .body) {
.body => themeGet().font_body,
.heading => themeGet().font_heading,
.caption => themeGet().font_caption,
.caption_heading => themeGet().font_caption_heading,
.title => themeGet().font_title,
.title_1 => themeGet().font_title_1,
.title_2 => themeGet().font_title_2,
.title_3 => themeGet().font_title_3,
.title_4 => themeGet().font_title_4,
};
}
pub fn idExtra(self: *const Options) usize {
return self.id_extra orelse 0;
}
pub fn debugGet(self: *const Options) bool {
return self.debug orelse false;
}
pub fn expandGet(self: *const Options) Expand {
return self.expand orelse .none;
}
pub fn gravityGet(self: *const Options) Gravity {
return .{ .x = self.gravity_x orelse 0.0, .y = self.gravity_y orelse 0.0 };
}
pub fn marginGet(self: *const Options) Rect {
return self.margin orelse Rect{};
}
pub fn borderGet(self: *const Options) Rect {
return self.border orelse Rect{};
}
pub fn backgroundGet(self: *const Options) bool {
return self.background orelse false;
}
pub fn paddingGet(self: *const Options) Rect {
return self.padding orelse Rect{};
}
pub fn corner_radiusGet(self: *const Options) Rect {
return self.corner_radius orelse Rect{};
}
pub fn min_sizeGet(self: *const Options) Size {
return self.min_size_contentGet().pad(self.paddingGet()).pad(self.borderGet()).pad(self.marginGet());
}
pub fn min_size_contentGet(self: *const Options) Size {
return self.min_size_content orelse Size{};
}
pub fn rotationGet(self: *const Options) f32 {
return self.rotation orelse 0.0;
}
// Used in compound widgets to strip out the styling that should only apply
// to the outermost container widget. For example, with a button
// (container with label) the container uses:
// - rect
// - min_size_content
// - margin
// - border
// - background
// - padding
// - corner_radius
// - expand
// - gravity
// while the label uses:
// - fonts
// - colors
pub fn strip(self: *const Options) Options {
return Options{
// reset to defaults of internal widgets
.id_extra = null,
.name = null,
.rect = null,
.min_size_content = null,
.expand = null,
.gravity_x = null,
.gravity_y = null,
// ignore defaults of internal widgets
.tab_index = null,
.margin = Rect{},
.border = Rect{},
.padding = Rect{},
.corner_radius = Rect{},
.background = false,
// keep the rest
.color_accent = self.color_accent,
.color_text = self.color_text,
.color_fill = self.color_fill,
.color_border = self.color_border,
.color_hover = self.color_hover,
.color_press = self.color_press,
.font = self.font,
.color_style = self.color_style,
.font_style = self.font_style,
.rotation = self.rotation,
.debug = self.debug,
};
}
pub fn wrapOuter(self: *const Options) Options {
var ret = self.*;
ret.tab_index = null;
ret.border = Rect{};
ret.padding = Rect{};
ret.background = false;
return ret;
}
pub fn wrapInner(self: *const Options) Options {
return self.strip().override(.{
.tab_index = self.tab_index,
.border = self.border,
.padding = self.padding,
.corner_radius = self.corner_radius,
.background = self.background,
.expand = .both,
});
}
pub fn override(self: *const Options, over: Options) Options {
var ret = self.*;
inline for (@typeInfo(Options).Struct.fields) |f| {
if (@field(over, f.name)) |fval| {
@field(ret, f.name) = fval;
}
}
return ret;
}
//pub fn format(self: *const Options, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
// try std.fmt.format(writer, "Options{{ .background = {?}, .color_style = {?} }}", .{ self.background, self.color_style });
//}
};
pub fn themeGet() *Theme {
return currentWindow().theme;
}
pub fn themeSet(theme: *Theme) void {
currentWindow().theme = theme;
}
pub fn toggleDebugWindow() void {
var cw = currentWindow();
cw.debug_window_show = !cw.debug_window_show;
}
pub fn placeOnScreen(spawner: Rect, start: Rect) Rect {
var r = start;
const wr = windowRect();
if ((r.x + r.w) > wr.w) {
if (spawner.w == 0) {
r.x = wr.w - r.w;
} else {
r.x = spawner.x - spawner.w - r.w;
}
}
if (r.x < wr.x) {
r.x = wr.x;
}
if ((r.x + r.w) > wr.w) {
r.w = wr.w - r.x;
}
if ((r.y + r.h) > wr.h) {
r.y = wr.h - r.h;
}
if (r.y < wr.y) {
r.y = wr.y;
}
if ((r.y + r.h) > wr.h) {
r.h = wr.h - r.y;
}
return r;
}
pub fn frameTimeNS() i128 {
return currentWindow().frame_time_ns;
}
pub const Font = struct {
size: f32,
line_height_factor: f32 = 1.0,
name: []const u8,
ttf_bytes: []const u8,
pub fn resize(self: *const Font, s: f32) Font {
return Font{ .size = s, .line_height_factor = self.line_height_factor, .name = self.name, .ttf_bytes = self.ttf_bytes };
}
pub fn lineHeightFactor(self: *const Font, factor: f32) Font {
return Font{ .size = self.size, .line_height_factor = factor, .name = self.name, .ttf_bytes = self.ttf_bytes };
}
// handles multiple lines
pub fn textSize(self: *const Font, text: []const u8) !Size {
var ret = Size{};
var end: usize = 0;
while (end < text.len) {
var end_idx: usize = undefined;
const s = try self.textSizeEx(text[end..], null, &end_idx, .before);
ret.h += s.h;
ret.w = @max(ret.w, s.w);
end += end_idx;
}
return ret;
}
pub const EndMetric = enum {
before, // end_idx stops before text goes past max_width
nearest, // end_idx stops at start of character closest to max_width
};
/// textSizeEx always stops at a newline, use textSize to get multiline sizes
pub fn textSizeEx(self: *const Font, text: []const u8, max_width: ?f32, end_idx: ?*usize, end_metric: EndMetric) !Size {
// ask for a font that matches the natural display pixels so we get a more
// accurate size
const ss = parentGet().screenRectScale(Rect{}).s;
const ask_size = @ceil(self.size * ss);
const max_width_sized = (max_width orelse 1000000.0) * ss;
const sized_font = self.resize(ask_size);
const s = try sized_font.textSizeRaw(text, max_width_sized, end_idx, end_metric);
// do this check after calling textSizeRaw so that end_idx is set
if (ss == 0) return Size{};
const target_fraction = self.size / ask_size;
//std.debug.print("textSize size {d} for \"{s}\" {d} {}\n", .{ self.size, text, target_fraction, s.scale(target_fraction) });
return s.scale(target_fraction);
}
// doesn't scale the font or max_width, always stops at newlines
pub fn textSizeRaw(self: *const Font, text: []const u8, max_width: ?f32, end_idx: ?*usize, end_metric: EndMetric) !Size {
const fce = try fontCacheGet(self.*);
const mwidth = max_width orelse 1000000.0;
var x: f32 = 0;
var minx: f32 = 0;
var maxx: f32 = 0;
var miny: f32 = 0;
var maxy: f32 = fce.height;
var tw: f32 = 0;
var th: f32 = fce.height;
var ei: usize = 0;
var nearest_break: bool = false;
var utf8 = (try std.unicode.Utf8View.init(text)).iterator();
while (utf8.nextCodepoint()) |codepoint| {
const gi = try fce.glyphInfoGet(@as(u32, @intCast(codepoint)), self.name);
minx = @min(minx, x + gi.minx);
maxx = @max(maxx, x + gi.maxx);
maxx = @max(maxx, x + gi.advance);
miny = @min(miny, gi.miny);
maxy = @max(maxy, gi.maxy);
// TODO: kerning
if (codepoint == '\n') {
// newlines always terminate, and don't use any space
ei += std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable;
break;
}
if ((maxx - minx) > mwidth) {
switch (end_metric) {
.before => break, // went too far
.nearest => {
if ((maxx - minx) - mwidth >= mwidth - tw) {
break; // current one is closest
} else {
// get the next glyph and then break
nearest_break = true;
}
},
}
}
// record that we processed this codepoint
ei += std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable;
// update space taken by glyph
tw = maxx - minx;
th = maxy - miny;
x += gi.advance;
if (nearest_break) break;
}
// TODO: xstart and ystart
if (end_idx) |endout| {
endout.* = ei;
}
//std.debug.print("textSizeRaw size {d} for \"{s}\" {d}x{d} {d}\n", .{ self.size, text, tw, th, ei });
return Size{ .w = tw, .h = th };
}
pub fn lineHeight(self: *const Font) !f32 {
// do the same sized thing as textSizeEx so they will cache the same font
const ss = parentGet().screenRectScale(Rect{}).s;
if (ss == 0) return 0;
const ask_size = @ceil(self.size * ss);
const target_fraction = self.size / ask_size;
const sized_font = self.resize(ask_size);
const fce = try fontCacheGet(sized_font);
const face_height = fce.height;
return face_height * target_fraction * self.line_height_factor;
}
};
const GlyphInfo = struct {
minx: f32,
maxx: f32,
advance: f32,
miny: f32,
maxy: f32,
uv: @Vector(2, f32),
};
const FontCacheEntry = struct {
used: bool = true,
face: c.FT_Face,
height: f32,
ascent: f32,
glyph_info: std.AutoHashMap(u32, GlyphInfo),
texture_atlas: *anyopaque,
texture_atlas_size: Size,
texture_atlas_regen: bool,
pub const OpenFlags = packed struct(c_int) {
memory: bool = false,
stream: bool = false,
path: bool = false,
driver: bool = false,
params: bool = false,
_padding: u27 = 0,
};
pub const LoadFlags = packed struct(c_int) {
no_scale: bool = false,
no_hinting: bool = false,
render: bool = false,
no_bitmap: bool = false,
vertical_layout: bool = false,
force_autohint: bool = false,
crop_bitmap: bool = false,
pedantic: bool = false,
ignore_global_advance_with: bool = false,
no_recurse: bool = false,
ignore_transform: bool = false,
monochrome: bool = false,
linear_design: bool = false,
no_autohint: bool = false,
_padding: u1 = 0,
target_normal: bool = false,
target_light: bool = false,
target_mono: bool = false,
target_lcd: bool = false,
target_lcd_v: bool = false,
color: bool = false,
compute_metrics: bool = false,
bitmap_metrics_only: bool = false,
_padding0: u9 = 0,
};
pub fn intToError(err: c_int) !void {
return switch (err) {
c.FT_Err_Ok => {},
c.FT_Err_Cannot_Open_Resource => error.CannotOpenResource,
c.FT_Err_Unknown_File_Format => error.UnknownFileFormat,
c.FT_Err_Invalid_File_Format => error.InvalidFileFormat,
c.FT_Err_Invalid_Version => error.InvalidVersion,
c.FT_Err_Lower_Module_Version => error.LowerModuleVersion,
c.FT_Err_Invalid_Argument => error.InvalidArgument,
c.FT_Err_Unimplemented_Feature => error.UnimplementedFeature,
c.FT_Err_Invalid_Table => error.InvalidTable,
c.FT_Err_Invalid_Offset => error.InvalidOffset,
c.FT_Err_Array_Too_Large => error.ArrayTooLarge,
c.FT_Err_Missing_Module => error.MissingModule,
c.FT_Err_Missing_Property => error.MissingProperty,
c.FT_Err_Invalid_Glyph_Index => error.InvalidGlyphIndex,
c.FT_Err_Invalid_Character_Code => error.InvalidCharacterCode,
c.FT_Err_Invalid_Glyph_Format => error.InvalidGlyphFormat,
c.FT_Err_Cannot_Render_Glyph => error.CannotRenderGlyph,
c.FT_Err_Invalid_Outline => error.InvalidOutline,
c.FT_Err_Invalid_Composite => error.InvalidComposite,
c.FT_Err_Too_Many_Hints => error.TooManyHints,
c.FT_Err_Invalid_Pixel_Size => error.InvalidPixelSize,
c.FT_Err_Invalid_Handle => error.InvalidHandle,
c.FT_Err_Invalid_Library_Handle => error.InvalidLibraryHandle,
c.FT_Err_Invalid_Driver_Handle => error.InvalidDriverHandle,
c.FT_Err_Invalid_Face_Handle => error.InvalidFaceHandle,
c.FT_Err_Invalid_Size_Handle => error.InvalidSizeHandle,
c.FT_Err_Invalid_Slot_Handle => error.InvalidSlotHandle,
c.FT_Err_Invalid_CharMap_Handle => error.InvalidCharMapHandle,
c.FT_Err_Invalid_Cache_Handle => error.InvalidCacheHandle,
c.FT_Err_Invalid_Stream_Handle => error.InvalidStreamHandle,
c.FT_Err_Too_Many_Drivers => error.TooManyDrivers,
c.FT_Err_Too_Many_Extensions => error.TooManyExtensions,
c.FT_Err_Out_Of_Memory => error.OutOfMemory,
c.FT_Err_Unlisted_Object => error.UnlistedObject,
c.FT_Err_Cannot_Open_Stream => error.CannotOpenStream,
c.FT_Err_Invalid_Stream_Seek => error.InvalidStreamSeek,
c.FT_Err_Invalid_Stream_Skip => error.InvalidStreamSkip,
c.FT_Err_Invalid_Stream_Read => error.InvalidStreamRead,
c.FT_Err_Invalid_Stream_Operation => error.InvalidStreamOperation,
c.FT_Err_Invalid_Frame_Operation => error.InvalidFrameOperation,
c.FT_Err_Nested_Frame_Access => error.NestedFrameAccess,
c.FT_Err_Invalid_Frame_Read => error.InvalidFrameRead,
c.FT_Err_Raster_Uninitialized => error.RasterUninitialized,
c.FT_Err_Raster_Corrupted => error.RasterCorrupted,
c.FT_Err_Raster_Overflow => error.RasterOverflow,
c.FT_Err_Raster_Negative_Height => error.RasterNegativeHeight,
c.FT_Err_Too_Many_Caches => error.TooManyCaches,
c.FT_Err_Invalid_Opcode => error.InvalidOpcode,
c.FT_Err_Too_Few_Arguments => error.TooFewArguments,
c.FT_Err_Stack_Overflow => error.StackOverflow,
c.FT_Err_Code_Overflow => error.CodeOverflow,
c.FT_Err_Bad_Argument => error.BadArgument,
c.FT_Err_Divide_By_Zero => error.DivideByZero,
c.FT_Err_Invalid_Reference => error.InvalidReference,
c.FT_Err_Debug_OpCode => error.DebugOpCode,
c.FT_Err_ENDF_In_Exec_Stream => error.ENDFInExecStream,
c.FT_Err_Nested_DEFS => error.NestedDEFS,
c.FT_Err_Invalid_CodeRange => error.InvalidCodeRange,
c.FT_Err_Execution_Too_Long => error.ExecutionTooLong,
c.FT_Err_Too_Many_Function_Defs => error.TooManyFunctionDefs,
c.FT_Err_Too_Many_Instruction_Defs => error.TooManyInstructionDefs,
c.FT_Err_Table_Missing => error.TableMissing,
c.FT_Err_Horiz_Header_Missing => error.HorizHeaderMissing,
c.FT_Err_Locations_Missing => error.LocationsMissing,
c.FT_Err_Name_Table_Missing => error.NameTableMissing,
c.FT_Err_CMap_Table_Missing => error.CMapTableMissing,
c.FT_Err_Hmtx_Table_Missing => error.HmtxTableMissing,
c.FT_Err_Post_Table_Missing => error.PostTableMissing,
c.FT_Err_Invalid_Horiz_Metrics => error.InvalidHorizMetrics,
c.FT_Err_Invalid_CharMap_Format => error.InvalidCharMapFormat,
c.FT_Err_Invalid_PPem => error.InvalidPPem,
c.FT_Err_Invalid_Vert_Metrics => error.InvalidVertMetrics,
c.FT_Err_Could_Not_Find_Context => error.CouldNotFindContext,
c.FT_Err_Invalid_Post_Table_Format => error.InvalidPostTableFormat,
c.FT_Err_Invalid_Post_Table => error.InvalidPostTable,
c.FT_Err_Syntax_Error => error.Syntax,
c.FT_Err_Stack_Underflow => error.StackUnderflow,
c.FT_Err_Ignore => error.Ignore,
c.FT_Err_No_Unicode_Glyph_Name => error.NoUnicodeGlyphName,
c.FT_Err_Missing_Startfont_Field => error.MissingStartfontField,
c.FT_Err_Missing_Font_Field => error.MissingFontField,
c.FT_Err_Missing_Size_Field => error.MissingSizeField,
c.FT_Err_Missing_Fontboundingbox_Field => error.MissingFontboundingboxField,
c.FT_Err_Missing_Chars_Field => error.MissingCharsField,
c.FT_Err_Missing_Startchar_Field => error.MissingStartcharField,
c.FT_Err_Missing_Encoding_Field => error.MissingEncodingField,
c.FT_Err_Missing_Bbx_Field => error.MissingBbxField,
c.FT_Err_Bbx_Too_Big => error.BbxTooBig,
c.FT_Err_Corrupted_Font_Header => error.CorruptedFontHeader,
c.FT_Err_Corrupted_Font_Glyphs => error.CorruptedFontGlyphs,
else => unreachable,
};
}
pub fn hash(font: Font) u32 {
var h = fnv.init();
h.update(std.mem.asBytes(&font.ttf_bytes.ptr));
h.update(std.mem.asBytes(&font.size));
return h.final();
}
pub fn glyphInfoGet(self: *FontCacheEntry, codepoint: u32, font_name: []const u8) !GlyphInfo {
if (self.glyph_info.get(codepoint)) |gi| {
return gi;
}
FontCacheEntry.intToError(c.FT_Load_Char(self.face, codepoint, @as(i32, @bitCast(LoadFlags{ .render = false })))) catch |err| {
std.log.err("glyphInfoGet: freetype error {!} font {s} codepoint {d}", .{ err, font_name, codepoint });
return error.freetypeError;
};
const m = self.face.*.glyph.*.metrics;
const minx = @as(f32, @floatFromInt(m.horiBearingX)) / 64.0;
const miny = self.ascent - @as(f32, @floatFromInt(m.horiBearingY)) / 64.0;
const gi = GlyphInfo{
.minx = @floor(minx),
.maxx = @ceil(minx + @as(f32, @floatFromInt(m.width)) / 64.0),
.advance = @ceil(@as(f32, @floatFromInt(m.horiAdvance)) / 64.0),
.miny = @floor(miny),
.maxy = @ceil(miny + @as(f32, @floatFromInt(m.height)) / 64.0),
.uv = .{ 0, 0 },
};
// new glyph, need to regen texture atlas on next render
//std.debug.print("new glyph {}\n", .{codepoint});
self.texture_atlas_regen = true;
try self.glyph_info.put(codepoint, gi);
return gi;
}
};
pub fn fontCacheGet(font: Font) !*FontCacheEntry {
var cw = currentWindow();
const fontHash = FontCacheEntry.hash(font);
if (cw.font_cache.getPtr(fontHash)) |fce| {
fce.used = true;
return fce;
}
//std.debug.print("FontCacheGet creating font size {d} name \"{s}\"\n", .{font.size, font.name});
var face: c.FT_Face = undefined;
var args: c.FT_Open_Args = undefined;
args.flags = @as(u32, @bitCast(FontCacheEntry.OpenFlags{ .memory = true }));
args.memory_base = font.ttf_bytes.ptr;
args.memory_size = @as(u31, @intCast(font.ttf_bytes.len));
FontCacheEntry.intToError(c.FT_Open_Face(cw.ft2lib, &args, 0, &face)) catch |err| {
log.err("fontCacheGet: freetype error {!} trying to FT_Open_Face font {s}", .{ err, font.name });
return error.freetypeError;
};
const pixel_size = @as(u32, @intFromFloat(font.size));
FontCacheEntry.intToError(c.FT_Set_Pixel_Sizes(face, pixel_size, pixel_size)) catch |err| {
log.err("fontCacheGet: freetype error {!} trying to FT_Set_Pixel_Sizes font {s}", .{ err, font.name });
return error.freetypeError;
};
const ascender = @as(f32, @floatFromInt(face.*.ascender)) / 64.0;
const ss = @as(f32, @floatFromInt(face.*.size.*.metrics.y_scale)) / 0x10000;
const ascent = ascender * ss;
const height = @as(f32, @floatFromInt(face.*.size.*.metrics.height)) / 64.0;
//std.debug.print("fontcache size {d} ascender {d} scale {d} ascent {d} height {d}\n", .{ font.size, ascender, ss, ascent, height });
// make debug texture atlas so we can see if something later goes wrong
const size = .{ .w = 10, .h = 10 };
var pixels = try cw.arena.alloc(u8, @as(usize, @intFromFloat(size.w * size.h)) * 4);
@memset(pixels, 255);
const entry = FontCacheEntry{
.face = face,
.height = @ceil(height),
.ascent = @floor(ascent),
.glyph_info = std.AutoHashMap(u32, GlyphInfo).init(cw.gpa),
.texture_atlas = cw.backend.textureCreate(pixels, @as(u32, @intFromFloat(size.w)), @as(u32, @intFromFloat(size.h))),
.texture_atlas_size = size,
.texture_atlas_regen = true,
};
try cw.font_cache.put(fontHash, entry);
return cw.font_cache.getPtr(fontHash).?;
}
const IconCacheEntry = struct {
texture: *anyopaque,
size: Size,
used: bool = true,
pub fn hash(tvg_bytes: []const u8, height: u32) u32 {
var h = fnv.init();
h.update(std.mem.asBytes(&tvg_bytes.ptr));
h.update(std.mem.asBytes(&height));
return h.final();
}
};
pub fn iconWidth(name: []const u8, tvg_bytes: []const u8, height: f32) !f32 {
if (height == 0) return 0.0;
var stream = std.io.fixedBufferStream(tvg_bytes);
var parser = tvg.parse(currentWindow().arena, stream.reader()) catch |err| {
log.err("iconWidth: Tinyvg error {!} parsing icon {s}", .{ err, name });
return error.tvgError;
};
defer parser.deinit();
return height * @as(f32, @floatFromInt(parser.header.width)) / @as(f32, @floatFromInt(parser.header.height));
}
pub fn iconTexture(name: []const u8, tvg_bytes: []const u8, height: u32) !IconCacheEntry {
var cw = currentWindow();
const icon_hash = IconCacheEntry.hash(tvg_bytes, height);
if (cw.icon_cache.getPtr(icon_hash)) |ice| {
ice.used = true;
return ice.*;
}
_ = try currentWindow().arena.create(u8);
var image = tvg.rendering.renderBuffer(
cw.arena,
cw.arena,
tvg.rendering.SizeHint{ .height = height },
@as(tvg.rendering.AntiAliasing, @enumFromInt(2)),
tvg_bytes,
) catch |err| {
log.err("iconTexture: Tinyvg error {!} rendering icon {s} at height {d}", .{ err, name, height });
return error.tvgError;
};
defer image.deinit(cw.arena);