-
Notifications
You must be signed in to change notification settings - Fork 1
/
gral_macos.m
1037 lines (922 loc) · 37.5 KB
/
gral_macos.m
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
/*
Copyright (c) 2016-2024 Elias Aebi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "gral.h"
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
#include <stdlib.h>
static NSUInteger get_next_code_point(CFStringRef string, NSUInteger i, uint32_t *code_point) {
unichar c1 = CFStringGetCharacterAtIndex(string, i);
if ((c1 & 0xFC00) == 0xD800) {
unichar c2 = CFStringGetCharacterAtIndex(string, i+1);
*code_point = (((c1 & 0x03FF) << 10) | (c2 & 0x03FF)) + 0x10000;
return 2;
}
else {
*code_point = c1;
return 1;
}
}
static NSUInteger utf8_index_to_utf16(CFStringRef string, int index) {
int i8 = 0;
NSUInteger i16 = 0;
while (i8 < index) {
uint32_t c; // UTF-32 code point
i16 += get_next_code_point(string, i16, &c);
if (c <= 0x7F) i8 += 1;
else if (c <= 0x7FF) i8 += 2;
else if (c <= 0xFFFF) i8 += 3;
else i8 += 4;
}
return i16;
}
static int utf16_index_to_utf8(CFStringRef string, NSUInteger index) {
int i8 = 0;
NSUInteger i16 = 0;
while (i16 < index) {
uint32_t c; // UTF-32 code point
i16 += get_next_code_point(string, i16, &c);
if (c <= 0x7F) i8 += 1;
else if (c <= 0x7FF) i8 += 2;
else if (c <= 0xFFFF) i8 += 3;
else i8 += 4;
}
return i8;
}
@interface GralCallbackObject: NSObject {
@public
void (*callback)(void *user_data);
void *user_data;
}
@end
@implementation GralCallbackObject
- (void)invoke:(id)object {
callback(user_data);
}
@end
/*================
APPLICATION
================*/
@interface GralApplication: NSApplication<NSApplicationDelegate> {
@public
struct gral_application_interface const *interface;
void *user_data;
}
@end
@implementation GralApplication
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender {
return YES;
}
- (void)applicationWillFinishLaunching:(NSNotification *)notification {
interface->start(user_data);
}
- (BOOL)applicationOpenUntitledFile:(NSApplication *)sender {
interface->open_empty(user_data);
return YES;
}
- (void)application:(NSApplication *)sender openFiles:(NSArray<NSString *> *)filenames {
for (NSUInteger i = 0; i < [filenames count]; i++) {
const char *path = [[filenames objectAtIndex:i] UTF8String];
interface->open_file(path, user_data);
}
}
- (void)applicationWillTerminate:(NSNotification *)notification {
interface->quit(user_data);
}
@end
struct gral_application *gral_application_create(char const *id, struct gral_application_interface const *interface, void *user_data) {
GralApplication *application = [GralApplication sharedApplication];
application->interface = interface;
application->user_data = user_data;
[application setDelegate:application];
return (struct gral_application *)application;
}
void gral_application_delete(struct gral_application *application) {
}
int gral_application_run(struct gral_application *application, int argc, char **argv) {
[(GralApplication *)application run];
return 0;
}
/*============
DRAWING
============*/
static void image_release_callback(void *info, const void *data, size_t size) {
free(data);
}
struct gral_image *gral_image_create(int width, int height, void *data) {
CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef data_provider = CGDataProviderCreateWithData(NULL, data, width * height * 4, image_release_callback);
CGImageRef image = CGImageCreate(width, height, 8, 8 * 4, width * 4, color_space, kCGBitmapByteOrder32Big | kCGImageAlphaLast, data_provider, NULL, NO, kCGRenderingIntentDefault);
CGDataProviderRelease(data_provider);
CGColorSpaceRelease(color_space);
return (struct gral_image *)image;
}
void gral_image_delete(struct gral_image *image) {
CGImageRelease((CGImageRef)image);
}
struct gral_font *gral_font_create(struct gral_window *window, char const *name, float size) {
CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingUTF8);
CTFontRef font = CTFontCreateWithName(string, size, NULL);
CFRelease(string);
return (struct gral_font *)font;
}
struct gral_font *gral_font_create_default(struct gral_window *window, float size) {
return (struct gral_font *)CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, size, NULL);
}
struct gral_font *gral_font_create_monospace(struct gral_window *window, float size) {
return (struct gral_font *)CTFontCreateUIFontForLanguage(kCTFontUIFontUserFixedPitch, size, NULL);
}
void gral_font_delete(struct gral_font *font) {
CFRelease(font);
}
void gral_font_get_metrics(struct gral_window *window, struct gral_font *font, float *ascent, float *descent) {
if (ascent) *ascent = CTFontGetAscent((CTFontRef)font);
if (descent) *descent = CTFontGetDescent((CTFontRef)font);
}
struct gral_text *gral_text_create(struct gral_window *window, char const *text, struct gral_font *font) {
CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, text, kCFStringEncodingUTF8);
CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(NULL, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attributes, kCTFontAttributeName, font);
CFAttributedStringRef attributed_string = CFAttributedStringCreate(NULL, string, attributes);
CFRelease(string);
CFRelease(attributes);
CFMutableAttributedStringRef mutable_attributed_string = CFAttributedStringCreateMutableCopy(NULL, 0, attributed_string);
CFRelease(attributed_string);
return (struct gral_text *)mutable_attributed_string;
}
void gral_text_delete(struct gral_text *text) {
CFRelease(text);
}
void gral_text_set_bold(struct gral_text *text, int start_index, int end_index) {
CFStringRef string = CFAttributedStringGetString((CFAttributedStringRef)text);
CFIndex loc = utf8_index_to_utf16(string, start_index);
CFIndex len = utf8_index_to_utf16(string, end_index) - loc;
CTFontRef font = CFAttributedStringGetAttribute((CFAttributedStringRef)text, loc, kCTFontAttributeName, NULL);
CTFontRef bold_font = CTFontCreateCopyWithSymbolicTraits(font, 0, NULL, kCTFontTraitBold, kCTFontTraitBold);
if (bold_font) {
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)text, CFRangeMake(loc, len), kCTFontAttributeName, bold_font);
CFRelease(bold_font);
}
}
void gral_text_set_italic(struct gral_text *text, int start_index, int end_index) {
CFStringRef string = CFAttributedStringGetString((CFAttributedStringRef)text);
CFIndex loc = utf8_index_to_utf16(string, start_index);
CFIndex len = utf8_index_to_utf16(string, end_index) - loc;
CTFontRef font = CFAttributedStringGetAttribute((CFAttributedStringRef)text, loc, kCTFontAttributeName, NULL);
CTFontRef italic_font = CTFontCreateCopyWithSymbolicTraits(font, 0, NULL, kCTFontTraitItalic, kCTFontTraitItalic);
if (italic_font) {
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)text, CFRangeMake(loc, len), kCTFontAttributeName, italic_font);
CFRelease(italic_font);
}
}
void gral_text_set_color(struct gral_text *text, int start_index, int end_index, float red, float green, float blue, float alpha) {
CFStringRef string = CFAttributedStringGetString((CFAttributedStringRef)text);
CFIndex loc = utf8_index_to_utf16(string, start_index);
CFIndex len = utf8_index_to_utf16(string, end_index) - loc;
CGColorRef color = CGColorCreateGenericRGB(red, green, blue, alpha);
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)text, CFRangeMake(loc, len), kCTForegroundColorAttributeName, color);
CGColorRelease(color);
}
float gral_text_get_width(struct gral_text *text, struct gral_draw_context *draw_context) {
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)text);
CGRect bounds = CTLineGetImageBounds(line, (CGContextRef)draw_context);
CFRelease(line);
return bounds.size.width;
}
float gral_text_index_to_x(struct gral_text *text, int index) {
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)text);
CFStringRef string = CFAttributedStringGetString((CFAttributedStringRef)text);
CGFloat offset = CTLineGetOffsetForStringIndex(line, utf8_index_to_utf16(string, index), NULL);
CFRelease(line);
return offset;
}
int gral_text_x_to_index(struct gral_text *text, float x) {
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)text);
CFIndex index = CTLineGetStringIndexForPosition(line, CGPointMake(x, 0.0f));
CFRelease(line);
if (index == kCFNotFound) {
return 0;
}
CFStringRef string = CFAttributedStringGetString((CFAttributedStringRef)text);
return utf16_index_to_utf8(string, index);
}
void gral_draw_context_draw_image(struct gral_draw_context *draw_context, struct gral_image *image, float x, float y) {
size_t width = CGImageGetWidth((CGImageRef)image);
size_t height = CGImageGetHeight((CGImageRef)image);
CGContextScaleCTM((CGContextRef)draw_context, 1.0f, -1.0f);
CGContextDrawImage((CGContextRef)draw_context, CGRectMake(x, -(y + height), width, height), (CGImageRef)image);
CGContextScaleCTM((CGContextRef)draw_context, 1.0f, -1.0f);
}
void gral_draw_context_draw_text(struct gral_draw_context *draw_context, struct gral_text *text, float x, float y, float red, float green, float blue, float alpha) {
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)text);
CGContextSetTextMatrix((CGContextRef)draw_context, CGAffineTransformMakeScale(1.0f, -1.0f));
CFArrayRef glyph_runs = CTLineGetGlyphRuns(line);
for (int i = 0; i < CFArrayGetCount(glyph_runs); i++) {
CTRunRef run = CFArrayGetValueAtIndex(glyph_runs, i);
CGPoint const *positions = CTRunGetPositionsPtr(run);
CGGlyph const *glyphs = CTRunGetGlyphsPtr(run);
int count = CTRunGetGlyphCount(run);
CFDictionaryRef attributes = CTRunGetAttributes(run);
CTFontRef font = CFDictionaryGetValue(attributes, kCTFontAttributeName);
CGColorRef color = (CGColorRef)CFDictionaryGetValue(attributes, kCTForegroundColorAttributeName);
if (color) {
CGContextSetFillColorWithColor((CGContextRef)draw_context, color);
}
else {
CGContextSetRGBFillColor((CGContextRef)draw_context, red, green, blue, alpha);
}
CGContextSetTextPosition((CGContextRef)draw_context, x, y);
CTFontDrawGlyphs(font, glyphs, positions, count, (CGContextRef)draw_context);
}
CFRelease(line);
}
void gral_draw_context_add_text(struct gral_draw_context *draw_context, struct gral_text *text, float x, float y) {
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)text);
CGContextSetTextMatrix((CGContextRef)draw_context, CGAffineTransformMakeScale(1.0f, -1.0f));
CFArrayRef glyph_runs = CTLineGetGlyphRuns(line);
for (int i = 0; i < CFArrayGetCount(glyph_runs); i++) {
CTRunRef run = CFArrayGetValueAtIndex(glyph_runs, i);
CGPoint const *positions = CTRunGetPositionsPtr(run);
CGGlyph const *glyphs = CTRunGetGlyphsPtr(run);
int count = CTRunGetGlyphCount(run);
CFDictionaryRef attributes = CTRunGetAttributes(run);
CTFontRef font = CFDictionaryGetValue(attributes, kCTFontAttributeName);
for (int j = 0; j < count; j++) {
CGContextSetTextPosition((CGContextRef)draw_context, x + positions[j].x, y + positions[j].y);
CGAffineTransform matrix = CGContextGetTextMatrix((CGContextRef)draw_context);
CGPathRef path = CTFontCreatePathForGlyph(font, glyphs[j], &matrix);
CGContextAddPath((CGContextRef)draw_context, path);
CGPathRelease(path);
}
}
CFRelease(line);
}
void gral_draw_context_close_path(struct gral_draw_context *draw_context) {
CGContextClosePath((CGContextRef)draw_context);
}
void gral_draw_context_move_to(struct gral_draw_context *draw_context, float x, float y) {
CGContextMoveToPoint((CGContextRef)draw_context, x, y);
}
void gral_draw_context_line_to(struct gral_draw_context *draw_context, float x, float y) {
CGContextAddLineToPoint((CGContextRef)draw_context, x, y);
}
void gral_draw_context_curve_to(struct gral_draw_context *draw_context, float x1, float y1, float x2, float y2, float x, float y) {
CGContextAddCurveToPoint((CGContextRef)draw_context, x1, y1, x2, y2, x, y);
}
void gral_draw_context_fill(struct gral_draw_context *draw_context, float red, float green, float blue, float alpha) {
CGContextSetRGBFillColor((CGContextRef)draw_context, red, green, blue, alpha);
CGContextFillPath((CGContextRef)draw_context);
}
void gral_draw_context_fill_linear_gradient(struct gral_draw_context *draw_context, float start_x, float start_y, float end_x, float end_y, struct gral_gradient_stop const *stops, int count) {
CGFloat components[count*4];
CGFloat locations[count];
for (int i = 0; i < count; i++) {
components[i*4+0] = stops[i].red;
components[i*4+1] = stops[i].green;
components[i*4+2] = stops[i].blue;
components[i*4+3] = stops[i].alpha;
locations[i] = stops[i].position;
}
CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(color_space, components, locations, count);
CGContextSaveGState((CGContextRef)draw_context);
CGContextClip((CGContextRef)draw_context);
CGContextDrawLinearGradient((CGContextRef)draw_context, gradient, CGPointMake(start_x, start_y), CGPointMake(end_x, end_y), kCGGradientDrawsBeforeStartLocation|kCGGradientDrawsAfterEndLocation);
CGContextRestoreGState((CGContextRef)draw_context);
CGGradientRelease(gradient);
CGColorSpaceRelease(color_space);
}
void gral_draw_context_stroke(struct gral_draw_context *draw_context, float line_width, float red, float green, float blue, float alpha) {
CGContextSetLineWidth((CGContextRef)draw_context, line_width);
CGContextSetLineCap((CGContextRef)draw_context, kCGLineCapRound);
CGContextSetLineJoin((CGContextRef)draw_context, kCGLineJoinRound);
CGContextSetRGBStrokeColor((CGContextRef)draw_context, red, green, blue, alpha);
CGContextStrokePath((CGContextRef)draw_context);
}
void gral_draw_context_stroke_linear_gradient(struct gral_draw_context *draw_context, float line_width, float start_x, float start_y, float end_x, float end_y, struct gral_gradient_stop const *stops, int count) {
CGContextSetLineWidth((CGContextRef)draw_context, line_width);
CGContextSetLineCap((CGContextRef)draw_context, kCGLineCapRound);
CGContextSetLineJoin((CGContextRef)draw_context, kCGLineJoinRound);
CGContextReplacePathWithStrokedPath((CGContextRef)draw_context);
gral_draw_context_fill_linear_gradient(draw_context, start_x, start_y, end_x, end_y, stops, count);
}
void gral_draw_context_draw_clipped(struct gral_draw_context *draw_context, void (*callback)(struct gral_draw_context *draw_context, void *user_data), void *user_data) {
CGContextSaveGState((CGContextRef)draw_context);
CGContextClip((CGContextRef)draw_context);
callback(draw_context, user_data);
CGContextRestoreGState((CGContextRef)draw_context);
}
void gral_draw_context_draw_transformed(struct gral_draw_context *draw_context, float a, float b, float c, float d, float e, float f, void (*callback)(struct gral_draw_context *draw_context, void *user_data), void *user_data) {
CGContextSaveGState((CGContextRef)draw_context);
CGContextConcatCTM((CGContextRef)draw_context, CGAffineTransformMake(a, b, c, d, e, f));
callback(draw_context, user_data);
CGContextRestoreGState((CGContextRef)draw_context);
}
/*===========
WINDOW
===========*/
static int get_key(UInt16 key_code) {
switch (key_code) {
case kVK_Return:
return GRAL_KEY_ENTER;
case kVK_Tab:
return GRAL_KEY_TAB;
case kVK_Delete:
return GRAL_KEY_BACKSPACE;
case kVK_ForwardDelete:
return GRAL_KEY_DELETE;
case kVK_LeftArrow:
return GRAL_KEY_ARROW_LEFT;
case kVK_UpArrow:
return GRAL_KEY_ARROW_UP;
case kVK_RightArrow:
return GRAL_KEY_ARROW_RIGHT;
case kVK_DownArrow:
return GRAL_KEY_ARROW_DOWN;
case kVK_PageUp:
return GRAL_KEY_PAGE_UP;
case kVK_PageDown:
return GRAL_KEY_PAGE_DOWN;
case kVK_Home:
return GRAL_KEY_HOME;
case kVK_End:
return GRAL_KEY_END;
case kVK_Escape:
return GRAL_KEY_ESCAPE;
default:
{
TISInputSourceRef input_source = TISCopyCurrentKeyboardInputSource();
CFDataRef uchr = TISGetInputSourceProperty(input_source, kTISPropertyUnicodeKeyLayoutData);
UCKeyboardLayout const *keyboard_layout = (UCKeyboardLayout const *)CFDataGetBytePtr(uchr);
UInt32 dead_key_state = 0;
UniChar string[255];
UniCharCount string_length = 0;
UCKeyTranslate(keyboard_layout, key_code, kUCKeyActionDown, 0, LMGetKbdType(), 0, &dead_key_state, 255, &string_length, string);
if (string_length > 0) {
CFStringRef characters = CFStringCreateWithCharactersNoCopy(NULL, string, string_length, kCFAllocatorNull);
uint32_t code_point;
get_next_code_point(characters, 0, &code_point);
CFRelease(characters);
return code_point;
}
return 0;
}
}
}
static int get_modifiers(NSEventModifierFlags modifier_flags) {
int modifiers = 0;
if (modifier_flags & NSEventModifierFlagControl) modifiers |= GRAL_MODIFIER_CONTROL;
if (modifier_flags & NSEventModifierFlagOption) modifiers |= GRAL_MODIFIER_ALT;
if (modifier_flags & NSEventModifierFlagCommand) modifiers |= GRAL_MODIFIER_CONTROL;
if (modifier_flags & NSEventModifierFlagShift) modifiers |= GRAL_MODIFIER_SHIFT;
return modifiers;
}
@interface GralWindow: NSWindow<NSWindowDelegate> {
@public
struct gral_window_interface const *interface;
void *user_data;
}
@end
@implementation GralWindow
- (BOOL)windowShouldClose:(id)sender {
return interface->close(user_data);
}
- (void)windowDidBecomeKey:(NSNotification *)notification {
interface->focus_enter(user_data);
}
- (void)windowDidResignKey:(NSNotification *)notification {
interface->focus_leave(user_data);
}
- (void)dealloc {
interface->destroy(user_data);
[super dealloc];
}
@end
@interface GralView: NSView<NSTextInputClient> {
@public
struct gral_window_interface const *interface;
void *user_data;
BOOL is_pointer_locked;
}
@end
@implementation GralView
- (BOOL)acceptsFirstResponder {
return YES;
}
- (BOOL)isFlipped {
return YES;
}
- (void)drawRect:(NSRect)rect {
CGContextRef context = [[NSGraphicsContext currentContext] CGContext];
interface->draw((struct gral_draw_context *)context, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, user_data);
}
- (void)setFrameSize:(NSSize)size {
[super setFrameSize:size];
interface->resize(size.width, size.height, user_data);
}
- (BOOL)acceptsFirstMouse:(NSEvent *)event {
return YES;
}
- (void)mouseEntered:(NSEvent *)event {
interface->mouse_enter(user_data);
}
- (void)mouseExited:(NSEvent *)event {
interface->mouse_leave(user_data);
}
- (void)mouseMoved:(NSEvent *)event {
if (is_pointer_locked) {
interface->mouse_move_relative([event deltaX], [event deltaY], user_data);
}
else {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
interface->mouse_move(location.x, location.y, user_data);
}
}
- (void)mouseDragged:(NSEvent *)event {
[self mouseMoved:event];
}
- (void)rightMouseDragged:(NSEvent *)event {
[self mouseMoved:event];
}
- (void)otherMouseDragged:(NSEvent *)event {
[self mouseMoved:event];
}
- (void)mouseDown:(NSEvent *)event {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
int modifiers = get_modifiers([event modifierFlags]);
interface->mouse_button_press(location.x, location.y, GRAL_PRIMARY_MOUSE_BUTTON, modifiers, user_data);
if ([event clickCount] == 2) {
interface->double_click(location.x, location.y, GRAL_PRIMARY_MOUSE_BUTTON, modifiers, user_data);
}
}
- (void)rightMouseDown:(NSEvent *)event {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
int modifiers = get_modifiers([event modifierFlags]);
interface->mouse_button_press(location.x, location.y, GRAL_SECONDARY_MOUSE_BUTTON, modifiers, user_data);
if ([event clickCount] == 2) {
interface->double_click(location.x, location.y, GRAL_SECONDARY_MOUSE_BUTTON, modifiers, user_data);
}
}
- (void)otherMouseDown:(NSEvent *)event {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
int modifiers = get_modifiers([event modifierFlags]);
interface->mouse_button_press(location.x, location.y, GRAL_MIDDLE_MOUSE_BUTTON, modifiers, user_data);
if ([event clickCount] == 2) {
interface->double_click(location.x, location.y, GRAL_MIDDLE_MOUSE_BUTTON, modifiers, user_data);
}
}
- (void)mouseUp:(NSEvent *)event {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
interface->mouse_button_release(location.x, location.y, GRAL_PRIMARY_MOUSE_BUTTON, user_data);
}
- (void)rightMouseUp:(NSEvent *)event {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
interface->mouse_button_release(location.x, location.y, GRAL_SECONDARY_MOUSE_BUTTON, user_data);
}
- (void)otherMouseUp:(NSEvent *)event {
NSPoint location = [self convertPoint:[event locationInWindow] fromView:nil];
interface->mouse_button_release(location.x, location.y, GRAL_MIDDLE_MOUSE_BUTTON, user_data);
}
- (void)scrollWheel:(NSEvent *)event {
interface->scroll([event scrollingDeltaX], [event scrollingDeltaY], user_data);
}
- (void)keyDown:(NSEvent *)event {
[self interpretKeyEvents:[NSArray arrayWithObject:event]];
unsigned short key_code = [event keyCode];
int key = get_key(key_code);
if (key) {
interface->key_press(key, key_code, get_modifiers([event modifierFlags]), user_data);
}
}
- (void)keyUp:(NSEvent *)event {
unsigned short key_code = [event keyCode];
int key = get_key(key_code);
if (key) {
interface->key_release(key, key_code, user_data);
}
}
// NSTextInputClient implementation
- (BOOL)hasMarkedText {
return NO;
}
- (NSRange)markedRange {
return NSMakeRange(NSNotFound, 0);
}
- (NSRange)selectedRange {
return NSMakeRange(NSNotFound, 0);
}
- (void)setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
}
- (void)unmarkText {
}
- (NSArray *)validAttributesForMarkedText {
return [NSArray array];
}
- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range actualRange:(NSRangePointer)actualRange {
return nil;
}
- (void)insertText:(id)string replacementRange:(NSRange)replacementRange {
if ([string isKindOfClass:[NSString class]]) {
interface->text([(NSString *)string UTF8String], user_data);
}
}
- (NSUInteger)characterIndexForPoint:(NSPoint)point {
return NSNotFound;
}
- (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange {
return NSMakeRect(0, 0, 0, 0);
}
- (void)doCommandBySelector:(SEL)selector {
}
@end
struct gral_window *gral_window_create(struct gral_application *application, int width, int height, char const *title, struct gral_window_interface const *interface, void *user_data) {
GralWindow *window = [[GralWindow alloc]
initWithContentRect:CGRectMake(0, 0, width, height)
styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable
backing:NSBackingStoreBuffered
defer:NO
];
window->interface = interface;
window->user_data = user_data;
[window setDelegate:window];
[window setTitle:[NSString stringWithUTF8String:title]];
return (struct gral_window *)window;
}
void gral_window_show(struct gral_window *window_) {
GralWindow *window = (GralWindow *)window_;
GralView *view = [[GralView alloc] init];
view->interface = window->interface;
view->user_data = window->user_data;
view->is_pointer_locked = NO;
NSTrackingArea *trackingArea = [[NSTrackingArea alloc]
initWithRect:NSZeroRect
options:NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveAlways|NSTrackingInVisibleRect
owner:view
userInfo:nil
];
[view addTrackingArea:trackingArea];
[trackingArea release];
[window setContentView:view];
[view release];
[window makeKeyAndOrderFront:nil];
}
void gral_window_set_title(struct gral_window *window, char const *title) {
[(GralWindow *)window setTitle:[NSString stringWithUTF8String:title]];
}
void gral_window_request_redraw(struct gral_window *window, int x, int y, int width, int height) {
[[(GralWindow *)window contentView] setNeedsDisplayInRect:NSMakeRect(x, y, width, height)];
}
void gral_window_set_minimum_size(struct gral_window *window, int minimum_width, int minimum_height) {
[(GralWindow *)window setContentMinSize:NSMakeSize(minimum_width, minimum_height)];
}
static NSCursor *get_cursor(int cursor) {
static NSCursor *transparent_cursor = NULL;
switch (cursor) {
case GRAL_CURSOR_DEFAULT:
return [NSCursor arrowCursor];
case GRAL_CURSOR_HAND:
return [NSCursor pointingHandCursor];
case GRAL_CURSOR_TEXT:
return [NSCursor IBeamCursor];
case GRAL_CURSOR_HORIZONTAL_ARROWS:
return [NSCursor resizeLeftRightCursor];
case GRAL_CURSOR_VERTICAL_ARROWS:
return [NSCursor resizeUpDownCursor];
case GRAL_CURSOR_NONE:
if (transparent_cursor == NULL) {
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)];
transparent_cursor = [[NSCursor alloc] initWithImage:image hotSpot:NSMakePoint(0, 0)];
[image release];
}
return transparent_cursor;
default:
return NULL;
}
}
void gral_window_set_cursor(struct gral_window *window, int cursor) {
[get_cursor(cursor) set];
}
void gral_window_hide_cursor(struct gral_window *window) {
CGDisplayHideCursor(kCGNullDirectDisplay);
}
void gral_window_show_cursor(struct gral_window *window) {
CGDisplayShowCursor(kCGNullDirectDisplay);
}
void gral_window_warp_cursor(struct gral_window *window_, float x, float y) {
GralWindow *window = (GralWindow *)window_;
NSPoint point = [[window contentView] convertPoint:NSMakePoint(x, y) toView:nil];
point = NSMakePoint(NSMinX(window.frame) + point.x, NSMaxY(NSScreen.screens[0].frame) - (NSMinY(window.frame) + point.y));
CGWarpMouseCursorPosition(point);
}
void gral_window_lock_pointer(struct gral_window *window) {
GralView *view = (GralView *)[(GralWindow *)window contentView];
CGAssociateMouseAndMouseCursorPosition(NO);
view->is_pointer_locked = YES;
}
void gral_window_unlock_pointer(struct gral_window *window) {
GralView *view = (GralView *)[(GralWindow *)window contentView];
CGAssociateMouseAndMouseCursorPosition(YES);
view->is_pointer_locked = NO;
}
void gral_window_show_open_file_dialog(struct gral_window *window, void (*callback)(char const *file, void *user_data), void *user_data) {
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSModalResponseOK) {
callback([[[panel URL] path] UTF8String], user_data);
}
}
void gral_window_show_save_file_dialog(struct gral_window *window, void (*callback)(char const *file, void *user_data), void *user_data) {
NSSavePanel *panel = [NSSavePanel savePanel];
if ([panel runModal] == NSModalResponseOK) {
callback([[[panel URL] path] UTF8String], user_data);
}
}
void gral_window_clipboard_copy(struct gral_window *window, char const *text) {
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
[pasteboard setString:[NSString stringWithUTF8String:text] forType:NSPasteboardTypeString];
}
void gral_window_clipboard_paste(struct gral_window *window, void (*callback)(char const *text, void *user_data), void *user_data) {
NSString *text = [[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];
if (text) {
callback([text UTF8String], user_data);
}
}
struct gral_timer *gral_timer_create(int milliseconds, void (*callback)(void *user_data), void *user_data) {
GralCallbackObject *callback_object = [[GralCallbackObject alloc] init];
callback_object->callback = callback;
callback_object->user_data = user_data;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:milliseconds/1000.0 target:callback_object selector:@selector(invoke:) userInfo:nil repeats:YES];
[callback_object release];
return (struct gral_timer *)timer;
}
void gral_timer_delete(struct gral_timer *timer) {
[(NSTimer *)timer invalidate];
}
void gral_run_on_main_thread(void (*callback)(void *user_data), void *user_data) {
GralCallbackObject *callback_object = [[GralCallbackObject alloc] init];
callback_object->callback = callback;
callback_object->user_data = user_data;
[callback_object performSelectorOnMainThread:@selector(invoke:) withObject:nil waitUntilDone:NO];
[callback_object release];
}
/*=========
FILE
=========*/
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/event.h>
struct gral_file *gral_file_open_read(char const *path) {
int fd = open(path, O_RDONLY);
return fd == -1 ? NULL : (struct gral_file *)(intptr_t)fd;
}
struct gral_file *gral_file_open_write(char const *path) {
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0666);
return fd == -1 ? NULL : (struct gral_file *)(intptr_t)fd;
}
struct gral_file *gral_file_get_standard_input(void) {
return (struct gral_file *)STDIN_FILENO;
}
struct gral_file *gral_file_get_standard_output(void) {
return (struct gral_file *)STDOUT_FILENO;
}
struct gral_file *gral_file_get_standard_error(void) {
return (struct gral_file *)STDERR_FILENO;
}
void gral_file_close(struct gral_file *file) {
close((int)(intptr_t)file);
}
size_t gral_file_read(struct gral_file *file, void *buffer, size_t size) {
return read((int)(intptr_t)file, buffer, size);
}
void gral_file_write(struct gral_file *file, void const *buffer, size_t size) {
write((int)(intptr_t)file, buffer, size);
}
size_t gral_file_get_size(struct gral_file *file) {
struct stat s;
fstat((int)(intptr_t)file, &s);
return s.st_size;
}
void *gral_file_map(struct gral_file *file, size_t size) {
return mmap(NULL, size, PROT_READ, MAP_PRIVATE, (int)(intptr_t)file, 0);
}
void gral_file_unmap(void *address, size_t size) {
munmap(address, size);
}
int gral_file_get_type(char const *path) {
struct stat s;
if (stat(path, &s) == 0) {
if (S_ISREG(s.st_mode)) return GRAL_FILE_TYPE_REGULAR;
if (S_ISDIR(s.st_mode)) return GRAL_FILE_TYPE_DIRECTORY;
}
return GRAL_FILE_TYPE_INVALID;
}
void gral_file_rename(char const *old_path, char const *new_path) {
rename(old_path, new_path);
}
void gral_file_remove(char const *path) {
unlink(path);
}
void gral_directory_create(char const *path) {
mkdir(path, 0777);
}
void gral_directory_iterate(char const *path, void (*callback)(char const *name, void *user_data), void *user_data) {
DIR *directory = opendir(path);
struct dirent *entry;
while (entry = readdir(directory)) {
callback(entry->d_name, user_data);
}
closedir(directory);
}
void gral_directory_remove(char const *path) {
rmdir(path);
}
char *gral_get_current_working_directory(void) {
return getcwd(NULL, 0);
}
@interface GralDirectoryWatcher: GralCallbackObject {
@public
int fd;
}
@end
@implementation GralDirectoryWatcher
- (void)dealloc {
close(fd);
[super dealloc];
}
@end
static void gral_directory_watcher_release(void *info) {
GralDirectoryWatcher *directory_watcher = info;
[directory_watcher release];
}
static void *gral_directory_watcher_retain(void *info) {
GralDirectoryWatcher *directory_watcher = info;
[directory_watcher retain];
return info;
}
static void directory_watcher_callback(CFFileDescriptorRef fdref, CFOptionFlags flags, void *info) {
GralDirectoryWatcher *directory_watcher = info;
int kq = CFFileDescriptorGetNativeDescriptor(fdref);
struct kevent event;
kevent(kq, NULL, 0, &event, 1, NULL);
directory_watcher->callback(directory_watcher->user_data);
CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
}
struct gral_directory_watcher *gral_directory_watch(char const *path, void (*callback)(void *user_data), void *user_data) {
GralDirectoryWatcher *directory_watcher = [[GralDirectoryWatcher alloc] init];
directory_watcher->callback = callback;
directory_watcher->user_data = user_data;
directory_watcher->fd = open(path, O_EVTONLY);
int kq = kqueue();
struct kevent event;
event.ident = directory_watcher->fd;
event.filter = EVFILT_VNODE;
event.flags = EV_ADD | EV_CLEAR;
event.fflags = NOTE_WRITE;
event.data = 0;
event.udata = NULL;
kevent(kq, &event, 1, NULL, 0, NULL);
CFFileDescriptorContext context;
context.copyDescription = NULL;
context.info = directory_watcher;
context.release = gral_directory_watcher_release;
context.retain = gral_directory_watcher_retain;
context.version = 0;
CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, kq, TRUE, &directory_watcher_callback, &context);
CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);
CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
CFRelease(source);
CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
[directory_watcher release];
return (struct gral_directory_watcher *)fdref;
}
void gral_directory_watcher_delete(struct gral_directory_watcher *directory_watcher) {
CFFileDescriptorInvalidate((CFFileDescriptorRef)directory_watcher);
CFRelease((CFFileDescriptorRef)directory_watcher);
}
/*=========
TIME
=========*/
double gral_time_get_monotonic(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec / 1e9;
}
/*==========
AUDIO
==========*/
#import <AudioToolbox/AudioToolbox.h>
#define FRAMES 1024
typedef struct {
int (*callback)(float *buffer, int frames, void *user_data);
void *user_data;
} AudioCallbackData;
static void audio_callback(void *user_data, AudioQueueRef queue, AudioQueueBufferRef buffer) {
AudioCallbackData *callback_data = user_data;
int frames = buffer->mAudioDataBytesCapacity / (2 * sizeof(float));
frames = callback_data->callback(buffer->mAudioData, frames, callback_data->user_data);
if (frames > 0) {
buffer->mAudioDataByteSize = frames * 2 * sizeof(float);
AudioQueueEnqueueBuffer(queue, buffer, buffer->mPacketDescriptionCount, buffer->mPacketDescriptions);
}
else {
AudioQueueStop(queue, NO);
CFRunLoopStop(CFRunLoopGetCurrent());
}
}
void gral_audio_play(int (*callback)(float *buffer, int frames, void *user_data), void *user_data) {
AudioCallbackData callback_data = {callback, user_data};
AudioQueueRef queue;
AudioStreamBasicDescription format;
format.mFormatID = kAudioFormatLinearPCM;
format.mFormatFlags = kLinearPCMFormatFlagIsFloat;
format.mSampleRate = 44100;
format.mBitsPerChannel = 32;
format.mChannelsPerFrame = 2;
format.mBytesPerFrame = format.mBitsPerChannel / 8 * format.mChannelsPerFrame;
format.mFramesPerPacket = 1;
format.mBytesPerPacket = format.mBytesPerFrame * format.mFramesPerPacket;
format.mReserved = 0;
AudioQueueNewOutput(&format, &audio_callback, &callback_data, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &queue);
AudioQueueBufferRef buffers[3];
for (int i = 0; i < 3; i++) {
AudioQueueAllocateBuffer(queue, FRAMES * 2 * sizeof(float), &buffers[i]);
audio_callback(&callback_data, queue, buffers[i]);
}
AudioQueueStart(queue, NULL);
CFRunLoopRun();
AudioQueueDispose(queue, NO);
}
/*=========
MIDI
=========*/
struct gral_midi {
struct gral_midi_interface const *interface;
void *user_data;
MIDIClientRef client;
MIDIPortRef port;
};
static void midi_callback(MIDINotification const *notification, void *user_data) {
struct gral_midi *midi = user_data;
if (notification->messageID == kMIDIMsgObjectAdded) {
MIDIObjectAddRemoveNotification *add_remove_notification = (MIDIObjectAddRemoveNotification *)notification;
if (add_remove_notification->childType == kMIDIObjectType_Source) {
MIDIPortConnectSource(midi->port, add_remove_notification->child, NULL);
}
}
}
static void midi_read_callback(MIDIPacketList const *packet_list, void *user_data, void *srcConnRefCon) {
struct gral_midi *midi = user_data;
MIDIPacket const *packet = packet_list->packet;
for (UInt32 i = 0; i < packet_list->numPackets; i++) {
for (UInt16 j = 0; j < packet->length; j++) {
if ((packet->data[j] & 0xF0) == 0x80 && j + 2 < packet->length) {
Byte note = packet->data[j+1];
Byte velocity = packet->data[j+2];
midi->interface->note_off(note, velocity, midi->user_data);
j += 2;
}
else if ((packet->data[j] & 0xF0) == 0x90 && j + 2 < packet->length) {
Byte note = packet->data[j+1];
Byte velocity = packet->data[j+2];