forked from ghostty-org/ghostty
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathembedded.zig
More file actions
2376 lines (2057 loc) 路 77.5 KB
/
Copy pathembedded.zig
File metadata and controls
2376 lines (2057 loc) 路 77.5 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
//! Application runtime for the embedded version of Ghostty. The embedded
//! version is when Ghostty is embedded within a parent host application,
//! rather than owning the application lifecycle itself. This is used for
//! example for the macOS build of Ghostty so that we can use a native
//! Swift+XCode-based application.
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const objc = @import("objc");
const apprt = @import("../apprt.zig");
const font = @import("../font/main.zig");
const input = @import("../input.zig");
const internal_os = @import("../os/main.zig");
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");
const CoreApp = @import("../App.zig");
const CoreInspector = @import("../inspector/main.zig").Inspector;
const CoreSurface = @import("../Surface.zig");
const configpkg = @import("../config.zig");
const Config = configpkg.Config;
const String = @import("../main_c.zig").String;
const log = std.log.scoped(.embedded_window);
pub const resourcesDir = internal_os.resourcesDir;
pub const App = struct {
/// Because we only expect the embedding API to be used in embedded
/// environments, the options are extern so that we can expose it
/// directly to a C callconv and not pay for any translation costs.
///
/// C type: ghostty_runtime_config_s
pub const Options = extern struct {
/// These are just aliases to make the function signatures below
/// more obvious what values will be sent.
const AppUD = ?*anyopaque;
const SurfaceUD = ?*anyopaque;
/// Userdata that is passed to all the callbacks.
userdata: AppUD = null,
/// True if the selection clipboard is supported.
supports_selection_clipboard: bool = false,
/// Callback called to wakeup the event loop. This should trigger
/// a full tick of the app loop.
wakeup: *const fn (AppUD) callconv(.c) void,
/// Callback called to handle an action.
action: *const fn (*App, apprt.Target.C, apprt.Action.C) callconv(.c) bool,
/// Read the clipboard value. Returns true if the clipboard request
/// was started and complete_clipboard_request may be called with the
/// given state pointer. Returns false if the clipboard request couldn't
/// be started (such as when no text is available for a paste request).
read_clipboard: *const fn (SurfaceUD, c_int, *apprt.ClipboardRequest) callconv(.c) bool,
/// This may be called after a read clipboard call to request
/// confirmation that the clipboard value is safe to read. The embedder
/// must call complete_clipboard_request with the given request.
confirm_read_clipboard: *const fn (
SurfaceUD,
[*:0]const u8,
*apprt.ClipboardRequest,
apprt.ClipboardRequestType,
) callconv(.c) void,
/// Write the clipboard value.
write_clipboard: *const fn (
SurfaceUD,
c_int,
[*]const CAPI.ClipboardContent,
usize,
bool,
) callconv(.c) void,
/// Close the current surface given by this function.
close_surface: ?*const fn (SurfaceUD, bool) callconv(.c) void = null,
};
/// This is the key event sent for ghostty_surface_key and
/// ghostty_app_key.
pub const KeyEvent = struct {
action: input.Action,
mods: input.Mods,
consumed_mods: input.Mods,
keycode: u32,
text: ?[:0]const u8,
unshifted_codepoint: u32,
composing: bool,
/// Convert a libghostty key event into a core key event.
fn core(self: KeyEvent) ?input.KeyEvent {
const text: []const u8 = if (self.text) |v| v else "";
const unshifted_codepoint: u21 = std.math.cast(
u21,
self.unshifted_codepoint,
) orelse 0;
// We want to get the physical unmapped key to process keybinds.
const physical_key = keycode: for (input.keycodes.entries) |entry| {
if (entry.native == self.keycode) break :keycode entry.key;
} else .unidentified;
// Build our final key event
return .{
.action = self.action,
.key = physical_key,
.mods = self.mods,
.consumed_mods = self.consumed_mods,
.composing = self.composing,
.utf8 = text,
.unshifted_codepoint = unshifted_codepoint,
};
}
};
core_app: *CoreApp,
opts: Options,
keymap: input.Keymap,
/// The configuration for the app. This is owned by this structure.
config: Config,
pub fn init(
self: *App,
core_app: *CoreApp,
config: *const Config,
opts: Options,
) !void {
// We have to clone the config.
const alloc = core_app.alloc;
var config_clone = try config.clone(alloc);
errdefer config_clone.deinit();
var keymap = try input.Keymap.init();
errdefer keymap.deinit();
self.* = .{
.core_app = core_app,
.config = config_clone,
.opts = opts,
.keymap = keymap,
};
}
pub fn terminate(self: *App) void {
self.keymap.deinit();
self.config.deinit();
}
/// Returns true if there are any global keybinds in the configuration.
pub fn hasGlobalKeybinds(self: *const App) bool {
var it = self.config.keybind.set.bindings.iterator();
while (it.next()) |entry| {
switch (entry.value_ptr.*) {
.leader => {},
inline .leaf, .leaf_chained => |leaf| if (leaf.flags.global) return true,
}
}
return false;
}
/// The target of a key event. This is used to determine some subtly
/// different behavior between app and surface key events.
pub const KeyTarget = union(enum) {
app,
surface: *Surface,
};
/// See CoreApp.focusEvent
pub fn focusEvent(self: *App, focused: bool) void {
self.core_app.focusEvent(focused);
}
/// See CoreApp.keyEvent.
pub fn keyEvent(
self: *App,
target: KeyTarget,
event: KeyEvent,
) !bool {
// Convert our C key event into a Zig one.
const input_event: input.KeyEvent = event.core() orelse
return false;
// Invoke the core Ghostty logic to handle this input.
const effect: CoreSurface.InputEffect = switch (target) {
.app => if (self.core_app.keyEvent(
self,
input_event,
)) .consumed else .ignored,
.surface => |surface| try surface.core_surface.keyCallback(
input_event,
),
};
return switch (effect) {
.closed => true,
.ignored => false,
.consumed => true,
};
}
/// This should be called whenever the keyboard layout was changed.
pub fn reloadKeymap(self: *App) !void {
// Reload the keymap
try self.keymap.reload();
}
/// Loads the keyboard layout.
///
/// Kind of expensive so this should be avoided if possible. When I say
/// "kind of expensive" I mean that its not something you probably want
/// to run on every keypress.
pub fn keyboardLayout(self: *const App) input.KeyboardLayout {
// We only support keyboard layout detection on macOS.
if (comptime builtin.os.tag != .macos) return .unknown;
// Any layout larger than this is not something we can handle.
var buf: [256]u8 = undefined;
const id = self.keymap.sourceId(&buf) catch |err| {
comptime assert(@TypeOf(err) == error{OutOfMemory});
return .unknown;
};
return input.KeyboardLayout.mapAppleId(id) orelse .unknown;
}
pub fn wakeup(self: *const App) void {
self.opts.wakeup(self.opts.userdata);
}
pub fn wait(self: *const App) !void {
_ = self;
}
/// Create a new surface for the app.
fn newSurface(self: *App, opts: Surface.Options) !*Surface {
// Grab a surface allocation because we're going to need it.
var surface = try self.core_app.alloc.create(Surface);
errdefer self.core_app.alloc.destroy(surface);
// Create the surface
try surface.init(self, opts);
errdefer surface.deinit();
return surface;
}
/// Close the given surface.
pub fn closeSurface(self: *App, surface: *Surface) void {
surface.deinit();
self.core_app.alloc.destroy(surface);
}
pub fn redrawInspector(self: *App, surface: *Surface) void {
_ = self;
surface.queueInspectorRender();
}
/// Perform a given action. Returns `true` if the action was able to be
/// performed, `false` otherwise.
pub fn performAction(
self: *App,
target: apprt.Target,
comptime action: apprt.Action.Key,
value: apprt.Action.Value(action),
) !bool {
// Special case certain actions before they are sent to the
// embedded apprt.
self.performPreAction(target, action, value);
log.debug("dispatching action target={t} action={} value={any}", .{
target,
action,
value,
});
return self.opts.action(
self,
target.cval(),
@unionInit(apprt.Action, @tagName(action), value).cval(),
);
}
fn performPreAction(
self: *App,
target: apprt.Target,
comptime action: apprt.Action.Key,
value: apprt.Action.Value(action),
) void {
// Special case certain actions before they are sent to the embedder
switch (action) {
.set_title => switch (target) {
.app => {},
.surface => |surface| {
// Dupe the title so that we can store it. If we get an allocation
// error we just ignore it, since this only breaks a few minor things.
const alloc = self.core_app.alloc;
if (surface.rt_surface.title) |v| alloc.free(v);
surface.rt_surface.title = alloc.dupeZ(u8, value.title) catch null;
},
},
.config_change => switch (target) {
.surface => {},
// For app updates, we update our core config. We need to
// clone it because the caller owns the param.
.app => if (value.config.clone(self.core_app.alloc)) |config| {
self.config.deinit();
self.config = config;
} else |err| {
log.err("error updating app config err={}", .{err});
},
},
else => {},
}
}
/// Send the given IPC to a running Ghostty. Returns `true` if the action was
/// able to be performed, `false` otherwise.
///
/// Note that this is a static function. Since this is called from a CLI app (or
/// some other process that is not Ghostty) there is no full-featured apprt App
/// to use.
pub fn performIpc(
_: Allocator,
_: apprt.ipc.Target,
comptime action: apprt.ipc.Action.Key,
_: apprt.ipc.Action.Value(action),
) (Allocator.Error || std.posix.WriteError || apprt.ipc.Errors)!bool {
switch (action) {
.new_window => return false,
.toggle_quick_terminal => return false,
}
}
};
/// Platform-specific configuration for libghostty.
pub const Platform = union(PlatformTag) {
macos: MacOS,
ios: IOS,
// If our build target for libghostty is not darwin then we do
// not include macos support at all.
pub const MacOS = if (builtin.target.os.tag.isDarwin()) struct {
/// The view to render the surface on.
nsview: objc.Object,
} else void;
pub const IOS = if (builtin.target.os.tag.isDarwin()) struct {
/// The view to render the surface on.
uiview: objc.Object,
} else void;
// The C ABI compatible version of this union. The tag is expected
// to be stored elsewhere.
pub const C = extern union {
macos: extern struct {
nsview: ?*anyopaque,
},
ios: extern struct {
uiview: ?*anyopaque,
},
};
/// Initialize a Platform a tag and configuration from the C ABI.
pub fn init(tag_int: c_int, c_platform: C) !Platform {
const tag = try std.meta.intToEnum(PlatformTag, tag_int);
return switch (tag) {
.macos => if (MacOS != void) macos: {
const config = c_platform.macos;
const nsview = objc.Object.fromId(config.nsview orelse
break :macos error.NSViewMustBeSet);
break :macos .{ .macos = .{ .nsview = nsview } };
} else error.UnsupportedPlatform,
.ios => if (IOS != void) ios: {
const config = c_platform.ios;
const uiview = objc.Object.fromId(config.uiview orelse
break :ios error.UIViewMustBeSet);
break :ios .{ .ios = .{ .uiview = uiview } };
} else error.UnsupportedPlatform,
};
}
};
pub const PlatformTag = enum(c_int) {
// "0" is reserved for invalid so we can detect unset values
// from the C API.
macos = 1,
ios = 2,
};
pub const EnvVar = extern struct {
/// The name of the environment variable.
key: [*:0]const u8,
/// The value of the environment variable.
value: [*:0]const u8,
};
// cmux fork: delete when upstream libghostty exposes equivalent surface IO
// ownership. iOS uses this so Rust owns the session while Ghostty renders it.
pub const IoMode = enum(c_int) {
exec = 0,
manual = 1,
};
pub const IoWriteCallback = *const fn (?*anyopaque, [*]const u8, usize) callconv(.c) void;
pub const Surface = struct {
app: *App,
platform: Platform,
userdata: ?*anyopaque = null,
core_surface: CoreSurface,
content_scale: apprt.ContentScale,
size: apprt.SurfaceSize,
cursor_pos: apprt.CursorPos,
cursor_pos_mods: input.Mods,
inspector: ?*Inspector = null,
io_mode: IoMode = .exec,
io_write_cb: ?IoWriteCallback = null,
io_write_userdata: ?*anyopaque = null,
/// The current title of the surface. The embedded apprt saves this so
/// that getTitle works without the implementer needing to save it.
title: ?[:0]const u8 = null,
/// Surface initialization options.
pub const Options = extern struct {
/// The platform that this surface is being initialized for and
/// the associated platform-specific configuration.
platform_tag: c_int = 0,
platform: Platform.C = undefined,
/// Userdata passed to some of the callbacks.
userdata: ?*anyopaque = null,
/// The scale factor of the screen.
scale_factor: f64 = 1,
/// The font size to inherit. If 0, default font size will be used.
font_size: f32 = 0,
/// The working directory to load into.
working_directory: ?[*:0]const u8 = null,
/// The command to run in the new surface. If this is set then
/// the "wait-after-command" option is also automatically set to true,
/// since this is used for scripting.
///
/// This command always run in a shell (e.g. via `/bin/sh -c`),
/// despite Ghostty allowing directly executed commands via config.
/// This is a legacy thing and we should probably change it in the
/// future once we have a concrete use case.
command: ?[*:0]const u8 = null,
/// Extra environment variables to set for the surface.
env_vars: ?[*]EnvVar = null,
env_var_count: usize = 0,
/// Input to send to the command after it is started.
initial_input: ?[*:0]const u8 = null,
/// Wait after the command exits
wait_after_command: bool = false,
/// Context for the new surface
context: apprt.surface.NewSurfaceContext = .window,
/// IO mode for the surface.
io_mode: IoMode = .exec,
/// Callback invoked when Ghostty wants to write to the backend.
io_write_cb: ?IoWriteCallback = null,
/// Userdata passed to io_write_cb.
io_write_userdata: ?*anyopaque = null,
};
pub fn init(self: *Surface, app: *App, opts: Options) !void {
self.* = .{
.app = app,
.platform = try .init(opts.platform_tag, opts.platform),
.userdata = opts.userdata,
.core_surface = undefined,
.content_scale = .{
.x = @floatCast(opts.scale_factor),
.y = @floatCast(opts.scale_factor),
},
.size = .{ .width = 800, .height = 600 },
.cursor_pos = .{ .x = -1, .y = -1 },
.cursor_pos_mods = .{},
.io_mode = opts.io_mode,
.io_write_cb = opts.io_write_cb,
.io_write_userdata = opts.io_write_userdata,
};
// Add ourselves to the list of surfaces on the app.
try app.core_app.addSurface(self);
errdefer app.core_app.deleteSurface(self);
// Shallow copy the config so that we can modify it.
var config = try apprt.surface.newConfig(app.core_app, &app.config, opts.context);
defer config.deinit();
// If we have a working directory from the options then we set it.
if (opts.working_directory) |c_wd| {
const wd = std.mem.sliceTo(c_wd, 0);
if (wd.len > 0) wd: {
var dir = std.fs.openDirAbsolute(wd, .{}) catch |err| {
log.warn(
"error opening requested working directory dir={s} err={}",
.{ wd, err },
);
break :wd;
};
defer dir.close();
const stat = dir.stat() catch |err| {
log.warn(
"failed to stat requested working directory dir={s} err={}",
.{ wd, err },
);
break :wd;
};
if (stat.kind != .directory) {
log.warn(
"requested working directory is not a directory dir={s}",
.{wd},
);
break :wd;
}
var wd_val: configpkg.WorkingDirectory = .{ .path = wd };
if (wd_val.finalize(config.arenaAlloc())) |_| {
config.@"working-directory" = wd_val;
} else |err| {
log.warn(
"error finalizing working directory config dir={s} err={}",
.{ wd_val.path, err },
);
}
}
}
// If we have a command from the options then we set it.
if (opts.command) |c_command| {
const cmd = std.mem.sliceTo(c_command, 0);
if (cmd.len > 0) {
config.command = .{ .shell = cmd };
config.@"wait-after-command" = true;
}
}
// Apply any environment variables that were requested.
if (opts.env_var_count > 0) {
const alloc = config.arenaAlloc();
for (opts.env_vars.?[0..opts.env_var_count]) |env_var| {
const key = std.mem.sliceTo(env_var.key, 0);
const value = std.mem.sliceTo(env_var.value, 0);
try config.env.map.put(
alloc,
try alloc.dupeZ(u8, key),
try alloc.dupeZ(u8, value),
);
}
}
// If we have an initial input then we set it.
if (opts.initial_input) |c_input| {
const alloc = config.arenaAlloc();
// We need to escape the string because the "raw" field
// expects a Zig string.
var buf: std.Io.Writer.Allocating = .init(alloc);
defer buf.deinit();
try std.zig.stringEscape(
std.mem.sliceTo(c_input, 0),
&buf.writer,
);
config.input.list.clearRetainingCapacity();
try config.input.list.append(
alloc,
.{ .raw = try buf.toOwnedSliceSentinel(0) },
);
}
// Wait after command
if (opts.wait_after_command) {
config.@"wait-after-command" = true;
}
// Initialize our surface right away. We're given a view that is
// ready to use.
try self.core_surface.init(
app.core_app.alloc,
&config,
app.core_app,
app,
self,
);
errdefer self.core_surface.deinit();
// If our options requested a specific font-size, set that.
if (opts.font_size != 0) {
var font_size = self.core_surface.font_size;
font_size.points = opts.font_size;
try self.core_surface.setFontSize(font_size);
}
}
pub fn deinit(self: *Surface) void {
// Shut down our inspector
self.freeInspector();
// Free our title
if (self.title) |v| self.app.core_app.alloc.free(v);
// Remove ourselves from the list of known surfaces in the app.
self.app.core_app.deleteSurface(self);
// Clean up our core surface so that all the rendering and IO stop.
self.core_surface.deinit();
}
/// Initialize the inspector instance. A surface can only have one
/// inspector at any given time, so this will return the previous inspector
/// if it was already initialized.
pub fn initInspector(self: *Surface) !*Inspector {
if (self.inspector) |v| return v;
const alloc = self.app.core_app.alloc;
const inspector = try alloc.create(Inspector);
errdefer alloc.destroy(inspector);
inspector.* = try .init(self);
self.inspector = inspector;
return inspector;
}
pub fn freeInspector(self: *Surface) void {
if (self.inspector) |v| {
v.deinit();
self.app.core_app.alloc.destroy(v);
self.inspector = null;
}
}
pub fn core(self: *Surface) *CoreSurface {
return &self.core_surface;
}
pub fn rtApp(self: *const Surface) *App {
return self.app;
}
pub fn close(self: *const Surface, process_alive: bool) void {
const func = self.app.opts.close_surface orelse {
log.info("runtime embedder does not support closing a surface", .{});
return;
};
func(self.userdata, process_alive);
}
pub fn getContentScale(self: *const Surface) !apprt.ContentScale {
return self.content_scale;
}
pub fn getSize(self: *const Surface) !apprt.SurfaceSize {
return self.size;
}
pub fn ioMode(self: *const Surface) IoMode {
return self.io_mode;
}
pub fn ioWriteCallback(self: *const Surface) ?IoWriteCallback {
return self.io_write_cb;
}
pub fn ioWriteUserdata(self: *const Surface) ?*anyopaque {
return self.io_write_userdata;
}
pub fn getTitle(self: *Surface) ?[:0]const u8 {
return self.title;
}
pub fn supportsClipboard(
self: *const Surface,
clipboard_type: apprt.Clipboard,
) bool {
return switch (clipboard_type) {
.standard => true,
.selection, .primary => self.app.opts.supports_selection_clipboard,
};
}
pub fn clipboardRequest(
self: *Surface,
clipboard_type: apprt.Clipboard,
state: apprt.ClipboardRequest,
) !bool {
// We need to allocate to get a pointer to store our clipboard request
// so that it is stable until the read_clipboard callback and call
// complete_clipboard_request. This sucks but clipboard requests aren't
// high throughput so it's probably fine.
const alloc = self.app.core_app.alloc;
const state_ptr = try alloc.create(apprt.ClipboardRequest);
errdefer alloc.destroy(state_ptr);
state_ptr.* = state;
const started = self.app.opts.read_clipboard(
self.userdata,
@intCast(@intFromEnum(clipboard_type)),
state_ptr,
);
if (!started) {
alloc.destroy(state_ptr);
return false;
}
return true;
}
fn completeClipboardRequest(
self: *Surface,
str: [:0]const u8,
state: *apprt.ClipboardRequest,
confirmed: bool,
) void {
const alloc = self.app.core_app.alloc;
// Attempt to complete the request, but we may request
// confirmation.
self.core_surface.completeClipboardRequest(
state.*,
str,
confirmed,
) catch |err| switch (err) {
error.UnsafePaste,
error.UnauthorizedPaste,
=> {
self.app.opts.confirm_read_clipboard(
self.userdata,
str.ptr,
state,
state.*,
);
return;
},
else => log.err("error completing clipboard request err={}", .{err}),
};
// We don't defer this because the clipboard confirmation route
// preserves the clipboard request.
alloc.destroy(state);
}
pub fn setClipboard(
self: *const Surface,
clipboard_type: apprt.Clipboard,
contents: []const apprt.ClipboardContent,
confirm: bool,
) !void {
const alloc = self.app.core_app.alloc;
const array = try alloc.alloc(CAPI.ClipboardContent, contents.len);
defer alloc.free(array);
for (contents, 0..) |content, i| {
array[i] = .{
.mime = content.mime,
.data = content.data,
};
}
self.app.opts.write_clipboard(
self.userdata,
@intCast(@intFromEnum(clipboard_type)),
array.ptr,
array.len,
confirm,
);
}
pub fn getCursorPos(self: *const Surface) !apprt.CursorPos {
return self.cursor_pos;
}
pub fn refresh(self: *Surface) void {
self.core_surface.refreshCallback() catch |err| {
log.err("error in refresh callback err={}", .{err});
return;
};
}
pub fn draw(self: *Surface) void {
self.core_surface.draw() catch |err| {
log.err("error in draw err={}", .{err});
return;
};
}
pub fn renderNow(self: *Surface) void {
self.core_surface.applyPendingResizeIfNeeded();
self.core_surface.renderer_thread.renderNow();
}
pub fn updateContentScale(self: *Surface, x: f64, y: f64) void {
// We are an embedded API so the caller can send us all sorts of
// garbage. We want to make sure that the float values are valid
// and we don't want to support fractional scaling below 1.
const x_scaled = @max(1, if (std.math.isNan(x)) 1 else x);
const y_scaled = @max(1, if (std.math.isNan(y)) 1 else y);
self.content_scale = .{
.x = @floatCast(x_scaled),
.y = @floatCast(y_scaled),
};
self.core_surface.contentScaleCallback(self.content_scale) catch |err| {
log.err("error in content scale callback err={}", .{err});
return;
};
}
pub fn updateSize(self: *Surface, width: u32, height: u32) void {
// Runtimes sometimes generate superfluous resize events even
// if the size did not actually change (SwiftUI). We check
// that the size actually changed from what we last recorded
// since resizes are expensive.
if (self.size.width == width and self.size.height == height) return;
self.size = .{
.width = width,
.height = height,
};
// Call the primary callback.
self.core_surface.sizeCallback(self.size) catch |err| {
log.err("error in size callback err={}", .{err});
return;
};
}
pub fn colorSchemeCallback(self: *Surface, scheme: apprt.ColorScheme) void {
self.core_surface.colorSchemeCallback(scheme) catch |err| {
log.err("error setting color scheme err={}", .{err});
return;
};
}
pub fn mouseButtonCallback(
self: *Surface,
action: input.MouseButtonState,
button: input.MouseButton,
mods: input.Mods,
) bool {
return self.core_surface.mouseButtonCallback(action, button, mods) catch |err| {
log.err("error in mouse button callback err={}", .{err});
return false;
};
}
pub fn mousePressureCallback(
self: *Surface,
stage: input.MousePressureStage,
pressure: f64,
) void {
self.core_surface.mousePressureCallback(stage, pressure) catch |err| {
log.err("error in mouse pressure callback err={}", .{err});
return;
};
}
pub fn scrollCallback(
self: *Surface,
xoff: f64,
yoff: f64,
mods: input.ScrollMods,
) void {
self.core_surface.scrollCallback(xoff, yoff, mods) catch |err| {
log.err("error in scroll callback err={}", .{err});
return;
};
}
pub fn cursorPosCallback(
self: *Surface,
x: f64,
y: f64,
mods: input.Mods,
) void {
// Convert our unscaled x/y to scaled.
const pos = self.cursorPosToPixels(.{
.x = @floatCast(x),
.y = @floatCast(y),
}) catch |err| {
log.err(
"error converting cursor pos to scaled pixels in cursor pos callback err={}",
.{err},
);
return;
};
// There are cases where the platform reports a mouse motion event
// without the cursor actually moving. For example, on macOS, updating
// the window title can trigger a phantom mouse-move event at the same
// coordinates. This can cause the mouse to incorrectly unhide when
// mouse-hide-while-typing is enabled (commonly seen with TUI apps
// like Zellij that frequently update the title). To prevent incorrect
// behavior, we only continue with callback logic if the cursor has
// actually moved.
if (@abs(self.cursor_pos.x - pos.x) < 1 and
@abs(self.cursor_pos.y - pos.y) < 1 and
self.cursor_pos_mods.equal(mods)) return;
self.cursor_pos = pos;
self.cursor_pos_mods = mods;
self.core_surface.cursorPosCallback(self.cursor_pos, mods) catch |err| {
log.err("error in cursor pos callback err={}", .{err});
return;
};
}
pub fn preeditCallback(self: *Surface, preedit_: ?[]const u8) void {
_ = self.core_surface.preeditCallback(preedit_) catch |err| {
log.err("error in preedit callback err={}", .{err});
return;
};
}
pub fn textCallback(self: *Surface, text: []const u8) void {
_ = self.core_surface.textCallback(text) catch |err| {
log.err("error in key callback err={}", .{err});
return;
};
}
pub fn textInputCallback(self: *Surface, text: []const u8) void {
_ = self.core_surface.textInputCallback(text) catch |err| {
log.err("error in text input callback err={}", .{err});
return;
};
}
pub fn focusCallback(self: *Surface, focused: bool) void {
self.core_surface.focusCallback(focused) catch |err| {
log.err("error in focus callback err={}", .{err});
return;
};
}
pub fn occlusionCallback(self: *Surface, visible: bool) void {
self.core_surface.occlusionCallback(visible) catch |err| {
log.err("error in occlusion callback err={}", .{err});
return;
};
}
fn queueInspectorRender(self: *Surface) void {
_ = self.app.performAction(
.{ .surface = &self.core_surface },
.render_inspector,
{},
) catch |err| {
log.err("error rendering the inspector err={}", .{err});
return;
};
}
pub fn newSurfaceOptions(self: *const Surface, context: apprt.surface.NewSurfaceContext) apprt.Surface.Options {
const font_size: f32 = font_size: {
if (!self.app.config.@"window-inherit-font-size") break :font_size 0;
break :font_size self.core_surface.font_size.points;
};
const working_directory: ?[*:0]const u8 = wd: {
if (!apprt.surface.shouldInheritWorkingDirectory(context, &self.app.config)) break :wd null;
const cwd = self.core_surface.pwd(self.app.core_app.alloc) catch null orelse break :wd null;
defer self.app.core_app.alloc.free(cwd);
break :wd self.app.core_app.alloc.dupeZ(u8, cwd) catch null;
};
return .{
.font_size = font_size,
.working_directory = working_directory,