-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathEditor.zig
More file actions
4336 lines (3848 loc) · 193 KB
/
Copy pathEditor.zig
File metadata and controls
4336 lines (3848 loc) · 193 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
const std = @import("std");
const builtin = @import("builtin");
const icons = @import("icons");
const assets = @import("assets");
const objc = @import("objc");
const cozette_ttf = assets.files.fonts.@"CozetteVector.ttf";
const cozette_bold_ttf = assets.files.fonts.@"CozetteVectorBold.ttf";
const comfortaa_ttf = assets.files.fonts.@"Comfortaa-Regular.ttf";
const comfortaa_bold_ttf = assets.files.fonts.@"Comfortaa-Bold.ttf";
const plus_jakarta_sans_ttf = assets.files.fonts.@"PlusJakartaSans-Regular.ttf";
const plus_jakarta_sans_bold_ttf = assets.files.fonts.@"PlusJakartaSans-Bold.ttf";
const build_opts = @import("build_opts");
const fizzy = @import("../fizzy.zig");
const dvui = @import("dvui");
const update_notify = @import("../backend/update_notify.zig");
const App = fizzy.App;
const Editor = @This();
pub const Recents = @import("Recents.zig");
pub const Settings = @import("Settings.zig");
pub const Dialogs = @import("dialogs/Dialogs.zig");
pub const Keybinds = @import("Keybinds.zig");
const KeybindSettings = @import("KeybindSettings.zig");
pub const menu_model = @import("menu_model.zig");
const workbench_mod = @import("workbench");
const text_mod = @import("text");
const markdown_mod = @import("markdown");
const image_mod = @import("image");
/// The bundled built-in modules, exactly the ones `postInit` imports and registers above.
/// Each exports its own `pub const plugin_id` (single source of truth — see e.g. `text_mod.plugin_id`)
/// instead of this list retyping the id strings a second time; adding a 5th built-in is one
/// line here, alongside its import/registration, not a separately-maintained string list.
const bundled_modules = .{ workbench_mod, text_mod, image_mod, markdown_mod };
const PluginLoader = if (builtin.target.cpu.arch == .wasm32)
@import("PluginLoader_stub.zig")
else
@import("PluginLoader.zig");
const PluginStore = @import("PluginStore.zig");
const PluginSettingsPane = @import("PluginSettingsPane.zig");
const SettingsTree = @import("SettingsTree.zig");
const OutputPanel = @import("OutputPanel.zig");
const SettingsPluginsZon = @import("SettingsPluginsZon.zig");
const SettingsWatcher = @import("SettingsWatcher.zig");
const Constants = @import("Constants.zig");
const DocumentWatcher = @import("DocumentWatcher.zig");
pub const Workspace = workbench_mod.Workspace;
pub const Explorer = @import("explorer/Explorer.zig");
pub const IgnoreRules = @import("explorer/IgnoreRules.zig");
pub const Panel = @import("panel/Panel.zig");
pub const Sidebar = @import("Sidebar.zig");
pub const Infobar = @import("Infobar.zig");
pub const Menu = @import("Menu.zig");
pub const FileLoadJob = workbench_mod.FileLoadJob;
pub const sdk = fizzy.sdk;
pub const Host = sdk.Host;
/// Workbench: the file-management home — file tree, open/load flow, and the
/// workspace/tabs/splits system, plus the per-branch explorer decoration registry.
pub const Workbench = workbench_mod.Workbench;
/// This arena is for small per-frame editor allocations, such as path joins, null terminations and labels.
/// Do not free these allocations, instead, this allocator will be .reset(.retain_capacity) each frame
arena: std.heap.ArenaAllocator,
config_folder: []const u8,
palette_folder: []const u8,
/// Plugin registry + service locator exposed to plugins
host: Host,
/// File-management workbench (per-branch explorer decorations, …)
workbench: Workbench,
/// Keeps plugin dylibs mapped while their vtables are live (native only).
loaded_plugin_libs: std.ArrayListUnmanaged(PluginLoader.LoadedLib) = .empty,
/// Runtime bookkeeping of user-plugin ids that are present on disk but not loaded
/// (explicitly disabled, or freshly dropped into `plugins/` with no `.enabled = true`).
/// Persistence lives per-plugin as `.plugins.<id>.enabled` in `settings.zon` (R12) — this
/// list is only the UI/skip-load set for the current session. Freed in `deinit`.
disabled_plugin_ids: std.ArrayListUnmanaged([]const u8) = .empty,
/// Shell-only pending `.plugins.<id>.enabled` writes (id → new bool), drained by
/// `writeMergedSettings` alongside `host.plugin_settings_pending`. Never touched by a
/// plugin itself — only by `setPluginEnabled` / store install. Keys are app-allocator-owned.
plugin_enabled_pending: std.StringArrayHashMapUnmanaged(bool) = .empty,
/// Snapshot of dvui's *built-in* keybinds (`char_left`, `copy`, `next_widget`, …), taken in
/// `init` before the shell adds its own. `Window.init` installs these once and never again,
/// so `rebuildKeybinds` — which wipes the map to drop an unloaded plugin's binds — must put
/// them back or every widget's caret/clipboard handling silently dies after the first plugin
/// load or unload. Keys are dvui's own static literals; only the map itself is owned here.
dvui_default_keybinds: std.StringHashMapUnmanaged(dvui.enums.Keybind) = .empty,
/// Resolved keybinding table: chord -> command id. Rebuilt by `Keybinds.buildKeymap`
/// whenever `rebuildKeybinds` runs (plugin load/unload), so a plugin's binds never outlive
/// the image their strings live in.
keymap: @import("keymap/keymap.zig").Keymap = .{},
/// Parsed `keybinds.zon`. Held because `keymap` borrows its command-id and owner-id strings —
/// it must outlive the keymap and is replaced wholesale on every rebuild.
keybinds_overrides: ?@import("keymap/keymap.zig").zon.File = null,
/// Cached `Keymap.conflicts()` result from the last rebuild — owned, freed on next rebuild.
keybind_conflicts: ?[]@import("keymap/keymap.zig").Conflict = null,
/// Which default keymap the shell starts from.
keybind_profile: Keybinds.Profile = .vscode,
/// VSCode-style Quick Open / command palette overlay.
command_palette: @import("CommandPalette.zig") = .{},
/// User plugins that failed to load this session, so the UI can tell the author what
/// went wrong instead of failing silently into the log. Populated by `loadUserPlugins`;
/// strings are owned here and freed in `deinit`. Surfaced in the Plugins store tab
/// (`PluginStore.zig`), not a startup dialog.
failed_user_plugins: std.ArrayListUnmanaged(FailedPlugin) = .empty,
settings: Settings = undefined,
recents: Recents = undefined,
explorer: *Explorer,
panel: *Panel,
last_titlebar_color: dvui.Color,
sidebar: Sidebar,
infobar: Infobar,
/// The root folder that will be searched for files and a .fizproject file
folder: ?[]const u8 = null,
/// Whether a text-input widget held keyboard focus at the end of the last frame.
///
/// `dvui.wantTextInput` is the cross-cutting signal — dvui's own `TextEntryWidget`, the text
/// plugin's fork, and any plugin entry all call it on frames they have focus — but it is reset
/// by `Window.begin` and filled in as widgets draw, so it can only be read as last frame's
/// answer. That is fine for deciding who owns a clipboard verb: focus doesn't change between
/// the keystroke and the frame that handles it.
text_input_focused: bool = false,
/// From `.fizignore` (preferred) or `.gitignore` at the project root; used by the Files explorer.
ignore: IgnoreRules = .{},
themes: std.ArrayList(dvui.Theme) = .empty,
open_files: std.AutoArrayHashMapUnmanaged(u64, sdk.DocHandle) = .empty,
/// Background file-load jobs in flight. Keyed by absolute path. Each job's worker thread loads
/// the document bytes off the main thread; the main thread polls via `processLoadingJobs`
/// and moves completed results into `open_files`. The map owns its key strings via each job's
/// `path` allocation; the StringHashMap stores key slices that point into job memory.
loading_jobs: std.StringHashMapUnmanaged(*FileLoadJob) = .empty,
/// True iff a loading job should set its target file as the active file once it lands.
/// `setActiveFile`-on-completion respects the most recent open request — multiple in-flight
/// loads only auto-focus the most recently requested one.
last_load_request_path: ?[]const u8 = null,
file_id_counter: u64 = 0,
window_opacity: f32 = 1.0,
/// Animated window-background opacity multiplier. Eases toward the windowed
/// target (translucent, vibrancy shows through) or 1.0 (opaque) when
/// maximized/fullscreen, so the vibrancy fades in/out across fullscreen
/// transitions instead of snapping. `< 0` is a sentinel meaning "snap to the
/// target on the first frame" so there is no fade at launch.
window_opacity_anim: f32 = -1.0,
/// Menu-bar clicks waiting for a safe point in the frame. Each is a `menu_model` tag.
pending_native_menu_actions: [16]usize = undefined,
pending_native_menu_actions_len: u8 = 0,
/// Same queue/flush shape as `pending_native_menu_actions`, but for the generic macOS
/// dispatch path: indices into `host.native_menu_items` (see `rebuildDynamicNativeMenus`).
pending_native_menu_item_indices: [16]usize = undefined,
pending_native_menu_item_indices_len: u8 = 0,
/// When set, next `tick` runs `warmupDrawingComposites` on the active file (after open or drawing-tool select).
pending_composite_warmup: bool = false,
/// Filled from the async SDL save dialog callback, then applied inside `tick` (when `currentWindow` is valid).
pending_save_as_path: ?[]u8 = null,
/// After Save As from "Save and Close", close this file id once save completes.
pending_close_file_id: ?u64 = null,
/// Files whose async save was kicked off by "Save and Close" (single-doc) — once
/// `File.isSaving()` clears, `tickPendingSaveCloses` closes the file. Set is fine
/// because at most one entry per file (saveAsync no-ops while already saving).
pending_close_after_save: std.AutoArrayHashMapUnmanaged(u64, void) = .empty,
/// "Save all and quit" queue. Walked by `advanceSaveAllQuit`: items move from this
/// queue into `quit_saves_in_flight` when their save kicks off, then drop out when
/// their save completes and the file closes. Non-empty (or in-flight non-empty) ⇒
/// save-all quit in progress.
quit_save_all_ids: std.ArrayListUnmanaged(u64) = .empty,
/// Files whose async save was started as part of save-all quit and we're waiting on.
/// When this AND `quit_save_all_ids` are both empty, the quit completes.
quit_saves_in_flight: std.AutoArrayHashMapUnmanaged(u64, void) = .empty,
/// True during save-all quit (nested Save As / flat-raster prompts).
quit_in_progress: bool = false,
/// Next frame: continue save-all quit (`advanceSaveAllQuit`).
pending_quit_continue: bool = false,
/// End this frame with `App.Result.close` (e.g. quit finished).
pending_app_close: bool = false,
/// Hash of the last serialized settings.zon text written or captured at startup; avoids
/// redundant writes without keeping a full duplicate copy of the text around. Doubles as the
/// "was that change ours" filter for `settings_watcher` (see R11 in
/// docs/PLUGIN_MANIFEST_PLAN.md) — a change to disk whose hash matches this is our own last
/// write, not an external edit worth reconciling.
settings_last_saved_hash: ?u64 = null,
/// True after user-driven settings edits until successfully persisted or snapshot matches disk.
settings_dirty: bool = false,
/// Monotonic deadline (`perf.nanoTimestamp()`): autosave runs when dirty and `now >= deadline`.
settings_save_deadline_ns: i128 = 0,
/// Explorer/panel split ratios — "window shape" state persisted in `window.zon`, not
/// `settings.zon` (dragging a splitter fires every frame; keeping it out of the settings file
/// means normal window use never dirties a git-tracked settings.zon). Loaded once at startup
/// (see `init`); defaults match the pre-move `Settings` field defaults.
explorer_ratio: f32 = 0.35,
panel_ratio: f32 = 0.25,
/// Debounced-save bookkeeping for the ratios above, separate from `settings_dirty`/
/// `settings_save_deadline_ns` — sidebar/panel dragging must not force a settings.zon write
/// attempt on every drag frame.
window_ratios_dirty: bool = false,
window_ratios_save_deadline_ns: i128 = 0,
/// Watches `<config>/` recursively (via nightwatch — see R12) for external `settings.zon`
/// changes and newly-created plugin directories, reconciling them live via `tick`. Null on wasm,
/// on an unsupported OS, or if starting the watch failed — all best-effort: fizzy must never
/// fail to launch because the watcher couldn't start, it just silently doesn't get live
/// reconciliation. Set up in `postInit` (needs `editor` at its final heap address — see
/// `SettingsWatcher.start`'s doc comment), torn down first in `deinit`.
settings_watcher: ?SettingsWatcher = null,
/// Watches each open on-disk document for external edits. Clean docs reload via
/// `Plugin.reloadDocument`; dirty docs set a conflict flag and `save` shows
/// `FileChangedOnDisk`. Null on wasm / unsupported OS / start failure — best-effort.
document_watcher: ?DocumentWatcher = null,
/// Timestamp of the most recent touch press anywhere in the app, or null if there
/// hasn't been one. `Editor.draw` forces a per-frame refresh during the post-press
/// grace window so `dvui.ContextWidget.updateHold` actually re-runs and gets a chance
/// to open the hold-to-context menu on touch-only hardware.
last_touch_press_ns: ?i128 = null,
const embedded_fonts: []const dvui.Font.Source = &.{
.{
.family = dvui.Font.array("CozetteVector"),
.bytes = cozette_ttf,
},
.{
.family = dvui.Font.array("CozetteVector"),
.bytes = cozette_bold_ttf,
.weight = .bold,
},
.{
.family = dvui.Font.array("Comfortaa"),
.bytes = comfortaa_ttf,
},
.{
.family = dvui.Font.array("Comfortaa"),
.bytes = comfortaa_bold_ttf,
.weight = .bold,
},
.{
.family = dvui.Font.array("PlusJakartaSans"),
.bytes = plus_jakarta_sans_ttf,
},
.{
.family = dvui.Font.array("PlusJakartaSans"),
.bytes = plus_jakarta_sans_bold_ttf,
.weight = .bold,
},
};
pub fn init(
app: *App,
) !Editor {
const arena = dvui.currentWindow().arena();
// Wasm: skip the env-map / known-folders lookup. `std.process.Environ.put`
// analyzes a `block.view()` call that doesn't compile on freestanding (where
// `Block == GlobalBlock`), and the browser has no concept of OS user dirs
// anyway. `app.root_path` ("." on wasm) is the only sensible fallback.
const config_root: []const u8 = if (comptime builtin.target.cpu.arch == .wasm32)
app.root_path
else config_root_blk: {
break :config_root_blk try fizzy.paths.configRoot(dvui.io, arena, fizzy.processEnviron(), app.root_path);
};
const config_folder: []const u8 = if (comptime builtin.target.cpu.arch == .wasm32)
app.root_path
else config_folder_blk: {
break :config_folder_blk try fizzy.paths.configFolder(fizzy.app.allocator, dvui.io, arena, fizzy.processEnviron(), app.root_path);
};
// One-time migration: pre-rename builds used `Fizzy/` (capitalized).
// On case-insensitive filesystems (Windows NTFS, macOS APFS) `fizzy/` already
// resolves to that same directory, so the rename is a no-op and the
// failure is ignored. On case-sensitive filesystems (most Linux) the legacy
// dir is otherwise orphaned, so we move it across to preserve user settings.
// Wasm: no filesystem, no migration; `Io.Dir.renameAbsolute` pulls in posix.AT.
if (comptime builtin.target.cpu.arch != .wasm32) {
const legacy = std.fs.path.join(arena, &.{ config_root, "Fizzy" }) catch null;
if (legacy) |legacy_path| {
// Only rename if the new path doesn't already have content.
const new_exists = blk: {
std.Io.Dir.accessAbsolute(dvui.io, config_folder, .{ .read = true }) catch break :blk false;
break :blk true;
};
const legacy_exists = blk: {
std.Io.Dir.accessAbsolute(dvui.io, legacy_path, .{ .read = true }) catch break :blk false;
break :blk true;
};
if (legacy_exists and !new_exists) {
std.Io.Dir.renameAbsolute(legacy_path, config_folder, dvui.io) catch |err| {
std.log.warn("legacy config folder migration ({s} -> {s}) failed: {s}", .{ legacy_path, config_folder, @errorName(err) });
};
}
}
}
const palette_folder = std.fs.path.join(fizzy.app.allocator, &.{ config_folder, "palettes" }) catch config_folder;
var editor: Editor = .{
.config_folder = config_folder,
.palette_folder = palette_folder,
.explorer = try app.allocator.create(Explorer),
.panel = try app.allocator.create(Panel),
.sidebar = try .init(),
.infobar = try .init(),
.arena = .init(std.heap.page_allocator),
.last_titlebar_color = dvui.themeGet().color(.control, .fill),
.themes = .empty,
.host = .init(app.allocator),
.workbench = .init(app.allocator),
};
try editor.workbench.registerBuiltins();
// Each plugin persists its own `<plugins_dir>/<id>.settings.zon` (see `Host.
// loadPluginSettings`/`flushPluginSettings`) rather than a blob embedded in settings.zon.
// Set before `Settings.load` (which may one-shot migrate a legacy settings.json's plugin
// blobs out to these files) and before any plugin registers and reads its own settings.
const plugins_dir: ?[]const u8 = if (comptime builtin.target.cpu.arch == .wasm32)
null
else
try std.fs.path.join(app.allocator, &.{ editor.config_folder, "plugins" });
editor.host.plugins_dir = plugins_dir;
{
const settings_path = try std.fs.path.join(app.allocator, &.{ editor.config_folder, "settings.zon" });
editor.settings = try Settings.load(app.allocator, settings_path, plugins_dir);
}
if (comptime builtin.target.cpu.arch != .wasm32) {
const ratios = fizzy.backend.loadWindowRatios(editor.config_folder);
editor.explorer_ratio = ratios.explorer_ratio;
editor.panel_ratio = ratios.panel_ratio;
}
// Save-queue worker is owned by the pixel-art plugin (`initPlugin` in `postInit`).
{ // Setup themes
var fizzy_dark = dvui.themeGet();
fizzy_dark.embedded_fonts = embedded_fonts;
fizzy_dark.window = .{
.fill = .{ .r = 28, .g = 29, .b = 36, .a = 255 },
.border = .{ .r = 34, .g = 35, .b = 42, .a = 255 },
.text = .{ .r = 206, .g = 163, .b = 127, .a = 255 },
};
fizzy_dark.control = .{
.fill = .{ .r = 28, .g = 29, .b = 36, .a = 255 },
.border = .{ .r = 34, .g = 35, .b = 42, .a = 255 },
.text = .{ .r = 134, .g = 138, .b = 148, .a = 255 },
};
fizzy_dark.highlight = .{
.fill = .{ .r = 47, .g = 179, .b = 135, .a = 255 },
.border = .{ .r = 47, .g = 179, .b = 135, .a = 255 },
.text = fizzy_dark.window.fill,
};
fizzy_dark.err = .{
.fill = .{ .r = 109, .g = 35, .b = 54, .a = 255 },
};
// theme.content
fizzy_dark.fill = .{ .r = 42, .g = 44, .b = 54, .a = 255 };
fizzy_dark.text = fizzy_dark.window.text.?;
fizzy_dark.focus = fizzy_dark.highlight.fill.?;
fizzy_dark.dark = true;
fizzy_dark.name = "Fizzy Dark";
fizzy_dark.font_body = .find(.{ .family = "Comfortaa", .size = editor.settings.font_body_size });
fizzy_dark.font_title = .find(.{ .family = "Comfortaa", .size = editor.settings.font_title_size, .weight = .bold });
fizzy_dark.font_heading = .find(.{ .family = "PlusJakartaSans", .size = editor.settings.font_heading_size, .weight = .bold });
fizzy_dark.font_mono = .find(.{ .family = "CozetteVector", .size = editor.settings.font_mono_size });
var moi: dvui.Theme = fizzy_dark;
moi.name = "Moi";
moi.window = .{
.fill = .{ .r = 84, .g = 12, .b = 26, .a = 255 },
.border = .{ .r = 104, .g = 62, .b = 72, .a = 255 },
.text = .{ .r = 255, .g = 190, .b = 190, .a = 240 },
};
moi.control = .{
.fill = moi.window.fill.?.lighten(10),
.border = .{ .r = 104, .g = 62, .b = 72, .a = 255 },
.text = .{ .r = 255, .g = 235, .b = 235, .a = 200 },
};
moi.highlight = .{
.fill = moi.window.fill.?.lighten(10),
};
moi.fill = moi.control.fill.?;
moi.text = moi.window.text.?;
moi.focus = moi.highlight.fill.?;
var fizzy_light = fizzy_dark;
fizzy_light.dark = false;
fizzy_light.name = "Fizzy Light";
fizzy_light.window = .{
.fill = .{ .r = 240, .g = 240, .b = 245, .a = 255 },
.border = dvui.Theme.builtin.adwaita_light.window.border,
.text = .{ .r = 120, .g = 70, .b = 65, .a = 255 },
};
fizzy_light.control = dvui.Theme.builtin.adwaita_light.control;
fizzy_light.highlight = .{
.fill = .{ .r = 170, .g = 130, .b = 140, .a = 255 },
.text = fizzy_light.window.fill,
};
fizzy_light.err = .{
.fill = .{ .r = 109, .g = 35, .b = 54, .a = 255 },
};
// theme.content
fizzy_light.fill = .{ .r = 200, .g = 200, .b = 205, .a = 255 };
fizzy_light.text = .{ .r = 40, .g = 40, .b = 45, .a = 255 };
fizzy_light.focus = fizzy_light.highlight.fill.?;
// User-themes scan reads a directory off disk (Io.Dir.cwd → posix.AT / NAME_MAX),
// unavailable on wasm32-freestanding. No persistent FS in browser anyway.
if (comptime builtin.target.cpu.arch != .wasm32) {
appendUserThemes(app.allocator, &editor) catch |err| {
dvui.log.err("Failed to prepare user themes folder: {s}", .{@errorName(err)});
};
}
editor.themes.append(app.allocator, fizzy_dark) catch {
dvui.log.err("Failed to append theme", .{});
return error.FailedToAppendTheme;
};
editor.themes.append(app.allocator, moi) catch {
dvui.log.err("Failed to append moi theme", .{});
return error.FailedToAppendMoiTheme;
};
editor.themes.append(app.allocator, fizzy_light) catch {
dvui.log.err("Failed to append fizzy light theme", .{});
return error.FailedToAppendFizzyLightTheme;
};
for (dvui.Theme.builtins) |b| {
editor.themes.append(app.allocator, b) catch {
dvui.log.err("Failed to append builtin theme", .{});
return error.FailedToAppendBuiltinTheme;
};
}
try editor.applySettingsTheme();
editor.applyHoldMenuDuration();
}
// Config + palette folder creation and recents-from-disk load are no-ops on
// wasm: `Io.Dir.accessAbsolute` / `createDirAbsolute` / `Recents.load` all
// walk `Io.Dir.cwd()` (posix.AT), unavailable on wasm32-freestanding.
if (comptime builtin.target.cpu.arch != .wasm32) {
var valid_path: bool = true;
if (std.fs.path.isAbsolute(editor.config_folder)) {
std.Io.Dir.accessAbsolute(dvui.io, editor.config_folder, .{ .read = true }) catch {
valid_path = false;
};
if (!valid_path) {
std.Io.Dir.createDirAbsolute(dvui.io, editor.config_folder, .default_dir) catch |err| dvui.log.err("Failed to create config folder: {s}: {any}", .{ editor.config_folder, err });
}
}
valid_path = true;
if (std.fs.path.isAbsolute(editor.palette_folder)) {
std.Io.Dir.accessAbsolute(dvui.io, editor.palette_folder, .{ .read = true }) catch {
valid_path = false;
};
if (!valid_path) {
std.Io.Dir.createDirAbsolute(dvui.io, editor.palette_folder, .default_dir) catch |err| dvui.log.err("Failed to create palette folder: {s}: {any}", .{ editor.palette_folder, err });
}
}
}
fizzy.perf.console_logging_enabled = Constants.perf_logging;
editor.recents = if (comptime builtin.target.cpu.arch == .wasm32)
.{ .folders = .init(app.allocator) }
else
Recents.load(app.allocator, try std.fs.path.join(app.allocator, &.{ editor.config_folder, "recents.zon" })) catch .{
.folders = .init(app.allocator),
};
fizzy.backend.setTitlebarColor(dvui.currentWindow(), dvui.themeGet().color(.content, .fill).opacity(if (dvui.themeGet().dark) editor.settings.window_opacity_dark else editor.settings.window_opacity_light));
editor.explorer.* = .init();
editor.panel.* = .init();
editor.open_files = .empty;
try editor.workbench.initDefaultWorkspace();
// Capture dvui's defaults before the shell's own binds land, so `rebuildKeybinds` can
// restore them after clearing the map.
editor.dvui_default_keybinds = try dvui.currentWindow().keybinds.clone(fizzy.app.allocator);
try Keybinds.register();
// Collect the initial settings.zon text for autosave dedup — must match exactly what
// `writeMergedSettings` would produce with no pending plugin writes (same composer, empty
// overlay), otherwise the very first autosave after startup would spuriously rewrite the
// file just because this seed only accounted for the shell's own fields, not `.plugins`.
if (comptime builtin.target.cpu.arch == .wasm32) {
const serialized = try Settings.serialize(&editor.settings, fizzy.app.allocator);
defer fizzy.app.allocator.free(serialized);
editor.settings_last_saved_hash = std.hash.Wyhash.hash(0, serialized);
} else {
const settings_path = try std.fs.path.join(fizzy.app.allocator, &.{ editor.config_folder, "settings.zon" });
defer fizzy.app.allocator.free(settings_path);
const composed = try editor.composeSettingsText(fizzy.app.allocator, settings_path, &.{});
defer fizzy.app.allocator.free(composed);
editor.settings_last_saved_hash = std.hash.Wyhash.hash(0, composed);
}
return editor;
}
/// Second-stage init that needs the editor at its FINAL heap address. `init`
/// builds an `Editor` by value and the caller copies it to the heap, so anything
/// that captures `&editor.*` (e.g. a service whose `ctx` is the editor pointer)
/// must run here — not in `init`, where it would point at the stack temporary.
/// Called from `App.AppInit` right after the heap copy. (The built-in branch
/// decorators registered in `init` are exempt: they store fn pointers, not `&editor`.)
/// Stable shell-builtin contribution id.
pub const view_settings = "shell.settings";
fn loadWorkbenchFromDylibEnabled() bool {
if (comptime builtin.target.cpu.arch == .wasm32) return false;
if (comptime build_opts.static_workbench) return false;
if (std.process.Environ.getAlloc(fizzy.processEnviron(), fizzy.app.allocator, "FIZZY_STATIC_WORKBENCH")) |v| {
defer fizzy.app.allocator.free(v);
return v.len == 0 or v[0] == '0';
} else |_| {}
return true;
}
fn loadTextFromDylibEnabled() bool {
if (comptime builtin.target.cpu.arch == .wasm32) return false;
if (comptime build_opts.static_text) return false;
if (std.process.Environ.getAlloc(fizzy.processEnviron(), fizzy.app.allocator, "FIZZY_STATIC_TEXT")) |v| {
defer fizzy.app.allocator.free(v);
return v.len == 0 or v[0] == '0';
} else |_| {}
return true;
}
fn loadMarkdownFromDylibEnabled() bool {
if (comptime builtin.target.cpu.arch == .wasm32) return false;
if (std.process.Environ.getAlloc(fizzy.processEnviron(), fizzy.app.allocator, "FIZZY_STATIC_MARKDOWN")) |v| {
defer fizzy.app.allocator.free(v);
return v.len == 0 or v[0] == '0';
} else |_| {}
return true;
}
fn loadImageFromDylibEnabled() bool {
if (comptime builtin.target.cpu.arch == .wasm32) return false;
if (comptime build_opts.static_image) return false;
if (std.process.Environ.getAlloc(fizzy.processEnviron(), fizzy.app.allocator, "FIZZY_STATIC_IMAGE")) |v| {
defer fizzy.app.allocator.free(v);
return v.len == 0 or v[0] == '0';
} else |_| {}
return true;
}
/// Stable workbench sidebar view id (matches `workbench.view_files`).
pub const workbench_files_view = workbench_mod.view_files;
/// Registered workbench plugin (dylib or static). Panics if missing after `postInit`.
pub fn workbenchPlugin(editor: *Editor) *sdk.Plugin {
return editor.host.pluginById("workbench") orelse @panic("workbench plugin not registered");
}
/// Registered text plugin (dylib or static). Panics if missing after `postInit`.
pub fn textPlugin(editor: *Editor) *sdk.Plugin {
return editor.host.pluginById("text") orelse @panic("text plugin not registered");
}
/// Push host dvui state into every loaded plugin dylib image.
pub fn syncLoadedPluginDvuiContexts(editor: *Editor) void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
for (editor.loaded_plugin_libs.items) |loaded| {
sdk.dvui_context.syncHostIntoPlugin(loaded.set_dvui_context);
}
}
/// Inject the host render bridge into every loaded plugin dylib (proxy backend).
pub fn syncLoadedPluginRenderBridge(editor: *Editor) void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
for (editor.loaded_plugin_libs.items) |loaded| {
sdk.render_bridge.syncHostIntoPlugin(loaded.set_render_bridge);
}
}
fn syncLoadedPluginGlobals(editor: *Editor, plugin_id: []const u8, arg_b: *anyopaque, arg_c: ?*anyopaque) void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
for (editor.loaded_plugin_libs.items) |loaded| {
if (!std.mem.eql(u8, loaded.plugin_id, plugin_id)) continue;
loaded.set_globals(@ptrCast(&fizzy.app.allocator), arg_b, arg_c);
}
}
/// Re-inject host-owned Globals into a loaded workbench dylib.
pub fn syncLoadedWorkbenchGlobals(editor: *Editor) void {
syncLoadedPluginGlobals(editor, "workbench", @ptrCast(&editor.host), @ptrCast(&editor.workbench));
}
fn appendLoadedPluginLib(editor: *Editor, loaded: PluginLoader.LoadedLib) !void {
const id_owned = try fizzy.app.allocator.dupe(u8, loaded.plugin_id);
var stored = loaded;
stored.plugin_id = id_owned;
try editor.loaded_plugin_libs.append(fizzy.app.allocator, stored);
}
/// Load `{exe_dir}/plugins/workbench.{ext}` and register via dylib entry.
pub fn loadWorkbenchDylib(editor: *Editor, exe_dir: []const u8) !void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
const path = try PluginLoader.builtinPluginPath(fizzy.app.allocator, exe_dir, "workbench");
errdefer fizzy.app.allocator.free(path);
const loaded = try PluginLoader.loadAndRegister(&editor.host, fizzy.app.allocator, path, "workbench", .{
.gpa = &fizzy.app.allocator,
.arg_b = @ptrCast(&editor.host), // workbench convention: arg_b = *Host
.arg_c = @ptrCast(&editor.workbench), // arg_c = *Workbench
});
try appendLoadedPluginLib(editor, loaded);
syncLoadedPluginDvuiContexts(editor);
syncLoadedPluginRenderBridge(editor);
}
/// Load `{exe_dir}/plugins/text.{ext}` and register via dylib entry.
pub fn loadTextDylib(editor: *Editor, exe_dir: []const u8) !void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
const path = try PluginLoader.builtinPluginPath(fizzy.app.allocator, exe_dir, "text");
errdefer fizzy.app.allocator.free(path);
const loaded = try PluginLoader.loadAndRegister(&editor.host, fizzy.app.allocator, path, "text", .{
.gpa = &fizzy.app.allocator,
.arg_b = @ptrCast(&editor.host),
.arg_c = null,
});
try appendLoadedPluginLib(editor, loaded);
syncLoadedPluginDvuiContexts(editor);
syncLoadedPluginRenderBridge(editor);
}
/// Load `{exe_dir}/plugins/markdown.{ext}` and register via dylib entry.
pub fn loadMarkdownDylib(editor: *Editor, exe_dir: []const u8) !void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
const path = try PluginLoader.builtinPluginPath(fizzy.app.allocator, exe_dir, "markdown");
errdefer fizzy.app.allocator.free(path);
const loaded = try PluginLoader.loadAndRegister(&editor.host, fizzy.app.allocator, path, "markdown", .{
.gpa = &fizzy.app.allocator,
.arg_b = @ptrCast(&editor.host),
.arg_c = null,
});
try appendLoadedPluginLib(editor, loaded);
syncLoadedPluginDvuiContexts(editor);
syncLoadedPluginRenderBridge(editor);
}
/// Load `{exe_dir}/plugins/image.{ext}` and register via dylib entry.
pub fn loadImageDylib(editor: *Editor, exe_dir: []const u8) !void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
const path = try PluginLoader.builtinPluginPath(fizzy.app.allocator, exe_dir, "image");
errdefer fizzy.app.allocator.free(path);
const loaded = try PluginLoader.loadAndRegister(&editor.host, fizzy.app.allocator, path, "image", .{
.gpa = &fizzy.app.allocator,
.arg_b = @ptrCast(&editor.host),
.arg_c = null,
});
try appendLoadedPluginLib(editor, loaded);
syncLoadedPluginDvuiContexts(editor);
syncLoadedPluginRenderBridge(editor);
}
/// Scan `<config_folder>/plugins/` for user-installed plugin dylibs and load each one.
///
/// Each sub-directory that contains `plugin.<ext>` is attempted in iteration order.
/// Failures are logged and skipped — a bad plugin never prevents the others from loading.
/// Built-in plugin IDs ("workbench", "text") are never overridden; any
/// user directory whose name collides with an already-registered plugin is skipped.
///
/// On success each loaded lib is appended to `loaded_plugin_libs` and the dvui context
/// + render bridge are synced once at the end. On wasm this is a no-op.
///
/// The user plugin directory does not need to exist; a missing directory is silently ignored.
/// A user plugin that failed to load, retained so the UI can surface it. `id` and `reason`
/// are heap-owned (app allocator) and freed in `deinit`.
pub const FailedPlugin = struct {
id: []const u8,
reason: []const u8,
/// Optional version / SDK detail when the dylib could be opened for probing.
detail: ?[]const u8 = null,
/// The plugin's own declared version, probed straight from the dylib without registering
/// it. Lets the store show "current version" for a build that is on disk but rejected —
/// null only when the dylib couldn't even be opened for probing.
plugin_version: ?std.SemanticVersion = null,
};
/// Record a failed user-plugin load so the UI can surface it. `id` and `reason` are copied
/// (the caller keeps ownership of its arguments). Best-effort: on OOM the failure is dropped
/// after being logged at the call site.
fn recordPluginFailure(editor: *Editor, id: []const u8, reason: []const u8, detail: ?[]const u8, plugin_version: ?std.SemanticVersion) void {
const id_owned = fizzy.app.allocator.dupe(u8, id) catch return;
const reason_owned = fizzy.app.allocator.dupe(u8, reason) catch {
fizzy.app.allocator.free(id_owned);
return;
};
const detail_owned: ?[]const u8 = if (detail) |d| fizzy.app.allocator.dupe(u8, d) catch null else null;
if (detail_owned == null and detail != null) {
fizzy.app.allocator.free(id_owned);
fizzy.app.allocator.free(reason_owned);
return;
}
editor.failed_user_plugins.append(fizzy.app.allocator, .{
.id = id_owned,
.reason = reason_owned,
.detail = detail_owned,
.plugin_version = plugin_version,
}) catch {
fizzy.app.allocator.free(id_owned);
fizzy.app.allocator.free(reason_owned);
if (detail_owned) |d| fizzy.app.allocator.free(d);
};
}
/// True if `id` is a user plugin present on disk that failed to load (ABI/SDK mismatch, etc.).
/// Lets the store offer replace/uninstall actions for a broken build instead of a dead end.
pub fn isFailedUserPlugin(editor: *Editor, id: []const u8) bool {
for (editor.failed_user_plugins.items) |f| {
if (std.mem.eql(u8, f.id, id)) return true;
}
return false;
}
/// Drop any recorded load-failure for `id` (freeing its strings). Called when the plugin later
/// loads successfully or is uninstalled, so a stale failure no longer lingers in the UI / dialog.
fn clearFailedUserPlugin(editor: *Editor, id: []const u8) void {
var i: usize = 0;
while (i < editor.failed_user_plugins.items.len) {
if (std.mem.eql(u8, editor.failed_user_plugins.items[i].id, id)) {
const f = editor.failed_user_plugins.orderedRemove(i);
fizzy.app.allocator.free(f.id);
fizzy.app.allocator.free(f.reason);
if (f.detail) |d| fizzy.app.allocator.free(d);
} else i += 1;
}
}
fn formatPluginProbeDetail(allocator: std.mem.Allocator, info: PluginLoader.PluginVersionInfo) ![]const u8 {
return std.fmt.allocPrint(allocator, "plugin {d}.{d}.{d}, min SDK {d}.{d}.{d}", .{
info.plugin_version.major,
info.plugin_version.minor,
info.plugin_version.patch,
info.min_sdk_version.major,
info.min_sdk_version.minor,
info.min_sdk_version.patch,
});
}
/// Human-readable, actionable explanation for a `PluginLoader.LoadError`.
fn pluginLoadFailureReason(err: PluginLoader.LoadError) []const u8 {
return switch (err) {
error.AbiMismatch => "built against an incompatible Fizzy SDK — rebuild the plugin against this Fizzy build",
error.AbiBuildEnvMismatch => "SDK versions match, but optimize mode does not match",
error.SdkVersionMismatch => "requires a newer Fizzy SDK — update Fizzy or install a matching plugin build",
error.PluginIdMismatch => "plugin id in the dylib does not match its filename — rename the file or fix manifest.id",
error.DylibOpenFailed => "the plugin library could not be opened (missing file, wrong architecture, or unresolved symbols)",
error.RegisterRejected => "the plugin's register() was rejected (often a duplicate plugin id — a built-in or another plugin already claims it)",
error.AbiFingerprintSymbolMissing,
error.RegisterSymbolMissing,
error.SetGlobalsSymbolMissing,
error.SetDvuiContextSymbolMissing,
error.SetRenderBridgeSymbolMissing,
error.SdkVersionSymbolMissing,
=> "the plugin is missing required entry symbols — rebuild it from a current root.zig template",
};
}
/// One-shot: moves any pre-R10 flat `{plugins_dir}/{id}.{ext}` into its own
/// `{plugins_dir}/{id}/{id}.{ext}` directory (see docs/PLUGIN_MANIFEST_PLAN.md R10). Collects the
/// list of flat files first, then renames in a second pass, so mutating the directory never races
/// the iterator that's still walking it. Best-effort: a single failed rename is logged and
/// skipped rather than aborting the rest.
fn migrateFlatPluginLayout(allocator: std.mem.Allocator, plugins_dir: []const u8, ext_suffix: []const u8) void {
var flat_ids: std.ArrayListUnmanaged([]const u8) = .empty;
defer {
for (flat_ids.items) |id| allocator.free(id);
flat_ids.deinit(allocator);
}
{
var dir = std.Io.Dir.cwd().openDir(dvui.io, plugins_dir, .{ .iterate = true }) catch return;
defer dir.close(dvui.io);
var iter = dir.iterate();
while (iter.next(dvui.io) catch null) |entry| {
if (entry.kind != .file) continue;
if (!std.mem.endsWith(u8, entry.name, ext_suffix)) continue;
const dot = std.mem.lastIndexOf(u8, entry.name, ".") orelse continue;
const id = entry.name[0..dot];
if (id.len == 0) continue;
const dup = allocator.dupe(u8, id) catch continue;
flat_ids.append(allocator, dup) catch allocator.free(dup);
}
}
for (flat_ids.items) |id| {
const new_dir = std.fs.path.join(allocator, &.{ plugins_dir, id }) catch continue;
defer allocator.free(new_dir);
std.Io.Dir.createDirAbsolute(dvui.io, new_dir, .default_dir) catch {}; // best-effort; exists is fine
const file_name = PluginLoader.pluginFilename(id, allocator) catch continue;
defer allocator.free(file_name);
const old_path = std.fs.path.join(allocator, &.{ plugins_dir, file_name }) catch continue;
defer allocator.free(old_path);
const new_path = std.fs.path.join(allocator, &.{ new_dir, file_name }) catch continue;
defer allocator.free(new_path);
std.Io.Dir.renameAbsolute(old_path, new_path, dvui.io) catch |err| {
dvui.log.warn("plugin '{s}': failed to migrate to its own directory: {s}", .{ id, @errorName(err) });
};
}
}
pub fn loadUserPlugins(editor: *Editor, config_folder: []const u8) void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
const plugins_dir = std.fs.path.join(fizzy.app.allocator, &.{ config_folder, "plugins" }) catch return;
defer fizzy.app.allocator.free(plugins_dir);
const ext_suffix: []const u8 = switch (builtin.os.tag) {
.windows => ".dll",
.macos => ".dylib",
else => ".so",
};
migrateFlatPluginLayout(fizzy.app.allocator, plugins_dir, ext_suffix);
// Leftover fresh-load temp copies from a previous run (see `PluginLoader.copyToFreshLoadPath`)
// — safe to clear unconditionally here since nothing is loaded from this directory yet.
PluginLoader.sweepLoadTempDir(fizzy.app.allocator, plugins_dir);
var dir = std.Io.Dir.cwd().openDir(dvui.io, plugins_dir, .{ .iterate = true }) catch return;
defer dir.close(dvui.io);
var loaded_any = false;
var loaded_count: usize = 0;
// Startup cost attributable to user plugins. `PluginLoader` logs any individual load over
// its slow threshold; this is the number to watch when "fizzy got slower to launch".
const scan_start = std.Io.Clock.boot.now(dvui.io).nanoseconds;
var iter = dir.iterate();
while (iter.next(dvui.io) catch null) |entry| {
if (entry.kind != .directory) continue;
const plugin_id = entry.name;
// Skip `.load-tmp` and any other dotfile/directory — not a plugin id.
if (plugin_id.len == 0 or plugin_id[0] == '.') continue;
// User-disabled plugins (store "disable") stay on disk but are not loaded.
if (editor.isPluginDisabled(plugin_id)) {
dvui.log.info("user plugin '{s}' is disabled; skipped", .{plugin_id});
continue;
}
const file_name = PluginLoader.pluginFilename(plugin_id, fizzy.app.allocator) catch continue;
defer fizzy.app.allocator.free(file_name);
const path = std.fs.path.join(fizzy.app.allocator, &.{ plugins_dir, plugin_id, file_name }) catch continue;
if (editor.host.pluginById(plugin_id) != null) {
// A shell built-in (`text`/`workbench`/`image`/`markdown`) is loaded via its own
// static/dylib path (see `postInit` above) and may *also* have its dylib sitting in
// this same shared plugins directory — built-ins compile "the same third-party
// shape" a real third-party plugin would, and `zig build install` drops every
// plugin's dylib here alike (see CLAUDE.md). Rediscovering a built-in's own binary
// here is expected, not a failure: recording it as one would surface the same id
// twice in the settings pane (once as the loaded built-in, once as a "failed" user
// plugin), which collides on the shared heading widget id. Only a genuine third-party
// id clash (some other plugin trying to claim an id a built-in already owns) is
// worth surfacing.
if (isBundledPluginId(plugin_id)) {
dvui.log.info("user plugin '{s}': already loaded as a built-in; skipped", .{plugin_id});
} else {
dvui.log.err("user plugin '{s}': id already registered by a built-in; skipped", .{plugin_id});
const probe = PluginLoader.probeVersionInfo(path);
editor.recordPluginFailure(plugin_id, "id already registered by a built-in plugin", null, if (probe) |info| info.plugin_version else null);
}
fizzy.app.allocator.free(path);
continue;
}
const load_start = std.Io.Clock.boot.now(dvui.io).nanoseconds;
const loaded = PluginLoader.loadAndRegister(&editor.host, fizzy.app.allocator, path, plugin_id, .{
.gpa = &fizzy.app.allocator,
.arg_b = @ptrCast(&editor.host),
.arg_c = null,
}) catch |err| {
const reason = pluginLoadFailureReason(err);
const probe = PluginLoader.probeVersionInfo(path);
const detail_owned: ?[]const u8 = if (probe) |info|
formatPluginProbeDetail(fizzy.app.allocator, info) catch null
else
null;
dvui.log.err("user plugin '{s}' ({s}): load failed: {s} — {s}", .{ plugin_id, path, @errorName(err), reason });
editor.recordPluginFailure(plugin_id, reason, detail_owned, if (probe) |info| info.plugin_version else null);
fizzy.app.allocator.free(path);
continue;
};
appendLoadedPluginLib(editor, loaded) catch {
dvui.log.err("user plugin '{s}': out of memory storing LoadedLib", .{plugin_id});
editor.recordPluginFailure(plugin_id, "ran out of memory while loading", null, loaded.version_info.plugin_version);
continue;
};
dvui.log.info("user plugin '{s}' loaded from {s} in {d}ms", .{
plugin_id,
path,
@divTrunc(std.Io.Clock.boot.now(dvui.io).nanoseconds - load_start, std.time.ns_per_ms),
});
loaded_any = true;
loaded_count += 1;
}
dvui.log.info("loaded {d} user plugin(s) in {d}ms", .{
loaded_count,
@divTrunc(std.Io.Clock.boot.now(dvui.io).nanoseconds - scan_start, std.time.ns_per_ms),
});
if (loaded_any) {
syncLoadedPluginDvuiContexts(editor);
syncLoadedPluginRenderBridge(editor);
}
}
fn unloadPluginLibs(editor: *Editor) void {
if (comptime builtin.target.cpu.arch == .wasm32) return;
for (editor.loaded_plugin_libs.items) |*entry| {
// Deliberately not `entry.lib.close()`: this only runs from `Editor.deinit`, called
// by `AppDeinit` — which the doc comment on `AppDeinit` notes runs *before*
// `dvui.Window.deinit()`. That later call walks dvui's window-level `data_store` and
// invokes each entry's `deinit` function pointer, which for data a plugin stored via
// `dvui.dataSet`/`dataSetSlice` is a comptime-specialized function compiled into that
// plugin's own dylib. Closing the dylib here first and freeing the data store second
// means calling through a function pointer into memory the OS already unmapped —
// caused a reliable segfault on exit whenever a plugin (e.g. widget state for an open
// document) still had a live data-store entry. `PluginLoader.zig`'s `DynLib` doc
// comment already says the handle "must stay open for the app's lifetime"; the process
// exiting reclaims it for free, same tradeoff as the leaked `FileLoadJob`s below.
fizzy.app.allocator.free(entry.plugin_id);
fizzy.app.allocator.free(entry.path);
}
editor.loaded_plugin_libs.deinit(fizzy.app.allocator);
for (editor.failed_user_plugins.items) |f| {
fizzy.app.allocator.free(f.id);
fizzy.app.allocator.free(f.reason);
if (f.detail) |d| fizzy.app.allocator.free(d);
}
editor.failed_user_plugins.deinit(fizzy.app.allocator);