Repository navigation
Expand file tree
/
Copy pathmain.m
More file actions
1022 lines (963 loc) · 36.1 KB
/
Copy pathmain.m
File metadata and controls
1022 lines (963 loc) · 36.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
#import <QuickLookUI/QuickLookUI.h>
#import <Security/Security.h>
#import <objc/runtime.h>
#include <dlfcn.h>
#include <libgen.h>
#include <limits.h>
#include <pwd.h>
#include <sys/stat.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
enum {
kAxisKey,
kNavigationControllerKey,
kScrollViewportSizeKey,
kScrollContentKey,
kButtonContentKey,
kFlexibleKey,
kTableSourceKey,
kCallbackKey,
kToolbarDelegateKey,
kColumnAlignmentKey,
kColumnSystemImageKey,
kResizeObserverKey,
kPaddingKey,
kPaddingHorizontalKey,
kPaddingLeadingKey,
kPaddingTrailingKey,
kPaddingVerticalKey,
kPaddingTopKey,
kPaddingBottomKey,
kSpacingKey,
kFlowMaxRowsKey,
kTrailingMaxWidthFractionKey,
kFlowOverflowKey,
kAlignmentKey,
kFixedWidthKey,
kFixedHeightKey,
kMinWidthKey,
kMinHeightKey,
kMaxWidthKey,
kMaxHeightKey,
kFlexGrowKey,
kFlexShrinkKey,
kFlexBasisKey,
kFillWidthKey,
kFillHeightKey,
kFitDiameterKey,
kUnitScaleKey,
kFixedSizeKey,
kIgnoresSafeAreaKey,
kBackgroundColorKey,
kCornerRadiusKey,
kClipsToBoundsKey,
kImageLayoutSizeKey,
kTableSpinnerKey,
kTableSelectionKey,
kTableActivationKey,
kTableRefreshKey,
kTableSortKey,
kTableColumnButtonKey,
kTableRowMenuKey,
kTableMoveKey,
kTextChangeKey,
kTextChangeObserverKey,
kTextFieldDelegateKey,
kTextProgrammaticKey,
kTextWrapKey,
kMenuTargetKey,
kSplitPaneFrameObserverKey,
kSplitProportionsKey,
kSplitProportionsAppliedKey,
kColumnFlexKey,
kColumnWidthKey,
kColumnCellKey,
kColumnSortableKey,
kTabViewDelegateKey,
kTableScrollViewKey,
kWorkspaceSafeAreaContentKey,
kTextViewSourceKey,
kWindowCloseKey,
kScrollAnchorKey,
kScrollOnKeyboardKey,
kContainerRelativeWidthKey,
kKeyCount
};
static char kKeys[kKeyCount];
static const CGFloat kStackSpacing = 8.0;
static const CGFloat kArcFullCircleDegrees = 359.0;
/* How often a relaunch looks for its new instance, and how long it waits. */
static const NSTimeInterval kRelaunchPollInterval = 0.25;
static const NSTimeInterval kRelaunchTimeout = 10.0;
/* SceneView (shared/scene_view.m): the frame rate it renders and calls
* `onFrame` at; a camera's default lens and clipping planes and a light's
* default intensity (SceneKit lumens); shadow softness, sampling and map
* resolution for lights that cast shadows; node transitions (how long they
* take, how far a popped node grows as it vanishes, how far a rising node
* travels and how much a pop overshoots); and the default `bob` period.
* Distances are scene units, the field of view degrees. */
static const NSInteger kSceneFramesPerSecond = 60;
static const CGFloat kSceneFieldOfView = 45.0;
static const CGFloat kSceneNearPlane = 0.1;
static const CGFloat kSceneFarPlane = 500.0;
static const CGFloat kSceneLightIntensity = 1000.0;
static const CGFloat kSceneShadowRadius = 4.0;
static const NSUInteger kSceneShadowSamples = 16;
static const CGFloat kSceneShadowMapSize = 2048.0;
static const CGFloat kSceneShadowOpacity = 0.35;
static const CGFloat kSceneShadowBias = 1.0;
static const CGFloat kSceneShadowScale = 1.0;
static const CGFloat kSceneShadowNearPlane = 1.0;
static const CGFloat kSceneShadowFarPlane = 100.0;
static const NSTimeInterval kSceneTransitionDuration = 0.3;
static const CGFloat kSceneTransitionPopScale = 1.6;
static const CGFloat kSceneTransitionRise = 1.0;
static const CGFloat kSceneTransitionOvershoot = 1.70158;
static const NSTimeInterval kSceneBobPeriod = 1.6;
/* How far a drag travels, in points, before it is a swipe and not a tap. */
static const CGFloat kSceneSwipeDistance = 24.0;
static const NSTimeInterval kScrollToAnimationDuration = 0.2;
/* Space between a paragraph's figure and the text wrapping beside it, and
* the number of lines the figure spans when the template does not say. */
static const CGFloat kParagraphFigureGap = 10.0;
static const NSInteger kParagraphFigureLines = 3;
/* How far below the baseline a link's dotted rule sits past the font's own
* underline position, so descenders do not run into the dots. */
static const CGFloat kParagraphLinkUnderlineOffset = 3.0;
/* Every value that controls visual appearance or layout has a named constant
* so that tuning across the codebase is a single-section edit. Add new constants
* here instead of embedding raw numbers in code. */
/* ----- Table / Outline cells ----- */
#define kIconBadgeCornerFraction 0.23
#define kIconBadgeSymbolScale 0.66
/* Workspace icons leave a clear margin around the squircle: 108 of 128 pixels. */
#define kAppIconArtworkFraction 0.84375
#define kTableCellImageWidth 18
#define kTableCellImageTextGap 8
#define kTableCellImageLeadingInset 0
#define kTableCellTextLeadingInset 8
#define kTableCellTextTrailingInset 8
#define kTableCellSymbolPointSize 13
#define kTableCellSecondaryFontSize 11
#define kTableSectionHeaderFontSize 11
/* Gauge thresholds above maxValue keep the capacity fill in its tint color. */
#define kGaugeNoThreshold 2
/* A disabled gauge's fill, as a fraction of its tint's opacity. */
#define kGaugeDisabledFillAlpha 0.35
#define kTableCellBadgeGap 6
/* ----- Motion ----- */
/* The system push transition of a view's contents (a tour page). */
#define kPushTransitionDuration 0.3
#define kPointerDragThreshold 3.0
#define kPointerDragIconSize 32.0
/* ----- ShaderView ----- */
/* Points one line of a notched mouse wheel scrolls a ShaderView. */
#define kShaderScrollLine 16.0
/* ----- Treemap ----- */
#define kTreemapGap 0
#define kTreemapCornerRadius 3
#define kTreemapBaseAlpha 0.55
#define kTreemapDepthFade 0.12
#define kTreemapMinAlpha 0.18
#define kTreemapDimmedAlpha 0.3
#define kDropHighlightWidth 3.0
#define kTreemapHatchSpacing 6
#define kTreemapHatchWidth 1
#define kTreemapHatchAlpha 0.22
#define kTreemapSelectionWidth 2
#define kTreemapLabelFontSize 11
#define kTreemapHeaderDetailSpacing 6
/* ----- Waveform ----- */
/* The band above the samples that holds bar numbers. */
#define kWaveformRulerHeight 18
#define kWaveformMinHeight 120
#define kWaveformVerticalInset 8
#define kWaveformLabelFontSize 10
#define kWaveformLabelInset 3
/* Beat and step lines are drawn only when this far apart; bar numbers need
* room for their digits. */
#define kWaveformMinGridSpacing 6
#define kWaveformMinBarLabelSpacing 24
#define kWaveformBarLineAlpha 0.32
#define kWaveformBeatLineAlpha 0.14
#define kWaveformStepLineAlpha 0.06
#define kWaveformSampleAlpha 0.6
#define kWaveformMinLineHeight 1
#define kWaveformSliceShadeAlpha 0.04
#define kWaveformMarkerWidth 1
#define kWaveformSelectedMarkerWidth 2
#define kWaveformHandleSize 10
#define kWaveformPlayheadWidth 2
/* Wheel zoom: the factor per point of vertical scroll (a trackpad reports
* points), and points per notch of a line-based mouse wheel. */
#define kWaveformZoomPerPoint 1.01
#define kWaveformZoomPointsPerLine 10
/* How close, in points, a press must land to grab a marker. */
#define kWaveformMarkerHitWidth 5
#define kTableCellLoadingGap 4
#define kTableCellLineSpacing 2
#define kTableCellLevelGap 8
#define kTableCellLevelStackSpacing 4
#define kTableCellLevelAccessorySide 16
#define kTableCellLevelThickness 9
#define kTableInfoButtonSide 22
#define kTableInfoButtonPointSize 15
#define kTableRowMenuOffset 2
#define kTableCellCurveInsetH 4
#define kTableCellCurveInsetV 10
#define kTableCellCurvePathWidth 100
#define kTableCellCurvePathHeight 32
#define kTableCellCurveLineWidth 1.5
#define kTableColumnMinWidth 40
#define kTableDefaultWidth 400
#define kTableDefaultHeight 200
#define kTableIntercellSpacingH 3
#define kTableIntercellSpacingV 2
#define kLayoutDebugGeometryTolerance 0.75
#define kLayoutDebugMaxTableRows 4
#define kLazyCollectionWidth 400
#define kLazyCollectionHeight 200
#define kLazyRowHeight 44
#define kLazyItemSpacing 8
#define kLazyMinimumItemWidth 1
#define kLazyStackColumns 1
#define kLazyGridColumns 2
#define kOutlineRowHeight 24
#define kOutlineIndentation 16
#define kOutlineDisclosureContentGap 8
#define kOutlineDefaultWidth 400
#define kOutlineDefaultHeight 200
/* ----- ActionButton ----- */
#define kActionBtnSymbolSize 17
#define kActionBtnSymbolSizeRow 20
#define kActionBtnTitleFontSize 13
#define kActionBtnSubtitleFontSize 11
#define kActionBtnDetailFontSize 11
#define kActionBtnTitleMaxLines 2
#define kActionBtnHeightPrimary 64
#define kActionBtnHeightPlain 58
#define kActionBtnHeightRow 52
#define kActionBtnHeightLink 40
#define kActionBtnWidth 220
#define kActionBtnIconWidth 24
#define kActionBtnIconWidthRow 28
#define kActionBtnIconGap 12
#define kActionBtnInsetPlain 12
#define kActionBtnInsetRow 14
#define kActionBtnInsetLink 20
#define kActionBtnDetailWidth 72
#define kActionBtnDetailHeight 16
#define kActionBtnDetailGap 12
#define kActionBtnTitleSubtitleGap 1
#define kActionBtnTextExtraInset 16
#define kActionBtnCornerRadius 8
#define kActionBtnHoverPrimary 0.85
#define kActionBtnHoverSecondary 0.07
#define kActionBtnSubtitleAlpha 0.75
/* ----- Spacer & Separator ----- */
#define kSpacerSize 10
#define kSeparatorSize 1
/* ----- Image ----- */
#define kDefaultImageMaxWidth 400.0
#define kImageViewerDefaultWidth 640
#define kImageViewerDefaultHeight 480
#define kImageViewerMinZoomScale 0.05
#define kImageViewerDefaultZoomScale 1.0
/* ----- System Image / SF Symbols ----- */
#define kDefaultSymbolPointSize 17
/* ----- Code Editor ----- */
#define kEditorFontSize 13
#define kEditorDefaultWidth 400
#define kEditorDefaultHeight 300
/* ----- Workspace Split Controller ----- */
#define kWorkspaceSidebarWidth 240
#define kWorkspaceSidebarMinWidth 160
#define kWorkspaceSidebarMaxWidth 420
#define kWorkspaceDetailWidth 330
#define kWorkspaceDetailMinWidth 280
#define kWorkspaceDetailMaxWidth 420
#define kWorkspaceContentDividerIndex 0
#define kWorkspaceDetailDividerIndex 1
/* ----- Symbol Toggle ----- */
#define kSymbolToggleSize 28
#define kSymbolTogglePointSize 13
/* ----- Page Control ----- */
/* A dot's click target, its symbol size and the gap between dots. */
#define kPageControlDotSize 16
#define kPageControlDotPointSize 7
#define kPageControlDotSpacing 2
/* ----- Loading Spinner ----- */
#define kLoadingSpinnerSize 32
#define kLoadingTablePadding 16
/* ----- Layout Engine ----- */
#define kLayoutDefaultWidth 400
#define kMinLeafWidth 1
#define kMinLeafHeight 22
#define kFlexEpsilon 0.5
/* ----- Preview / Render ----- */
#define kRenderDefaultWidth 400
#define kRenderDefaultHeight 300
/* ----- Misc ----- */
#define kFallbackBackingScale 2.0
#define kFSWatcherLatency 0.2
#define LUA_OBJC_HTTP_USER_AGENT \
@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " \
@"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
#define LUA_OBJC_VIEW_CLASS NSView
#define LUA_OBJC_WINDOW_CLASS NSWindow
#define LUA_OBJC_VIEW_METATABLE "nsview"
#define LUA_OBJC_WINDOW_METATABLE "nswindow"
#include "shared/lua_bridge_support.m"
#include "shared/layout_invalidation.m"
#include "shared/lua_error.m"
#include "shared/lua_async.m"
/* A Mac app has no private Documents folder; keep documents with
* App.recentStore under Application Support. */
#define LUA_OBJC_DOCUMENT_ROOT() [[NSSearchPathForDirectoriesInDomains( \
NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject \
stringByAppendingPathComponent:@"lua-objc"] stringByAppendingPathComponent:@"Documents"]
#include "shared/lua_documents.m"
#include "shared/performance_signpost.m"
#include "shared/lua_dealloc_watch.m"
/* Replaces any previously registered LuaReg at `key`. */
static void bridge_set_optional_callback(
lua_State *L, id target, const void *key, int argIdx
) {
lua_reg_store(target, key, lua_reg_opt(L, argIdx));
}
#include "appkit/bezier_path.m"
#include "appkit/level_indicator.m"
#include "appkit/table_data_source.m"
#include "appkit/outline_data_source.m"
#include "appkit/action_button.m"
#include "appkit/runtime.m"
#include "shared/view_tree.m"
#include "shared/arc_path.m"
#include "appkit/arc.m"
#include "shared/notifications.m"
#include "appkit/toolbar.m"
#include "appkit/presentation.m"
#include "appkit/text_field.m"
#include "appkit/views.m"
#include "shared/paragraph.m"
#include "appkit/paragraph.m"
#include "shared/flow_layout.m"
#include "appkit/layout.m"
#include "appkit/layout_debug.m"
#include "appkit/scroll_view.m"
#include "appkit/controls.m"
#include "appkit/outline.m"
#include "appkit/editor.m"
#include "appkit/tabview.m"
#include "appkit/navigation.m"
#include "appkit/platform.m"
#include "appkit/haptics.m"
#include "shared/webview.m"
#include "appkit/workspace.m"
#include "appkit/constructors.m"
#include "appkit/charts.m"
#include "appkit/waveform.m"
#include "shared/mesh_gradient.m"
#include "appkit/shader_view.m"
/* Imported here, after the AppKit fragments: SceneKit declares `target`
* properties that would make their `target` messages ambiguous. */
#import <SceneKit/SceneKit.h>
#import <GameController/GameController.h>
#include "shared/scene_models.m"
#include "shared/scene_view.m"
#include "appkit/reorder_container.m"
#include "shared/lazy_collection.m"
#include "shared/parity_batch.m"
#include "appkit/parity_batch.m"
#pragma mark - Module registration
static const luaL_Reg bridge_lib[] = {
{"_hapticsAvailable", bridge_haptics_available},
{"_reduceMotionEnabled", bridge_reduce_motion_enabled},
{"_hapticImpact", bridge_haptic_impact},
{"_hapticSelection", bridge_haptic_selection},
{"_hapticNotification", bridge_haptic_notification},
LUA_OBJC_WEBVIEW_FUNCTIONS
{"_testRowSwipe", bridge_test_row_swipe},
{"_parityMeasure", bridge_parity_measure},
{"_parityCapturePNG", bridge_parity_capture_png},
{"_parityWrite", bridge_parity_write},
{"_parityJSON", bridge_parity_json},
{"_parityReadJSON", bridge_parity_read_json},
{"_parityDocumentsDirectory", bridge_parity_documents},
{"Size", bridge_NSSize},
{"Point", bridge_NSPoint},
{"Rect", bridge_NSRect},
{"_vstack", bridge_AppKitControls_vstack},
{"_hstack", bridge_AppKitControls_hstack},
{"_flowStack", bridge_AppKitControls_flowStack},
{"_zstack", bridge_AppKitControls_zstack},
{"_scrollView", bridge_AppKitControls_scrollView},
{"_testScrollWheel", bridge_test_scroll_wheel},
{"_hsplit", bridge_AppKitControls_hsplit},
{"_vsplit", bridge_AppKitControls_vsplit},
{"_separator", bridge_AppKitControls_separator},
{"_spacer", bridge_AppKitControls_spacer},
{"_linearGradient", bridge_AppKitControls_linearGradient},
{"_linearGradientColors", bridge_AppKitControls_linearGradientColors},
LUA_OBJC_MESH_GRADIENT_FUNCTIONS
LUA_OBJC_SHADER_VIEW_FUNCTIONS
{"_hitTestTarget", bridge_hit_test_target},
{"_hostingController", bridge_hosting_controller},
{"_navigationStack", bridge_navigation_stack},
{"_navigationOnBack", bridge_navigation_on_back},
{"_label", bridge_AppKitControls_label},
{"_paragraph", bridge_AppKitControls_paragraph},
{"_paragraphSetLinks", bridge_paragraph_set_links},
{"_paragraphLinks", bridge_paragraph_links},
{"_paragraphPerformLink", bridge_paragraph_perform_link},
{"_hasLayoutAxis", bridge_has_layout_axis},
{"_textField", bridge_AppKitControls_textField},
{"_secureTextField", bridge_AppKitControls_secureTextField},
{"_searchField", bridge_AppKitControls_searchField},
{"_box", bridge_AppKitControls_box},
{"_progressIndicator", bridge_AppKitControls_progressIndicator},
{"_levelIndicator", bridge_AppKitControls_levelIndicator},
{"_tableCellView", bridge_AppKitControls_tableCellView},
{"_popUpButton", bridge_AppKitControls_popUpButton},
{"_menu", bridge_AppKitControls_menu},
{"_slider", bridge_AppKitControls_slider},
{"_stepper", bridge_AppKitControls_stepper},
{"_picker", bridge_AppKitControls_picker},
{"_segmentedPicker", bridge_AppKitControls_segmentedPicker},
LUA_OBJC_VIEW_TREE_FUNCTIONS
LUA_OBJC_NOTIFICATION_FUNCTIONS
{"_pointerView", bridge_pointer_view},
{"_pointerSend", bridge_pointer_send},
{"_treemap", bridge_treemap},
{"_treemapRefresh", bridge_treemap_refresh},
{"_waveform", bridge_waveform},
{"_waveformMarkers", bridge_waveform_markers},
{"_waveformSend", bridge_waveform_send},
{"_tableDragPath", bridge_table_drag_path},
{"_setDropHandler", bridge_set_drop_handler},
{"_dropFiles", bridge_drop_files},
{"_volumeCapacity", bridge_volume_capacity},
{"_datePicker", bridge_AppKitControls_datePicker},
{"_colorPicker", bridge_AppKitControls_colorPicker},
{"_button", bridge_AppKitControls_button},
{"_link", bridge_AppKitControls_link},
{"_toggle", bridge_AppKitControls_toggle},
{"_tableColumnWidths", bridge_table_column_widths},
{"_tableRowMenu", bridge_table_row_menu},
{"_tableCell", bridge_table_cell},
{"_pressColumnButton", bridge_press_column_button},
{"_viewMidlineFill", bridge_view_midline_fill},
{"_arcInkBounds", bridge_arc_ink_bounds},
{"_tableCellFrames", bridge_table_cell_frames},
{"_tableSeparatorRows", bridge_table_separator_rows},
{"_tableSpinnerFrame", bridge_table_spinner_frame},
{"_toolbar_item", bridge_toolbar_item},
{"_validateToolbar", bridge_validate_toolbar},
{"_window", bridge_window},
{"_setWindowWorkspace", bridge_set_window_workspace},
{"_image", bridge_image},
{"_systemImage", bridge_system_image},
{"_systemColor", bridge_system_color},
{"_textAlignment", bridge_text_alignment},
{"_addDoubleClick", bridge_add_double_click},
{"_addDrag", bridge_add_drag},
{"_addHoverTooltip", bridge_add_hover_tooltip},
{"_tableview", bridge_tableview},
{"_attachReorder", bridge_AppKitReorder_attach},
{"_testReorderMove", bridge_AppKitReorder_testMove},
LUA_OBJC_LAZY_COLLECTION_FUNCTIONS
{"_actionButton", bridge_action_button},
{"_glassEffect", bridge_glass_effect},
{"_glassEffectContainer", bridge_glass_effect_container},
{"_panel", bridge_panel},
{"_sheet", bridge_sheet},
{"_setMainMenu", bridge_set_main_menu},
{"_mainMenuSnapshot", bridge_main_menu_snapshot},
{"_performMainMenuItem", bridge_perform_main_menu_item},
{"_searchHelp", bridge_search_help},
{"_textFieldCallbacks", bridge_text_field_callbacks},
{"_textFieldTestInput", bridge_text_field_test_input},
{"_textFieldTestCommand", bridge_text_field_test_command},
{"_textFieldTestFocus", bridge_text_field_test_focus},
{"_textView", bridge_text_view},
{"_textEditorTestInput", bridge_text_editor_test_input},
{"_tabview", bridge_tabview},
{"_segmentedControl", bridge_segmented_control},
{"_watch", bridge_watch},
{"_bookmark", bridge_bookmark},
{"_onNavigationGesture", bridge_on_navigation_gesture},
{"_navigationGesture", bridge_navigation_gesture},
{"_resolveBookmark", bridge_resolve_bookmark},
{"_applicationSupportDirectory", bridge_application_support_directory},
{"_homeDirectory", bridge_home_directory},
{"_pageControl", bridge_page_control},
{"_unwatch", bridge_unwatch},
{"_latestEventId", bridge_latest_event_id},
{"_pickFolder", bridge_pick_folder},
{"_pickFile", bridge_pick_file},
{"_saveFile", bridge_save_file},
{"_outlineview", bridge_outlineview},
{"_listDirectory", bridge_list_directory},
{"_readPropertyList", bridge_read_property_list},
{"_parsePropertyList", bridge_parse_property_list},
{"_timerAfter", bridge_timer_after},
{"_uptime", bridge_uptime},
{"_httpGet", bridge_http_get},
{"_jsonParse", bridge_json_parse},
{"_font", bridge_font},
{"_pathView", bridge_pathView},
{"_arc", bridge_arc},
{"_sceneView", bridge_scene_view},
{"_sceneGraph", bridge_scene_graph},
{"_sceneBackground", bridge_scene_background},
{"_sceneNodes", bridge_scene_nodes},
{"_sceneSend", bridge_scene_send},
{"_setCurrentScope", bridge_set_current_scope},
{"_getCurrentScope", bridge_get_current_scope},
{"_invokeAction", bridge_invoke_action},
{"_onWindowClose", bridge_on_window_close},
{"_invalidateHandle", bridge_invalidate_handle},
{"_watchDealloc", bridge_dealloc_watch},
{"_deallocCount", bridge_dealloc_count},
{"_deallocReset", bridge_dealloc_reset},
{"_runLoopTick", bridge_runloop_tick},
{"_flushLayout", bridge_flush_layout},
{"_pendingLayoutCount", bridge_pending_layout_count},
{"_appkitLayout", bridge_appkit_layout},
{"_addContextMenu", bridge_add_context_menu},
{"_addClick", bridge_add_click},
{"_revealInFinder", bridge_reveal_in_finder},
{"_documentPath", bridge_document_path},
{"_documentRead", bridge_document_read},
{"_documentWrite", bridge_document_write},
{"_documentWriteData", bridge_document_write_data},
{"_documentExists", bridge_document_exists},
{"_jsonEncode", bridge_json_encode},
{"_openPath", bridge_open_path},
{"_moveToTrash", bridge_move_to_trash},
{"_moveItem", bridge_move_item},
{"_quickLook", bridge_quick_look},
{"_quickLookItems", bridge_quick_look_items},
{"_onOpenFiles", bridge_on_open_files},
{"_openFiles", bridge_open_files},
{"_runningApplications", bridge_running_applications},
{"_applicationPath", bridge_application_path},
{"_codeSignatures", bridge_code_signatures},
{"_fileIdentity", bridge_file_identity},
{"_relaunch", bridge_relaunch},
{"_clipboardCopy", bridge_clipboard_copy},
{"_alert", bridge_alert},
{"_diskSpace", bridge_disk_space},
{NULL, NULL},
};
static void register_metatable(lua_State *L, const char *name) {
luaL_newmetatable(L, name);
lua_pushcfunction(L, gc_objc);
lua_setfield(L, -2, "__gc");
lua_pushcfunction(L, nsview_index);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, nsview_newindex);
lua_setfield(L, -2, "__newindex");
lua_pop(L, 1);
}
int luaopen_bridge(lua_State *L) {
lua_objc_init_handles(L);
register_luareg_metatable(L);
register_metatable(L, "nsview");
register_metatable(L, "nswindow");
register_metatable(L, "nsobject");
#define GEN_STRUCT_REGISTER
#include "appkit/structs.m"
#undef GEN_STRUCT_REGISTER
luaL_newlib(L, bridge_lib);
return 1;
}
#pragma mark - Main
/*
* The executable is intentionally a tiny loader. AppKit.dylib owns the host
* runtime as well as luaopen_AppKit, so the same image that Lua requires also
* owns every AppKit control, layout key, callback target, and canvas service.
*/
int lua_objc_main(int argc, char *argv[]) {
[NSApplication sharedApplication];
const char *appearance = NULL;
const char *script = NULL;
int preview_mode = 0;
CGFloat preview_width = kRenderDefaultWidth;
CGFloat preview_height = kRenderDefaultHeight;
BOOL layout_width_set = NO;
BOOL layout_height_set = NO;
const char *preview_out = NULL;
const char *layout_out = NULL;
const char *screenshot_out = NULL;
const char *capture_out = NULL;
const char *capture_plan = NULL;
int app_ref = LUA_NOREF;
const char *internal_screenshot_out = NULL;
const char *script_args[256];
int script_arg_count = 0;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--preview") == 0) {
preview_mode = 1;
} else if (strncmp(argv[i], "--width=", 8) == 0) {
preview_width = atof(argv[i] + 8);
layout_width_set = YES;
} else if (strncmp(argv[i], "--height=", 9) == 0) {
preview_height = atof(argv[i] + 9);
layout_height_set = YES;
} else if (strncmp(argv[i], "--out=", 6) == 0) {
preview_out = argv[i] + 6;
} else if (strncmp(argv[i], "--dump-layout=", 14) == 0) {
layout_out = argv[i] + 14;
} else if (strncmp(argv[i], "--screenshot=", 13) == 0) {
screenshot_out = argv[i] + 13;
} else if (strncmp(argv[i], "--capture=", 10) == 0) {
capture_out = argv[i] + 10;
} else if (strncmp(argv[i], "--capture-plan=", 15) == 0) {
capture_plan = argv[i] + 15;
} else if (strncmp(argv[i], "--internal-screenshot=", 22) == 0) {
internal_screenshot_out = argv[i] + 22;
} else if (strncmp(argv[i], "--appearance=", 13) == 0) {
appearance = argv[i] + 13;
} else if (strcmp(argv[i], "--appearance") == 0 && i + 1 < argc) {
appearance = argv[++i];
} else if (script && script_arg_count < 256) {
script_args[script_arg_count++] = argv[i];
} else if (argv[i][0] != '-') {
if (!script) {
script = argv[i];
} else if (script_arg_count < (int)(sizeof(script_args) / sizeof(script_args[0]))) {
script_args[script_arg_count++] = argv[i];
}
} else if (script_arg_count < (int)(sizeof(script_args) / sizeof(script_args[0]))) {
/* Preserve app-level switches supplied before the entry point. */
script_args[script_arg_count++] = argv[i];
}
}
if (!script) script = "demo/hello";
// If script path is a directory, look for init.lua inside it.
{
static char resolvedPath[PATH_MAX];
BOOL isDir = NO;
if ([[NSFileManager defaultManager]
fileExistsAtPath:[NSString stringWithUTF8String:script]
isDirectory:&isDir] && isDir) {
NSString *initPath = [[NSString stringWithUTF8String:script]
stringByAppendingPathComponent:@"init.lua"];
snprintf(resolvedPath, sizeof(resolvedPath), "%s",
[initPath UTF8String]);
script = resolvedPath;
}
}
lua_State *L = luaL_newstate();
luaL_openlibs(L);
LuaStateOwner *mainOwner = [[LuaStateOwner alloc] initWithState:L];
(void)mainOwner; /* released by ARC at return → -dealloc → lua_close */
luaL_requiref(L, "AppKitNative", luaopen_bridge, 1);
lua_pop(L, 1);
if (appearance && strcmp(appearance, "system") != 0) {
lua_pushstring(L, appearance);
lua_setglobal(L, "_LAUNCH_APPEARANCE");
}
lua_newtable(L);
if (script) {
lua_pushinteger(L, 0);
lua_pushstring(L, script);
lua_settable(L, -3);
}
for (int i = 0; i < script_arg_count; i++) {
lua_pushinteger(L, i + 1);
lua_pushstring(L, script_args[i]);
lua_settable(L, -3);
}
lua_setglobal(L, "arg");
char cwd[4096];
if (getcwd(cwd, sizeof(cwd))) {
char frameworkDirectory[PATH_MAX] = "";
Dl_info imageInfo;
if (dladdr((const void *)&lua_objc_main, &imageInfo)
&& imageInfo.dli_fname) {
char imagePath[PATH_MAX];
snprintf(imagePath, sizeof(imagePath), "%s", imageInfo.dli_fname);
snprintf(frameworkDirectory, sizeof(frameworkDirectory), "%s",
dirname(imagePath));
}
lua_getglobal(L, "package");
lua_getfield(L, -1, "path");
const char *defpath = lua_tostring(L, -1);
char newpath[8192];
snprintf(newpath, sizeof(newpath), "%s;%s/?.lua;%s/lua/?.lua", defpath, cwd, cwd);
lua_pushstring(L, newpath);
lua_setfield(L, -3, "path");
lua_pop(L, 1);
lua_getfield(L, -1, "cpath");
const char *defcpath = lua_tostring(L, -1);
char newcpath[8192];
snprintf(newcpath, sizeof(newcpath), "%s;%s/build/?.dylib;%s/?.dylib",
defcpath, cwd, frameworkDirectory);
lua_pushstring(L, newcpath);
lua_setfield(L, -3, "cpath");
lua_pop(L, 2);
}
{
extern int luaopen_AppKit(lua_State *L);
luaL_requiref(L, "AppKit", luaopen_AppKit, 1);
lua_getglobal(L, "package");
lua_getfield(L, -1, "loaded");
lua_pushvalue(L, -3);
lua_setfield(L, -2, "ns");
lua_pop(L, 3);
}
if (preview_mode) {
/* --preview: eval the script in the main state, render to PNG. */
FILE *fp = fopen(script, "r");
if (!fp) {
fprintf(stderr, "preview: cannot open %s\n", script);
return 1;
}
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
rewind(fp);
char *code = malloc((size_t)fsize + 1);
fread(code, 1, (size_t)fsize, fp);
code[fsize] = '\0';
fclose(fp);
char *wrapped = malloc((size_t)fsize + 256);
snprintf(wrapped, (size_t)fsize + 256,
"local ns=require('AppKit');"
"local __rr;"
"ns.Window=function(p) __rr=ns.VStack(p) return __rr end;"
"ns.Preview=function(p) __rr=ns.VStack(p) return __rr end;"
"local __rok,__ret=pcall(function()\n%s\nend);"
"if not __rok then error(__ret) end;"
"return __ret or __rr",
code);
free(code);
NSString *previewSource = [NSString stringWithFormat:@"@%s", script];
if (luaL_loadbufferx(L, wrapped, strlen(wrapped),
previewSource.UTF8String, "t") != LUA_OK ||
lua_pcall(L, 0, 1, 0) != LUA_OK) {
report_lua_error(L, "preview");
free(wrapped);
return 1;
}
free(wrapped);
id resultObj = nil;
ObjCRef *ref = luaL_testudata(L, -1, "nsview");
if (!ref) ref = luaL_testudata(L, -1, "nswindow");
if (ref) resultObj = (__bridge id)ref->ptr;
if (!resultObj || ![resultObj isKindOfClass:[NSView class]]) {
fprintf(stderr, "preview: script did not return a view\n");
return 1;
}
NSView *view = (NSView *)resultObj;
view.frame = NSMakeRect(0, 0, preview_width, preview_height);
layout_recursive(view, preview_width);
NSData *png = offscreen_render(view, preview_width, preview_height);
lua_settop(L, 0);
if (!png) {
fprintf(stderr, "preview: render failed\n");
return 1;
}
int write_ok = 0;
if (!preview_out || strcmp(preview_out, "-") == 0) {
write_ok = fwrite(png.bytes, 1, png.length, stdout) == (size_t)png.length;
} else {
FILE *out = fopen(preview_out, "wb");
if (out) {
write_ok = fwrite(png.bytes, 1, png.length, out) == (size_t)png.length;
fclose(out);
}
}
return write_ok ? 0 : 1;
}
BOOL testMode = NO;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--test") == 0) testMode = YES;
}
if (layout_out || testMode) {
lua_pushboolean(L, 1);
lua_setglobal(L, "__headless");
}
if (luaL_dofile(L, script) != LUA_OK) {
report_lua_error(L, "script");
return 1;
}
if (testMode) return 0;
/*
* A script that declared itself headless has no window to serve. Without
* this, a test or scratch script launched without --test would idle in the
* run loop forever, holding everything it built.
*/
if (!layout_out) {
lua_getglobal(L, "__headless");
BOOL headless = lua_toboolean(L, -1);
lua_pop(L, 1);
if (headless) return 0;
}
/*
* If the script returned a table with a `new` method, treat it as an
* app class: call class.new() with no arguments, then
* instance:createWindow(). Constructors take optional dependency tables
* for tests, so the class itself must never arrive as the first argument.
*/
/*
* require() pushes two values: the module and the filename it was loaded
* from. Pop any trailing non-table values so the class table is on top.
*/
while (lua_gettop(L) > 0 && !lua_istable(L, -1))
lua_pop(L, 1);
if (lua_istable(L, -1)) {
lua_getfield(L, -1, "new");
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 1, 0) != LUA_OK) {
report_lua_error(L, "new");
} else if (lua_istable(L, -1)) {
lua_getfield(L, -1, "createWindow");
if (lua_isfunction(L, -1)) {
lua_pushvalue(L, -2); /* instance as self */
if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
report_lua_error(L, "createWindow");
} else {
/*
* Keep the launch controller and its window alive for the
* lifetime of the run loop. Many examples store their
* NSWindow and callback closures on the instance, so
* dropping the last Lua root here can deallocate the
* whole window tree before AppKit has a chance to display it.
*/
lua_pushvalue(L, -2);
app_ref = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushvalue(L, -1);
luaL_ref(L, LUA_REGISTRYINDEX);
}
}
}
}
}
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp finishLaunching];
if (layout_out) {
NSWindow *window = lua_objc_app_window();
if (window && (layout_width_set || layout_height_set)) {
NSSize size = window.contentView.bounds.size;
if (layout_width_set) size.width = preview_width;
if (layout_height_set) size.height = preview_height;
window.size = size;
}
if (!window || !write_layout_debug_dump(window, layout_out)) {
fprintf(stderr, "layout dump: cannot write %s\n", layout_out);
return 1;
}
return 0;
}
[NSApp unhide:nil];
[NSApp activate];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[NSApp unhide:nil];
[NSApp activate];
for (NSWindow *window in NSApp.windows) {
if (window.isVisible) {
// Panels and sheets cannot become main; an attached sheet owns key focus.
if (window.canBecomeKeyWindow && !window.attachedSheet) [window makeKeyAndOrderFront:nil];
if (window.canBecomeMainWindow) [window makeMainWindow];
[window orderFrontRegardless];
}
}
});
lua_settop(L, 0);
/* Resize before the settling interval, so WindowServer and native container
* layout commit the requested geometry before either capture path runs. */
if ((screenshot_out || internal_screenshot_out || capture_out || capture_plan)
&& (layout_width_set || layout_height_set)) {
NSWindow *window = lua_objc_app_window();
NSSize size = window.contentView.bounds.size;
if (layout_width_set) size.width = preview_width;
if (layout_height_set) size.height = preview_height;
window.size = size;
}
if (capture_plan) {
/* One launch, many captures: ui/capture.lua runs the plan against the
* app instance and its window once the launch has settled, and exits
* when the plan finishes. */
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
lua_getglobal(L, "require");
lua_pushstring(L, "ui.capture");
if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
report_lua_error(L, "capture plan");
exit(EXIT_FAILURE);
}
lua_getfield(L, -1, "run");
lua_pushstring(L, capture_plan);
lua_rawgeti(L, LUA_REGISTRYINDEX, app_ref);
push_objc(L, lua_objc_app_window(), "nsobject");
if (lua_pcall(L, 3, 0, 0) != LUA_OK) {
report_lua_error(L, "capture plan");
exit(EXIT_FAILURE);
}
lua_settop(L, 0);
});
} else if (capture_out) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
BOOL captured = write_window_capture(lua_objc_app_window(), capture_out);
if (!captured) fprintf(stderr, "capture: cannot write %s\n", capture_out);
exit(captured ? EXIT_SUCCESS : EXIT_FAILURE);
});
} else if (internal_screenshot_out) {
NSString *screenshotPath = [NSString stringWithUTF8String:internal_screenshot_out];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
NSWindow *window = lua_objc_app_window();
NSData *png = nil;
if (window && window.contentView) {
[window.contentView layoutSubtreeIfNeeded];
// The window was resized to the requested size, clamped to
// its minimum; render what it actually is.
NSSize size = window.contentView.bounds.size;
png = offscreen_render(window.contentView, size.width, size.height);
}
BOOL captured = png && [png writeToFile:screenshotPath atomically:YES];
if (captured) {
fprintf(stderr, "internal screenshot: wrote %s (%lu bytes)\n",
internal_screenshot_out, (unsigned long)png.length);
} else {
fprintf(stderr, "internal screenshot: failed to write %s\n",
internal_screenshot_out);
}
exit(captured ? EXIT_SUCCESS : EXIT_FAILURE);
});
} else if (screenshot_out) {
NSString *screenshotPath = [NSString stringWithUTF8String:screenshot_out];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
NSWindow *window = lua_objc_app_window();
NSData *png = nil;
[[NSFileManager defaultManager] removeItemAtPath:screenshotPath error:nil];
if (window) {
[window display];
NSTask *capture = [[NSTask alloc] init];