-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.zig
More file actions
876 lines (767 loc) · 36.1 KB
/
Copy pathplugin.zig
File metadata and controls
876 lines (767 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
//! The pixel-art editor plugin: registration + draw entry points. Its contributions
//! reach the plugin's state through the `Globals` injection. Registered from
//! `Editor.postInit`.
const std = @import("std");
const builtin = @import("builtin");
const dvui = @import("dvui");
const icons = @import("icons");
const internal = @import("src/pixi.zig");
const sdk = internal.sdk;
const runtime = @import("src/runtime.zig");
const State = internal.State;
const Packer = internal.Packer;
const CanvasData = @import("src/CanvasData.zig");
const FileWidget = @import("src/widgets/FileWidget.zig");
const ImageWidget = @import("src/widgets/ImageWidget.zig");
const keybind_ticks = @import("src/keybind_ticks.zig");
const radial_menu = @import("src/radial_menu.zig");
const clipboard = @import("src/clipboard.zig");
const pack_project = @import("src/pack_project.zig");
const transform_op = @import("src/transform_op.zig");
const infobar_status = @import("src/infobar_status.zig");
const GridLayout = @import("src/dialogs/GridLayout.zig");
const FlatRasterSaveWarning = @import("src/dialogs/FlatRasterSaveWarning.zig");
const NewFile = @import("src/dialogs/NewFile.zig");
const Export = @import("src/dialogs/Export.zig");
const DocHandle = sdk.DocHandle;
const Internal = internal.internal;
/// Injected at build time from `plugin.zig.zon` — required by fizzy's generated dylib root,
/// which reaches its own copy of this plugin's identity through this export rather than
/// importing `fizzy_plugin_options` itself (see fizzy's `docs/PLUGINS.md` §2.5).
pub const plugin_options = @import("fizzy_plugin_options");
pub const view_tools = "pixi.tools";
pub const view_sprites = "pixi.sprites";
pub const view_project = "pixi.project";
pub const bottom_sprites = "pixi.sprites_panel";
var plugin: sdk.Plugin = .{
.state = undefined,
.vtable = &vtable,
.id = plugin_options.id,
.display_name = plugin_options.name,
};
const vtable: sdk.Plugin.VTable = .{
.deinit = pluginDeinit,
.initPlugin = pluginInit,
.fileTypePriority = fileTypePriority,
.contributeKeybinds = contributeKeybinds,
.loadDocument = loadDocument,
.loadDocumentFromBytes = loadDocumentFromBytes,
.documentStackSize = documentStackSize,
.documentStackAlign = documentStackAlign,
.documentIdFromBuffer = documentIdFromBuffer,
.deinitDocumentBuffer = deinitDocumentBuffer,
.setDocumentGroupingOnBuffer = setDocumentGroupingOnBuffer,
.createDocument = createDocument,
.isDirty = isDirty,
.saveDocument = saveDocument,
.reloadDocument = reloadDocument,
.closeDocument = closeDocument,
.undo = undo,
.redo = redo,
.canUndo = canUndo,
.canRedo = canRedo,
.registerOpenDocument = registerOpenDocument,
.documentPtr = documentPtr,
.documentByPath = documentByPath,
.unregisterDocument = unregisterDocument,
.bindDocumentToPane = bindDocumentToPane,
.documentGrouping = documentGrouping,
.setDocumentGrouping = setDocumentGrouping,
.removeCanvasPane = removeCanvasPane,
.documentPath = documentPath,
.setDocumentPath = setDocumentPath,
.documentHasNativeExtension = documentHasNativeExtension,
.documentHasRecognizedSaveExtension = documentHasRecognizedSaveExtension,
.showsSaveStatusIndicator = showsSaveStatusIndicator,
.isDocumentSaving = isDocumentSaving,
.saveDocumentAsync = saveDocumentAsync,
.timeSinceSaveCompleteNs = timeSinceSaveCompleteNs,
.documentDefaultSaveAsFilename = documentDefaultSaveAsFilename,
.saveDocumentAs = saveDocumentAs,
.resetDocumentSaveUIState = resetDocumentSaveUIState,
.requestNewDocumentDialog = requestNewDocumentDialog,
.drawDocument = drawDocument,
.drawDocumentInfobar = drawDocumentInfobar,
// universal per-frame phases (pixel-art does its raster/canvas work inside them)
.beginFrame = beginFrame,
.prepareFrame = warmupActiveDocumentComposites,
.tickKeybinds = tickKeybinds,
.tickOpenDocuments = tickOpenDocuments,
.tickActiveDocument = tickActiveDocumentPlayback,
.drawOverlay = drawOverlay,
.endFrame = resetDocumentPeekLayers,
.needsContinuousRepaint = isAnyDocumentActivelyDrawing,
// folder lifecycle + save protocol
.onFolderClose = pluginPersistProjectFolder,
.onFolderOpen = pluginReloadProjectFolder,
.saveNeedsConfirmation = shouldConfirmFlatRasterSave,
.requestSaveConfirmation = requestSaveConfirmation,
};
/// A `DocHandle` for one of this plugin's open `*Internal.File`s. Resolved by `doc.id`
/// because `docs.files` may reallocate and stale `doc.ptr` values.
fn docFile(doc: DocHandle) *Internal.File {
return runtime.state().docs.fileById(doc.id).?;
}
/// Priority for opening `ext` (lower wins). pixi owns its native `.pixi`/`.fiz`
/// and flat-image `.png`/`.jpg`/`.jpeg`; native formats win over flat images when
/// some future plugin also claims an image type.
fn fileTypePriority(_: *anyopaque, ext: []const u8) ?u8 {
if (Internal.File.isFizzyExtension(ext)) return 0;
if (Internal.File.isFlatImageExtension(ext)) return 90;
return null;
}
/// Natural size reported for an atlas sprite icon, as a multiple of its native pixel size.
///
/// With `expand = .ratio` (see `host_slot_fit`) this no longer decides how big the icon *renders*
/// — the host's slot does that, and a ratio fit is invariant under a uniform scale of the
/// requested size. It only sets the min size reported upward for hosts that lay out around it.
const file_icon_sprite_scale: f32 = 2.0;
/// Fill the slot the host reserved for us.
///
/// The shell reserves a fixed rect per tree row (`core.dvui.treeRowGlyph`) and every icon —
/// vector, sprite, or letter — is expected to fit itself into it with `expand = .ratio`. Drawing
/// at a size of our own choosing instead makes pixi's rows taller than everyone else's and knocks
/// the labels out of alignment, which is exactly what the hard-coded scales below used to do.
const host_slot_fit: dvui.Options = .{
.expand = .ratio,
.gravity_x = 0.5,
.gravity_y = 0.5,
.padding = dvui.Rect.all(0),
.margin = dvui.Rect.all(0),
};
/// Draw the file-tree icon for the file types pixi owns: its own `ui_atlas` sprites for
/// `.fiz` (the `fiz` animation in `assets/src/misc.pixi`) and `.pixi` (the `pixi` animation),
/// plus a generic vector icon for flat images. Returns false for anything else so the workbench
/// falls back to a generic icon.
fn drawFileIcon(_: ?*anyopaque, ext: []const u8, _: []const u8, color: dvui.Color) bool {
const ui_atlas = runtime.uiAtlas();
if (std.mem.eql(u8, ext, ".fiz")) {
_ = ui_atlas.sprites[internal.atlas.sprites.fiz_default].draw(@src(), ui_atlas.source, file_icon_sprite_scale, host_slot_fit);
return true;
}
if (std.mem.eql(u8, ext, ".pixi")) {
_ = ui_atlas.sprites[internal.atlas.sprites.pixi_default].draw(@src(), ui_atlas.source, file_icon_sprite_scale, host_slot_fit);
return true;
}
if (Internal.File.isFlatImageExtension(ext)) {
dvui.icon(@src(), "PixiFileIcon", dvui.entypo.image, .{ .stroke_color = color, .fill_color = color }, host_slot_fit.override(.{ .background = false }));
return true;
}
return false;
}
fn drawPluginIcon(_: ?*anyopaque) void {
const ui_atlas = runtime.uiAtlas();
_ = ui_atlas.sprites[internal.atlas.sprites.pixi_default].draw(@src(), ui_atlas.source, file_icon_sprite_scale, host_slot_fit);
}
/// Load `path` into the plugin-owned `*Internal.File` at `out_doc`. Runs on the shell's
/// load worker thread; `File.fromPath` is the pixel-art loader.
fn loadDocument(_: *anyopaque, path: []const u8, out_doc: *anyopaque) anyerror!void {
// Web loads via bytes only (`loadDocumentFromBytes`); the comptime guard keeps the
// disk-reading `File.fromPath` path (Dir.cwd / posix.AT) out of the wasm binary.
if (comptime builtin.target.cpu.arch == .wasm32) return error.Unsupported;
const file = try Internal.File.fromPath(path) orelse return error.InvalidFile;
@as(*Internal.File, @ptrCast(@alignCast(out_doc))).* = file;
}
/// As `loadDocument`, from in-memory bytes (browser file picker; synchronous).
fn loadDocumentFromBytes(_: *anyopaque, path: []const u8, bytes: []const u8, out_doc: *anyopaque) anyerror!void {
const file = try Internal.File.fromBytes(path, bytes) orelse return error.InvalidFile;
@as(*Internal.File, @ptrCast(@alignCast(out_doc))).* = file;
}
fn isDirty(_: *anyopaque, doc: DocHandle) bool {
return docFile(doc).dirty();
}
/// Persist the document. The shell handles the Save-As / flat-raster / web-download
/// policy before routing here; this just runs the pixel-art async save.
fn saveDocument(_: *anyopaque, doc: DocHandle) anyerror!void {
try docFile(doc).saveAsync();
}
/// Reload from disk when the shell's document watcher sees an external change on a
/// clean tab (or the user picks Discard in the on-disk conflict dialog).
fn reloadDocument(_: *anyopaque, doc: DocHandle) anyerror!void {
try docFile(doc).reloadFromDisk();
}
/// Release the document's resources. The shell removes it from `open_files` and
/// fixes up the active-tab index; this just frees the pixel-art `File`.
fn closeDocument(_: *anyopaque, doc: DocHandle) void {
docFile(doc).deinit();
}
/// Render the open pixel-art document into the workbench-provided content region (the
/// current dvui parent). The workbench owns only the container + tab/split frame and sets
/// `canvas.id` / `workspace_handle` / `center` before routing here; pixi owns the
/// entire region: rulers, the canvas hbox, the transform/edit/sample overlays, the editing
/// widget, and the sample magnifier. The per-pane ruler/overlay/reorder state + draw helpers
/// live on the pixel-art-owned `CanvasData` (keyed by workbench pane `grouping` on `State`).
fn drawDocument(_: *anyopaque, doc: DocHandle) anyerror!void {
const file = docFile(doc);
const canvas = CanvasData.forGrouping(file.editor.grouping);
const container = dvui.parentGet().data();
// Grid (column/row) reorder is driven by the rulers and consumed by `FileWidget`; commit
// the pending reorder and clear the per-frame drag indices after the whole document (incl.
// the file widget) has drawn. Registered first so they run last.
defer canvas.columns_drag_index = null;
defer canvas.rows_drag_index = null;
defer canvas.processColumnReorder(file);
defer canvas.processRowReorder(file);
internal.perf.canvasPaneDrawn();
if (runtime.state().settings.show_rulers.get() and !dvui.firstFrame(container.id)) {
defer internal.core.dvui.drawEdgeShadow(container.rectScale(), .top, .{});
canvas.drawRuler(file, .horizontal);
}
var canvas_hbox = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .both });
defer canvas_hbox.deinit();
if (runtime.state().settings.show_rulers.get() and !dvui.firstFrame(container.id)) {
defer internal.core.dvui.drawEdgeShadow(container.rectScale(), .left, .{});
canvas.drawRuler(file, .vertical);
}
canvas.drawTransformDialog(file, container);
canvas.drawEditPill(container);
// Before the file widget so FloatingWidget uses window-scale coords (not canvas zoom).
canvas.drawSampleButton(container);
const pane_grouping = container.options.id_extra orelse return;
if (@as(u64, @intCast(pane_grouping)) != file.editor.grouping) return;
var file_widget = FileWidget.init(@src(), .{
.file = file,
.center = file.editor.center,
}, .{
.expand = .both,
.background = false,
.color_fill = .transparent,
});
defer file_widget.deinit();
file_widget.processEvents();
if (dvui.dataGet(null, file.editor.canvas.id, "sample_data_point", dvui.Point)) |data_pt| {
if (file.editor.canvas.samplePointerInViewport(dvui.currentWindow().mouse_pt)) {
FileWidget.drawSampleMagnifier(file, data_pt);
}
}
}
/// Take over a workspace pane to show the pixel-art packed-atlas preview (the "Project"
/// sidebar view's `draw_workspace`). The workbench owns the pane frame and routes here when
/// `view_project` is the active sidebar view.
fn drawProjectView(_: ?*anyopaque, pane: *sdk.WorkbenchPaneView) anyerror!void {
var content_color = dvui.themeGet().color(.window, .fill);
if (runtime.state().host.appliesNativeWindowOpacity()) {
content_color = if (!runtime.state().host.isMaximized())
content_color.opacity(runtime.state().host.contentOpacity())
else
content_color;
}
const show_packed_atlas = if (comptime builtin.target.cpu.arch == .wasm32)
runtime.packer().atlas != null
else
runtime.state().host.folder() != null and runtime.packer().atlas != null;
var canvas_vbox = sdk.pane_layout.mainCanvasVbox(content_color, show_packed_atlas, pane.grouping);
defer {
pane.canvas_rect_physical.* = canvas_vbox.data().contentRectScale().r;
dvui.toastsShow(canvas_vbox.data().id, canvas_vbox.data().contentRectScale().r.toNatural());
canvas_vbox.deinit();
}
if (show_packed_atlas) {
const atlas = &runtime.packer().atlas.?;
var image_widget = ImageWidget.init(@src(), .{
.source = atlas.source,
.canvas = &atlas.canvas,
.grouping = pane.grouping,
}, .{
.id_extra = @intCast(pane.grouping),
.expand = .both,
.background = false,
.color_fill = .transparent,
});
defer image_widget.deinit();
image_widget.processEvents();
if (dvui.dataGet(null, atlas.canvas.id, "sample_data_point", dvui.Point)) |data_pt| {
if (atlas.canvas.samplePointerInViewport(dvui.currentWindow().mouse_pt)) {
ImageWidget.drawSampleMagnifier(&atlas.canvas, atlas.source, data_pt);
}
}
} else {
var box = sdk.pane_layout.emptyStateCard(content_color, pane.grouping);
defer box.deinit();
const alpha = dvui.alpha(1.0);
dvui.alphaSet(1.0);
defer dvui.alphaSet(alpha);
const hint: []const u8 = if (comptime builtin.target.cpu.arch == .wasm32)
"Pack open files to see the preview."
else if (runtime.state().host.folder() == null)
"Open a project folder, then pack to see the preview."
else
"Pack the project to see the preview.";
dvui.labelNoFmt(
@src(),
hint,
.{ .align_x = 0.5 },
.{
.gravity_x = 0.5,
.gravity_y = 0.5,
.color_text = dvui.themeGet().color(.control, .text),
.font = dvui.Font.theme(.body),
},
);
}
}
fn drawDocumentInfobar(state: *anyopaque, doc: DocHandle, rect: dvui.Rect) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
return infobar_status.drawDocumentInfobar(st, doc, rect);
}
fn undo(_: *anyopaque, doc: DocHandle) anyerror!void {
const file = docFile(doc);
try file.history.undoRedo(file, .undo);
}
fn redo(_: *anyopaque, doc: DocHandle) anyerror!void {
const file = docFile(doc);
try file.history.undoRedo(file, .redo);
}
fn canUndo(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.canUndo(doc);
}
fn canRedo(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.canRedo(doc);
}
/// Pixi owns its own runtime state + atlas packer (like any third-party plugin) instead of the
/// shell allocating them. They live as plugin-image statics, created in `register` and torn down
/// in `pluginDeinit`.
var plugin_state: State = undefined;
var packer_state: Packer = undefined;
pub fn register(host: *sdk.Host) !void {
plugin_state = try State.init(sdk.allocator(), host);
packer_state = try Packer.init(sdk.allocator());
plugin_state.packer = &packer_state;
runtime.adoptState(&plugin_state);
plugin.state = @ptrCast(&plugin_state);
try host.registerPlugin(&plugin);
try host.registerFileRowFillColor(.{ .owner = &plugin, .color = &fileRowFillColor });
try host.registerFileIcon(.{ .owner = &plugin, .draw = drawFileIcon });
try host.registerPluginIcon(.{ .owner = &plugin, .draw = drawPluginIcon });
try host.registerSidebarView(.{
.id = view_tools,
.owner = &plugin,
.icon = dvui.entypo.pencil,
.title = "Tools",
.draw = drawTools,
});
try host.registerSidebarView(.{
.id = view_sprites,
.owner = &plugin,
.icon = dvui.entypo.grid,
.title = "Sprites",
.draw = drawSprites,
});
try host.registerSidebarView(.{
.id = view_project,
.owner = &plugin,
.icon = dvui.entypo.box,
.title = "Project",
.draw = drawProject,
.draw_workspace = drawProjectView,
});
try host.registerBottomView(.{
.id = bottom_sprites,
.owner = &plugin,
.title = "Sprites",
.draw = drawSpritesPanel,
.persistent = true,
});
try plugin_state.registerSettings(host, &plugin);
// Pixel-art's invocable, plugin-specific features. The shell/menus/keybinds trigger these
// by id via `host.runCommand` without naming them. (Generic active-doc editing verbs like
// `transform`/`copy`/`paste` are *not* commands — they are `Plugin.VTable` hooks the shell
// dispatches to the focused document's owner.)
try host.registerCommand(.{
.id = "pixi.gridLayout",
.owner = &plugin,
.title = "Grid Layout…",
.run = gridLayoutCommand,
.isEnabled = editActionEnabled,
.icon = icons.tvg.lucide.@"grid-3x3",
});
// Dispatched by the shell keymap (owner-scoped `mod+p`) — not by `tickKeybinds`, so it
// no longer races Quick Open / the command palette on the same chord.
try host.registerCommand(.{
.id = "pixi.export",
.owner = &plugin,
.title = "Export…",
.run = exportCommand,
.isEnabled = exportEnabled,
});
try host.registerCommand(.{
.id = "pixi.packProject",
.owner = &plugin,
.title = "Pack Project",
.run = packProjectCommand,
.isEnabled = packProjectEnabled,
});
// Editing verbs the shell's Edit menu / keybinds dispatch to per active-doc owner
// (`<owner_id>.<action>`, i.e. `pixi.<action>` since `plugin.id == "pixi"`). These are
// pixel-art's answers; another editor registers its own under its own id.
try host.registerCommand(.{ .id = "pixi.copy", .owner = &plugin, .title = "Copy", .run = pluginCopy, .icon = icons.tvg.lucide.copy });
try host.registerCommand(.{ .id = "pixi.paste", .owner = &plugin, .title = "Paste", .run = pluginPaste, .icon = icons.tvg.lucide.@"clipboard-paste" });
try host.registerCommand(.{ .id = "pixi.transform", .owner = &plugin, .title = "Transform", .run = pluginTransform, .isEnabled = editActionEnabled, .icon = icons.tvg.lucide.move });
try host.registerCommand(.{ .id = "pixi.acceptEdit", .owner = &plugin, .title = "Accept Edit", .run = pluginAcceptEdit });
try host.registerCommand(.{ .id = "pixi.cancelEdit", .owner = &plugin, .title = "Cancel Edit", .run = pluginCancelEdit });
try host.registerCommand(.{ .id = "pixi.deleteSelection", .owner = &plugin, .title = "Delete Selection", .run = pluginDeleteSelection });
// Transform / Grid Layout are pixel-art-only concepts — the shell's Edit menu has no
// knowledge of them. Inject both directly into the shell's existing "Edit" menu (in-app +
// native), only doing anything while the focused document is one of ours.
try host.registerMenuSection(.{
.id = "pixi.menu.edit_section",
.parent_menu_id = "fizzy.menu.edit",
.owner = &plugin,
.draw = drawEditMenuSection,
});
// Naming the command on each native item is what puts its chord on the macOS menu, and keeps
// it there across a rebind; `run` is still the click path.
try host.registerNativeMenuItem(.{
.id = "pixi.native.transform",
.owner = &plugin,
.parent_menu_id = "fizzy.menu.edit",
.title = "Transform",
.command = "pixi.transform",
.sf_symbol = "arrow.up.left.and.down.right.magnifyingglass",
.run = nativeTransform,
});
try host.registerNativeMenuItem(.{
.id = "pixi.native.gridLayout",
.owner = &plugin,
.parent_menu_id = "fizzy.menu.edit",
.title = "Grid Layout…",
.command = "pixi.gridLayout",
.sf_symbol = "square.grid.3x3",
.run = nativeGridLayout,
});
}
/// Whether the shell's active document belongs to this plugin — Transform/Grid Layout only
/// mean anything for a pixi document, so both entry points below no-op otherwise.
fn activeDocIsOurs() bool {
const doc = runtime.state().host.activeDoc() orelse return false;
return doc.owner == &plugin;
}
/// `Command.isEnabled` for `pixi.transform`/`pixi.gridLayout`. Naming this on the command (rather
/// than each call site re-deriving it) is what lets both the in-app dvui menu row
/// (`Host.drawMenuItem`, via `Host.commandEnabled`) and the native macOS row
/// (`FizzyNativeMenuGenericActionEnabled`, via the same lookup) grey themselves out for a
/// non-pixi document without either side special-casing pixi.
fn editActionEnabled(_: *anyopaque) bool {
return activeDocIsOurs();
}
/// In-app "Edit" menu section (see `Host.registerMenuSection`). Always drawn — greying for a
/// non-pixi document comes from `editActionEnabled` above via `Host.drawMenuItem`, not from an
/// early return here. An early return used to make both rows disappear entirely from this menu
/// while the *native* macOS one (a static bar with no per-row enabled hook of its own) kept
/// showing them regardless, so the two disagreed on every non-pixi document.
///
/// Both rows go through `Host.drawMenuItem`, naming the command each one runs: the shell draws
/// that command's current chord as the accelerator, so rebinding Transform / Grid Layout in the
/// Keyboard Shortcuts pane updates the menu. The hand-rolled row this replaced looked the chord
/// up by dvui *bind name* (`"transform"`, `"grid_layout"`) — names these commands have no entry
/// under — so it always drew a blank accelerator, and it built dvui menu widgets inside the
/// plugin dylib, which `EditorAPI.VTable.drawMenuItem`'s doc comment spells out is unsafe.
fn drawEditMenuSection(_: ?*anyopaque) anyerror!void {
if (runtime.state().host.drawMenuItem("Transform", "pixi.transform")) {
runtime.state().host.runCommand("pixi.transform") catch |err| {
dvui.log.err("Transform command failed: {s}", .{@errorName(err)});
};
}
if (runtime.state().host.drawMenuItem("Grid Layout…", "pixi.gridLayout")) {
runtime.state().host.runCommand("pixi.gridLayout") catch |err| {
dvui.log.err("Grid layout command failed: {s}", .{@errorName(err)});
};
}
}
/// AppKit now greys these two rows for a non-pixi document too (`FizzyNativeMenuGenericActionEnabled`
/// reads `editActionEnabled` off the named command, same as the in-app menu), so this guard
/// shouldn't fire in the ordinary click path anymore — kept as a backstop against any other way
/// `run` could be reached (e.g. a future direct dispatch that skips menu validation).
fn nativeTransform(_: ?*anyopaque) anyerror!void {
if (!activeDocIsOurs()) return;
try runtime.state().host.runCommand("pixi.transform");
}
fn nativeGridLayout(_: ?*anyopaque) anyerror!void {
if (!activeDocIsOurs()) return;
try runtime.state().host.runCommand("pixi.gridLayout");
}
/// Stable `*Plugin` for constructing `DocHandle.owner` fields.
pub fn pluginPtr() *sdk.Plugin {
return &plugin;
}
fn fileRowFillColor(_: ?*anyopaque, color_index: usize) ?dvui.Color {
if (runtime.state().colors.palette) |*palette| {
return palette.getDVUIColor(color_index);
}
return null;
}
fn drawTools(_: ?*anyopaque) anyerror!void {
try runtime.state().tools_pane.draw();
}
fn drawSprites(_: ?*anyopaque) anyerror!void {
try runtime.state().sprites_pane.draw();
}
fn drawProject(_: ?*anyopaque) anyerror!void {
try internal.explorer.project.draw();
}
fn drawSpritesPanel(_: ?*anyopaque) anyerror!void {
try runtime.state().sprites_panel.draw();
}
fn tickKeybinds(_: *anyopaque) anyerror!void {
try keybind_ticks.tick();
}
/// Pixel-art's per-frame overlay: the radial tool menu (processes its hold-to-open input,
/// then draws while visible). Wired to the universal `Plugin.drawOverlay` phase.
fn drawOverlay(_: *anyopaque) anyerror!void {
radial_menu.processHoldOpenInput();
if (radial_menu.visible()) try radial_menu.draw();
}
fn pluginCopy(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
try clipboard.copy(st);
}
fn pluginTransform(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
try transform_op.begin(st);
}
fn registerOpenDocument(state: *anyopaque, file: *anyopaque) anyerror!*anyopaque {
const st: *State = @ptrCast(@alignCast(state));
const internal_file: *Internal.File = @ptrCast(@alignCast(file));
const ptr = try st.registerOpenDocument(internal_file);
return ptr;
}
fn documentPtr(state: *anyopaque, id: u64) ?*anyopaque {
const st: *State = @ptrCast(@alignCast(state));
return st.documentFromId(id);
}
fn documentByPath(state: *anyopaque, path: []const u8) ?*anyopaque {
const st: *State = @ptrCast(@alignCast(state));
return st.documentFromPath(path);
}
fn unregisterDocument(state: *anyopaque, id: u64) void {
const st: *State = @ptrCast(@alignCast(state));
st.unregisterDocument(id);
}
fn bindDocumentToPane(state: *anyopaque, doc: DocHandle, canvas_id: dvui.Id, workspace_handle: *anyopaque, center: bool) void {
const st: *State = @ptrCast(@alignCast(state));
st.bindDocumentToWorkspace(doc, canvas_id, workspace_handle, center);
}
fn documentGrouping(state: *anyopaque, doc: DocHandle) u64 {
const st: *State = @ptrCast(@alignCast(state));
return st.documentGrouping(doc);
}
fn setDocumentGrouping(state: *anyopaque, doc: DocHandle, grouping: u64) void {
const st: *State = @ptrCast(@alignCast(state));
st.setDocumentGrouping(doc, grouping);
}
fn removeCanvasPane(state: *anyopaque, grouping: u64, allocator: std.mem.Allocator) void {
const st: *State = @ptrCast(@alignCast(state));
State.removeCanvasPane(st, allocator, grouping);
}
fn documentPath(state: *anyopaque, doc: DocHandle) []const u8 {
const st: *State = @ptrCast(@alignCast(state));
return st.documentPath(doc);
}
fn setDocumentPath(state: *anyopaque, doc: DocHandle, path: []const u8) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
return st.setDocumentPath(doc, path);
}
fn documentHasNativeExtension(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.documentHasNativeExtension(doc);
}
fn documentHasRecognizedSaveExtension(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.documentHasRecognizedSaveExtension(doc);
}
fn showsSaveStatusIndicator(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.showsSaveStatusIndicator(doc);
}
fn isDocumentSaving(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.isDocumentSaving(doc);
}
fn shouldConfirmFlatRasterSave(state: *anyopaque, doc: DocHandle) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.shouldConfirmFlatRasterSave(doc);
}
fn saveDocumentAsync(state: *anyopaque, doc: DocHandle) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
return st.saveDocumentAsync(doc);
}
fn timeSinceSaveCompleteNs(state: *anyopaque, doc: DocHandle) ?i128 {
const st: *State = @ptrCast(@alignCast(state));
return st.timeSinceSaveCompleteNs(doc);
}
fn pluginDeinit(state: *anyopaque) void {
const st: *State = @ptrCast(@alignCast(state));
const gpa = sdk.allocator();
State.persistProject(st); // save the open project before teardown (covers the quit path)
st.deinitPlugin();
if (st.packer) |p| p.deinit();
st.deinit(gpa);
}
fn pluginInit(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
return st.initPlugin();
}
fn documentStackSize(state: *anyopaque) usize {
const st: *State = @ptrCast(@alignCast(state));
return st.sizeOfDocument();
}
fn documentStackAlign(state: *anyopaque) usize {
const st: *State = @ptrCast(@alignCast(state));
return st.alignOfDocument();
}
fn documentIdFromBuffer(state: *anyopaque, doc: *anyopaque) u64 {
const st: *State = @ptrCast(@alignCast(state));
return st.documentIdFromBuffer(doc);
}
fn deinitDocumentBuffer(state: *anyopaque, doc: *anyopaque) void {
const st: *State = @ptrCast(@alignCast(state));
st.deinitDocumentBuffer(doc);
}
fn setDocumentGroupingOnBuffer(state: *anyopaque, doc: *anyopaque, grouping: u64) void {
const st: *State = @ptrCast(@alignCast(state));
st.setDocumentGroupingOnBuffer(doc, grouping);
}
fn createDocument(state: *anyopaque, path: []const u8, grid: sdk.EditorAPI.NewDocGrid, out_doc: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
return st.createDocument(path, grid, out_doc);
}
fn documentDefaultSaveAsFilename(state: *anyopaque, doc: DocHandle, allocator: std.mem.Allocator) anyerror![]const u8 {
const st: *State = @ptrCast(@alignCast(state));
return st.documentDefaultSaveAsFilename(doc, allocator);
}
fn saveDocumentAs(state: *anyopaque, doc: DocHandle, path: []const u8, window: *dvui.Window) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
return st.saveDocumentAs(doc, path, window);
}
fn resetDocumentSaveUIState(state: *anyopaque, doc: DocHandle) void {
const st: *State = @ptrCast(@alignCast(state));
st.resetDocumentSaveUIState(doc);
}
fn requestNewDocumentDialog(_: *anyopaque, parent_path: ?[]const u8, id_extra: usize) void {
NewFile.request(parent_path, id_extra);
}
/// Command body for `pixi.gridLayout` — opens the grid-layout dialog for the active doc.
fn gridLayoutCommand(_: *anyopaque) anyerror!void {
const doc = runtime.state().host.activeDoc() orelse return;
GridLayout.request(doc.id);
}
fn exportEnabled(_: *anyopaque) bool {
return activeDocIsOurs();
}
fn exportCommand(_: *anyopaque) anyerror!void {
if (!activeDocIsOurs()) return;
var mutex = internal.core.dvui.dialog(@src(), .{
.displayFn = Export.dialog,
.callafterFn = Export.callAfter,
.title = "Export...",
.ok_label = "Export",
.cancel_label = "Cancel",
.resizeable = false,
.modal = false,
.header_kind = .info,
.default = .ok,
});
mutex.mutex.unlock(dvui.io);
}
fn requestSaveConfirmation(_: *anyopaque, doc: DocHandle, mode: sdk.Plugin.SaveConfirmMode, from_save_all_quit: bool) void {
FlatRasterSaveWarning.request(doc.id, mode, from_save_all_quit);
}
fn beginFrame(state: *anyopaque) void {
const st: *State = @ptrCast(@alignCast(state));
// Advance the per-frame render clock used as a composite-cache invalidation key.
internal.render.frame_index +%= 1;
// Sweep any in-flight atlas-pack jobs. The shell no longer orchestrates packing — the
// plugin drives its own background work from this universal per-frame phase.
pack_project.tick(st);
if (comptime @import("builtin").target.cpu.arch == .wasm32) pack_project.runWasmWorkers(st);
}
/// Command body for `pixi.packProject`.
fn packProjectCommand(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
try pack_project.start(st);
}
/// `pixi.packProject` is enabled only when no pack is already in flight.
fn packProjectEnabled(state: *anyopaque) bool {
const st: *State = @ptrCast(@alignCast(state));
return !pack_project.isActive(st);
}
fn tickOpenDocuments(state: *anyopaque) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.tickOpenDocuments();
}
fn tickActiveDocumentPlayback(state: *anyopaque, timer_host_id: dvui.Id) void {
const st: *State = @ptrCast(@alignCast(state));
st.tickActiveDocumentPlayback(timer_host_id);
}
fn resetDocumentPeekLayers(state: *anyopaque) void {
const st: *State = @ptrCast(@alignCast(state));
st.resetDocumentPeekLayers();
}
fn warmupActiveDocumentComposites(state: *anyopaque) void {
const st: *State = @ptrCast(@alignCast(state));
st.warmupActiveDocumentComposites();
}
fn isAnyDocumentActivelyDrawing(state: *anyopaque) bool {
const st: *State = @ptrCast(@alignCast(state));
return st.isAnyDocumentActivelyDrawing();
}
// Editing-verb command bodies (registered in `register`). `anyerror!void` to match `Command.run`.
fn pluginAcceptEdit(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
st.acceptEdit();
}
fn pluginCancelEdit(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
st.cancelEdit();
}
fn pluginDeleteSelection(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
st.deleteSelection();
}
fn pluginPersistProjectFolder(state: *anyopaque) void {
const st: *State = @ptrCast(@alignCast(state));
st.persistProject();
}
fn pluginReloadProjectFolder(state: *anyopaque, allocator: std.mem.Allocator) void {
const st: *State = @ptrCast(@alignCast(state));
st.reloadProjectForFolder(allocator);
}
fn pluginPaste(state: *anyopaque) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
try clipboard.paste(st);
}
/// Pixel-art editing + tool keybinds.
/// binds in `Keybinds.register`; this fills in the pixel-art half. Platform: see
/// `Keybinds.register` for why `host.isMacOS()` (not `builtin`) is used.
fn contributeKeybinds(state: *anyopaque, win: *dvui.Window) anyerror!void {
const st: *State = @ptrCast(@alignCast(state));
if (st.host.isMacOS()) {
try win.keybinds.putNoClobber(win.gpa, "undo", .{ .key = .z, .command = true, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "redo", .{ .key = .z, .command = true, .shift = true });
try win.keybinds.putNoClobber(win.gpa, "sample", .{ .control = true });
try win.keybinds.putNoClobber(win.gpa, "transform", .{ .command = true, .key = .t });
try win.keybinds.putNoClobber(win.gpa, "grid_layout", .{ .command = true, .key = .g });
// shift=false so this never matches Cmd+Shift+P (command palette). Dispatch of Export
// itself goes through the shell keymap (`pixi.export`); this entry is only for menu hints.
try win.keybinds.putNoClobber(win.gpa, "export", .{ .command = true, .key = .p, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "delete_selection_contents", .{ .key = .backspace });
} else {
try win.keybinds.putNoClobber(win.gpa, "undo", .{ .key = .z, .control = true, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "redo", .{ .key = .z, .control = true, .shift = true });
try win.keybinds.putNoClobber(win.gpa, "sample", .{ .alt = true });
try win.keybinds.putNoClobber(win.gpa, "transform", .{ .control = true, .key = .t });
try win.keybinds.putNoClobber(win.gpa, "grid_layout", .{ .control = true, .key = .g });
try win.keybinds.putNoClobber(win.gpa, "export", .{ .control = true, .key = .p, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "delete_selection_contents", .{ .key = .delete });
}
try win.keybinds.putNoClobber(win.gpa, "increase_stroke_size", .{ .key = .right_bracket });
try win.keybinds.putNoClobber(win.gpa, "decrease_stroke_size", .{ .key = .left_bracket });
try win.keybinds.putNoClobber(win.gpa, "quick_tools", .{ .key = .space });
try win.keybinds.putNoClobber(win.gpa, "pencil", .{ .key = .d, .command = false, .control = false, .alt = false, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "eraser", .{ .key = .e, .command = false, .control = false, .alt = false, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "bucket", .{ .key = .b, .command = false, .control = false, .alt = false, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "selection", .{ .key = .s, .command = false, .control = false, .alt = false, .shift = false });
try win.keybinds.putNoClobber(win.gpa, "pointer", .{ .key = .escape });
}