aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/libghostty-vt/src/input/key_mods.zig
blob: 1a9814037c39f3c7473decad210bb9e103cc2cd7 (plain) (blame)
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
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const OptionAsAlt = @import("config.zig").OptionAsAlt;

/// Aliases for modifier names.
pub const alias: []const struct { []const u8, Mod } = &.{
    .{ "cmd", .super },
    .{ "command", .super },
    .{ "opt", .alt },
    .{ "option", .alt },
    .{ "control", .ctrl },
};

/// Single modifier
pub const Mod = enum {
    shift,
    ctrl,
    alt,
    super,

    pub const Side = enum(u1) { left, right };
};

/// A bitmask for all key modifiers.
///
/// IMPORTANT: Any changes here update include/ghostty.h
pub const Mods = packed struct(Mods.Backing) {
    pub const Backing = u16;

    shift: bool = false,
    ctrl: bool = false,
    alt: bool = false,
    super: bool = false,
    caps_lock: bool = false,
    num_lock: bool = false,
    sides: Side = .{},
    _padding: u6 = 0,

    /// The standard modifier keys only. Does not include the lock keys,
    /// only standard bindable keys.
    pub const Keys = packed struct(u4) {
        shift: bool = false,
        ctrl: bool = false,
        alt: bool = false,
        super: bool = false,

        pub const Backing = @typeInfo(Keys).@"struct".backing_integer.?;

        pub inline fn int(self: Keys) Keys.Backing {
            return @bitCast(self);
        }
    };

    /// Tracks the side that is active for any given modifier. Note
    /// that this doesn't confirm a modifier is pressed; you must check
    /// the bool for that in addition to this.
    ///
    /// Not all platforms support this, check apprt for more info.
    pub const Side = packed struct(u4) {
        shift: Mod.Side = .left,
        ctrl: Mod.Side = .left,
        alt: Mod.Side = .left,
        super: Mod.Side = .left,

        pub const Backing = @typeInfo(Side).@"struct".backing_integer.?;
    };

    /// The mask that has all the side bits set.
    pub const side_mask: Mods = .{
        .sides = .{
            .shift = .right,
            .ctrl = .right,
            .alt = .right,
            .super = .right,
        },
    };

    /// Integer value of this struct.
    pub fn int(self: Mods) Backing {
        return @bitCast(self);
    }

    /// Returns true if no modifiers are set.
    pub fn empty(self: Mods) bool {
        return self.int() == 0;
    }

    /// Returns true if two mods are equal.
    pub fn equal(self: Mods, other: Mods) bool {
        return self.int() == other.int();
    }

    /// Returns only the keys.
    ///
    /// In the future I want to remove `binding` for this. I didn't want
    /// to do that all in one PR where I added this because its a bigger
    /// change.
    pub fn keys(self: Mods) Keys {
        const backing: Keys.Backing = @truncate(self.int());
        return @bitCast(backing);
    }

    /// Return mods that are only relevant for bindings.
    pub fn binding(self: Mods) Mods {
        return .{
            .shift = self.shift,
            .ctrl = self.ctrl,
            .alt = self.alt,
            .super = self.super,
        };
    }

    /// Perform `self &~ other` to remove the other mods from self.
    pub fn unset(self: Mods, other: Mods) Mods {
        return @bitCast(self.int() & ~other.int());
    }

    /// Returns the mods without locks set.
    pub fn withoutLocks(self: Mods) Mods {
        var copy = self;
        copy.caps_lock = false;
        copy.num_lock = false;
        return copy;
    }

    /// Return the mods to use for key translation. This handles settings
    /// like macos-option-as-alt. The translation mods should be used for
    /// translation but never sent back in for the key callback.
    pub fn translation(self: Mods, option_as_alt: OptionAsAlt) Mods {
        var result = self;

        // macos-option-as-alt for darwin
        if (comptime builtin.target.os.tag.isDarwin()) alt: {
            // Alt has to be set only on the correct side
            switch (option_as_alt) {
                .false => break :alt,
                .true => {},
                .left => if (self.sides.alt == .right) break :alt,
                .right => if (self.sides.alt == .left) break :alt,
            }

            // Unset alt
            result.alt = false;
        }

        return result;
    }

    /// Checks to see if super is on (MacOS) or ctrl.
    pub fn ctrlOrSuper(self: Mods) bool {
        if (comptime builtin.target.os.tag.isDarwin()) {
            return self.super;
        }
        return self.ctrl;
    }

    // For our own understanding
    test {
        const testing = std.testing;
        try testing.expectEqual(@as(Backing, @bitCast(Mods{})), @as(Backing, 0b0));
        try testing.expectEqual(
            @as(Backing, @bitCast(Mods{ .shift = true })),
            @as(Backing, 0b0000_0001),
        );
    }

    test "translation macos-option-as-alt" {
        if (comptime !builtin.target.os.tag.isDarwin()) return error.SkipZigTest;

        const testing = std.testing;

        // Unset
        {
            const mods: Mods = .{};
            const result = mods.translation(.true);
            try testing.expectEqual(result, mods);
        }

        // Set
        {
            const mods: Mods = .{ .alt = true };
            const result = mods.translation(.true);
            try testing.expectEqual(Mods{}, result);
        }

        // Set but disabled
        {
            const mods: Mods = .{ .alt = true };
            const result = mods.translation(.false);
            try testing.expectEqual(result, mods);
        }

        // Set wrong side
        {
            const mods: Mods = .{ .alt = true, .sides = .{ .alt = .right } };
            const result = mods.translation(.left);
            try testing.expectEqual(result, mods);
        }
        {
            const mods: Mods = .{ .alt = true, .sides = .{ .alt = .left } };
            const result = mods.translation(.right);
            try testing.expectEqual(result, mods);
        }

        // Set with other mods
        {
            const mods: Mods = .{ .alt = true, .shift = true };
            const result = mods.translation(.true);
            try testing.expectEqual(Mods{ .shift = true }, result);
        }
    }
};

/// Modifier remapping. See `key-remap` in Config.zig for detailed docs.
pub const RemapSet = struct {
    /// Available mappings.
    map: std.AutoArrayHashMapUnmanaged(Mods, Mods),

    /// The mask of remapped modifiers that can be used to quickly
    /// check if some input mods need remapping.
    mask: Mask,

    pub const empty: RemapSet = .{
        .map = .{},
        .mask = .{},
    };

    pub const ParseError = Allocator.Error || error{
        MissingAssignment,
        InvalidMod,
    };

    /// Parse from CLI input. Required by Config.
    pub fn parseCLI(self: *RemapSet, alloc: Allocator, input: ?[]const u8) !void {
        const value = input orelse "";

        // Empty value resets the set
        if (value.len == 0) {
            self.map.clearRetainingCapacity();
            self.mask = .{};
            return;
        }

        self.parse(alloc, value) catch |err| switch (err) {
            error.OutOfMemory => return error.OutOfMemory,
            error.MissingAssignment, error.InvalidMod => return error.InvalidValue,
        };
    }

    /// Parse a modifier remap and add it to the set.
    pub fn parse(
        self: *RemapSet,
        alloc: Allocator,
        input: []const u8,
    ) ParseError!void {
        // Find the assignment point ('=')
        const eql_idx = std.mem.indexOfScalar(
            u8,
            input,
            '=',
        ) orelse return error.MissingAssignment;

        // The to side defaults to "left" if no explicit side is given.
        // This is because this is the default unsided value provided by
        // the apprts in the current Mods layout.
        const to: Mods = to: {
            const raw = try parseMod(input[eql_idx + 1 ..]);
            break :to initMods(raw[0], raw[1] orelse .left);
        };

        // The from side, if sided, is easy and we put it directly into
        // the map.
        const from_raw = try parseMod(input[0..eql_idx]);
        if (from_raw[1]) |from_side| {
            const from: Mods = initMods(from_raw[0], from_side);
            try self.map.put(
                alloc,
                from,
                to,
            );
            errdefer comptime unreachable;
            self.mask.update(from);
            return;
        }

        // We need to do some combinatorial explosion here for unsided
        // from in order to assign all possible sides.
        const from_left = initMods(from_raw[0], .left);
        const from_right = initMods(from_raw[0], .right);
        try self.map.put(
            alloc,
            from_left,
            to,
        );
        errdefer _ = self.map.swapRemove(from_left);
        try self.map.put(
            alloc,
            from_right,
            to,
        );
        errdefer _ = self.map.swapRemove(from_right);

        errdefer comptime unreachable;
        self.mask.update(from_left);
        self.mask.update(from_right);
    }

    pub fn deinit(self: *RemapSet, alloc: Allocator) void {
        self.map.deinit(alloc);
    }

    /// Must be called prior to any remappings so that the mapping
    /// is sorted properly. Otherwise, you will get invalid results.
    pub fn finalize(self: *RemapSet) void {
        const Context = struct {
            keys: []const Mods,

            pub fn lessThan(
                ctx: @This(),
                a_index: usize,
                b_index: usize,
            ) bool {
                _ = b_index;

                // Mods with any right sides prioritize
                const side_mask = comptime Mods.side_mask.int();
                const a = ctx.keys[a_index];
                return a.int() & side_mask != 0;
            }
        };

        self.map.sort(Context{ .keys = self.map.keys() });
    }

    /// Deep copy of the struct. Required by Config.
    pub fn clone(self: *const RemapSet, alloc: Allocator) Allocator.Error!RemapSet {
        return .{
            .map = try self.map.clone(alloc),
            .mask = self.mask,
        };
    }

    /// Compare if two RemapSets are equal. Required by Config.
    pub fn equal(self: RemapSet, other: RemapSet) bool {
        if (self.map.count() != other.map.count()) return false;

        var it = self.map.iterator();
        while (it.next()) |entry| {
            const other_value = other.map.get(entry.key_ptr.*) orelse return false;
            if (!entry.value_ptr.equal(other_value)) return false;
        }

        return true;
    }

    /// Used by Formatter. Required by Config.
    pub fn formatEntry(self: RemapSet, formatter: anytype) !void {
        if (self.map.count() == 0) {
            try formatter.formatEntry(void, {});
            return;
        }

        var it = self.map.iterator();
        while (it.next()) |entry| {
            const from = entry.key_ptr.*;
            const to = entry.value_ptr.*;

            var buf: [64]u8 = undefined;
            var writer: std.Io.Writer = .fixed(&buf);
            formatMod(&writer, from) catch return error.OutOfMemory;
            writer.writeByte('=') catch return error.OutOfMemory;
            formatMod(&writer, to) catch return error.OutOfMemory;
            try formatter.formatEntry([]const u8, writer.buffered());
        }
    }

    fn formatMod(writer: anytype, mods: Mods) !void {
        // Check which mod is set and format it with optional side prefix
        inline for (.{ "shift", "ctrl", "alt", "super" }) |name| {
            if (@field(mods, name)) {
                const side = @field(mods.sides, name);
                if (side == .right) {
                    try writer.writeAll("right_");
                } else {
                    // Only write left_ if we need to distinguish
                    // For now, always write left_ if it's a sided mapping
                    try writer.writeAll("left_");
                }
                try writer.writeAll(name);
                return;
            }
        }
    }

    /// Parses a single mode in a single remapping string. E.g.
    /// `ctrl` or `left_shift`.
    fn parseMod(input: []const u8) error{InvalidMod}!struct { Mod, ?Mod.Side } {
        const side_str, const mod_str = if (std.mem.indexOfScalar(
            u8,
            input,
            '_',
        )) |idx| .{
            input[0..idx],
            input[idx + 1 ..],
        } else .{
            "",
            input,
        };

        const mod: Mod = if (std.meta.stringToEnum(
            Mod,
            mod_str,
        )) |mod| mod else mod: {
            inline for (alias) |pair| {
                if (std.mem.eql(u8, mod_str, pair[0])) {
                    break :mod pair[1];
                }
            }

            return error.InvalidMod;
        };

        return .{
            mod,
            if (side_str.len > 0) std.meta.stringToEnum(
                Mod.Side,
                side_str,
            ) orelse return error.InvalidMod else null,
        };
    }

    fn initMods(mod: Mod, side: Mod.Side) Mods {
        switch (mod) {
            inline else => |tag| {
                var mods: Mods = .{};
                @field(mods, @tagName(tag)) = true;
                @field(mods.sides, @tagName(tag)) = side;
                return mods;
            },
        }
    }

    /// Returns true if the given mods need remapping.
    pub fn isRemapped(self: *const RemapSet, mods: Mods) bool {
        return self.mask.match(mods);
    }

    /// Apply a remap to the given mods.
    pub fn apply(self: *const RemapSet, mods: Mods) Mods {
        if (!self.isRemapped(mods)) return mods;

        const mods_binding: Mods.Keys.Backing = @truncate(mods.int());
        const mods_sides: Mods.Side.Backing = @bitCast(mods.sides);

        var it = self.map.iterator();
        while (it.next()) |entry| {
            const from = entry.key_ptr.*;
            const from_binding: Mods.Keys.Backing = @truncate(from.int());
            if (mods_binding & from_binding != from_binding) continue;
            const from_sides: Mods.Side.Backing = @bitCast(from.sides);
            if ((mods_sides ^ from_sides) & from_binding != 0) continue;

            var mods_int = mods.int();
            mods_int &= ~from.int();
            mods_int |= entry.value_ptr.int();
            return @bitCast(mods_int);
        }

        unreachable;
    }

    /// Tracks which modifier keys and sides have remappings registered.
    /// Used as a fast pre-check before doing expensive map lookups.
    ///
    /// The mask uses separate tracking for left and right sides because
    /// remappings can be side-specific (e.g., only remap left_ctrl).
    ///
    /// Note: `left_sides` uses inverted logic where 1 means "left is remapped"
    /// even though `Mod.Side.left = 0`. This allows efficient bitwise matching
    /// since we can AND directly with the side bits.
    pub const Mask = packed struct(u12) {
        /// Which modifier keys (shift/ctrl/alt/super) have any remapping.
        keys: Mods.Keys = .{},
        /// Which modifiers have left-side remappings (inverted: 1 = left remapped).
        left_sides: Mods.Side = .{},
        /// Which modifiers have right-side remappings (1 = right remapped).
        right_sides: Mods.Side = .{},

        /// Adds a modifier to the mask, marking it as having a remapping.
        pub fn update(self: *Mask, mods: Mods) void {
            const keys_int: Mods.Keys.Backing = mods.keys().int();

            // OR the new keys into our existing keys mask.
            // Example: keys=0b0000, new ctrl → keys=0b0010
            self.keys = @bitCast(self.keys.int() | keys_int);

            // Both Keys and Side are u4 with matching bit positions.
            // This lets us use keys_int to select which side bits to update.
            const sides: Mods.Side.Backing = @bitCast(mods.sides);
            const left_int: Mods.Side.Backing = @bitCast(self.left_sides);
            const right_int: Mods.Side.Backing = @bitCast(self.right_sides);

            // Update left_sides: set bit if this key is active AND side is left.
            // Since Side.left=0, we invert sides (~sides) so left becomes 1.
            // keys_int masks to only affect the modifier being added.
            // Example: left_ctrl → keys_int=0b0010, ~sides=0b1111 (left=0 inverted)
            //          result: left_int | (0b0010 & 0b1111) = left_int | 0b0010
            self.left_sides = @bitCast(left_int | (keys_int & ~sides));

            // Update right_sides: set bit if this key is active AND side is right.
            // Since Side.right=1, we use sides directly.
            // Example: right_ctrl → keys_int=0b0010, sides=0b0010 (right=1)
            //          result: right_int | (0b0010 & 0b0010) = right_int | 0b0010
            self.right_sides = @bitCast(right_int | (keys_int & sides));
        }

        /// Returns true if the given mods match any remapping in this mask.
        /// This is a fast check to avoid expensive map lookups when no
        /// remapping could possibly apply.
        ///
        /// Checks both that the modifier key is remapped AND that the
        /// specific side (left/right) being pressed has a remapping.
        pub fn match(self: *const Mask, mods: Mods) bool {
            // Find which pressed keys have remappings registered.
            // Example: pressed={ctrl,alt}, mask={ctrl} → active=0b0010 (just ctrl)
            const active = mods.keys().int() & self.keys.int();
            if (active == 0) return false;

            // Check if the pressed side matches a remapped side.
            // For left (sides bit = 0): check against left_int (where 1 = left remapped)
            //   ~sides inverts so left becomes 1, then AND with left_int
            // For right (sides bit = 1): check against right_int directly
            //
            // Example: pressing left_ctrl (sides.ctrl=0, left_int.ctrl=1)
            //   ~sides = 0b1111, left_int = 0b0010
            //   (~sides & left_int) = 0b0010 ✓ matches
            //
            // Example: pressing right_ctrl but only left_ctrl is remapped
            //   sides = 0b0010, left_int = 0b0010, right_int = 0b0000
            //   (~0b0010 & 0b0010) | (0b0010 & 0b0000) = 0b0000 ✗ no match
            const sides: Mods.Side.Backing = @bitCast(mods.sides);
            const left_int: Mods.Side.Backing = @bitCast(self.left_sides);
            const right_int: Mods.Side.Backing = @bitCast(self.right_sides);
            const side_match = (~sides & left_int) | (sides & right_int);

            // Final check: is any active (pressed + remapped) key also side-matched?
            return (active & side_match) != 0;
        }
    };
};

test "RemapSet: unsided remap creates both left and right mappings" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);
    try set.parse(alloc, "ctrl=super");
    set.finalize();
    try testing.expectEqual(
        Mods{
            .super = true,
            .sides = .{ .super = .left },
        },
        set.apply(.{
            .ctrl = true,
            .sides = .{ .ctrl = .left },
        }),
    );
    try testing.expectEqual(
        Mods{
            .super = true,
            .sides = .{ .super = .left },
        },
        set.apply(.{
            .ctrl = true,
            .sides = .{ .ctrl = .right },
        }),
    );
}

test "RemapSet: sided from only maps that side" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "left_alt=ctrl");
    set.finalize();

    const left_alt: Mods = .{ .alt = true, .sides = .{ .alt = .left } };
    const left_ctrl: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .left } };
    try testing.expectEqual(left_ctrl, set.apply(left_alt));

    const right_alt: Mods = .{ .alt = true, .sides = .{ .alt = .right } };
    try testing.expectEqual(right_alt, set.apply(right_alt));
}

test "RemapSet: sided to" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "ctrl=right_super");
    set.finalize();

    const left_ctrl: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .left } };
    const right_super: Mods = .{ .super = true, .sides = .{ .super = .right } };
    try testing.expectEqual(right_super, set.apply(left_ctrl));
}

test "RemapSet: both sides specified" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "left_shift=right_ctrl");
    set.finalize();

    const left_shift: Mods = .{ .shift = true, .sides = .{ .shift = .left } };
    const right_ctrl: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .right } };
    try testing.expectEqual(right_ctrl, set.apply(left_shift));
}

test "RemapSet: multiple parses accumulate" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "left_ctrl=super");
    try set.parse(alloc, "left_alt=ctrl");
    set.finalize();

    const left_ctrl: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .left } };
    const left_super: Mods = .{ .super = true, .sides = .{ .super = .left } };
    try testing.expectEqual(left_super, set.apply(left_ctrl));

    const left_alt: Mods = .{ .alt = true, .sides = .{ .alt = .left } };
    const left_ctrl_result: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .left } };
    try testing.expectEqual(left_ctrl_result, set.apply(left_alt));
}

test "RemapSet: error on missing assignment" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try testing.expectError(error.MissingAssignment, set.parse(alloc, "ctrl"));
    try testing.expectError(error.MissingAssignment, set.parse(alloc, ""));
}

test "RemapSet: error on invalid modifier" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try testing.expectError(error.InvalidMod, set.parse(alloc, "invalid=ctrl"));
    try testing.expectError(error.InvalidMod, set.parse(alloc, "ctrl=invalid"));
    try testing.expectError(error.InvalidMod, set.parse(alloc, "middle_ctrl=super"));
}

test "RemapSet: isRemapped checks mask" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "ctrl=super");
    set.finalize();

    try testing.expect(set.isRemapped(.{ .ctrl = true }));
    try testing.expect(!set.isRemapped(.{ .alt = true }));
    try testing.expect(!set.isRemapped(.{ .shift = true }));
}

test "RemapSet: clone creates independent copy" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "ctrl=super");
    set.finalize();

    var cloned = try set.clone(alloc);
    defer cloned.deinit(alloc);

    try testing.expect(set.equal(cloned));
    try testing.expect(cloned.isRemapped(.{ .ctrl = true }));
}

test "RemapSet: equal compares correctly" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set1: RemapSet = .empty;
    defer set1.deinit(alloc);

    var set2: RemapSet = .empty;
    defer set2.deinit(alloc);

    try testing.expect(set1.equal(set2));

    try set1.parse(alloc, "ctrl=super");
    try testing.expect(!set1.equal(set2));

    try set2.parse(alloc, "ctrl=super");
    try testing.expect(set1.equal(set2));

    try set1.parse(alloc, "alt=shift");
    try testing.expect(!set1.equal(set2));
}

test "RemapSet: parseCLI basic" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parseCLI(alloc, "ctrl=super");
    try testing.expectEqual(@as(usize, 2), set.map.count());
}

test "RemapSet: parseCLI empty clears" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parseCLI(alloc, "ctrl=super");
    try testing.expectEqual(@as(usize, 2), set.map.count());

    try set.parseCLI(alloc, "");
    try testing.expectEqual(@as(usize, 0), set.map.count());
}

test "RemapSet: parseCLI invalid" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try testing.expectError(error.InvalidValue, set.parseCLI(alloc, "foo=bar"));
    try testing.expectError(error.InvalidValue, set.parseCLI(alloc, "ctrl"));
}

test "RemapSet: parse aliased modifiers" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "cmd=ctrl");
    set.finalize();

    const left_super: Mods = .{ .super = true, .sides = .{ .super = .left } };
    const left_ctrl: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .left } };
    try testing.expectEqual(left_ctrl, set.apply(left_super));
}

test "RemapSet: parse aliased modifiers command" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "command=alt");
    set.finalize();

    const left_super: Mods = .{ .super = true, .sides = .{ .super = .left } };
    const left_alt: Mods = .{ .alt = true, .sides = .{ .alt = .left } };
    try testing.expectEqual(left_alt, set.apply(left_super));
}

test "RemapSet: parse aliased modifiers opt and option" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "opt=super");
    set.finalize();

    const left_alt: Mods = .{ .alt = true, .sides = .{ .alt = .left } };
    const left_super: Mods = .{ .super = true, .sides = .{ .super = .left } };
    try testing.expectEqual(left_super, set.apply(left_alt));

    set.deinit(alloc);
    set = .empty;

    try set.parse(alloc, "option=shift");
    set.finalize();

    const left_shift: Mods = .{ .shift = true, .sides = .{ .shift = .left } };
    try testing.expectEqual(left_shift, set.apply(left_alt));
}

test "RemapSet: parse aliased modifiers control" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "control=super");
    set.finalize();

    const left_ctrl: Mods = .{ .ctrl = true, .sides = .{ .ctrl = .left } };
    const left_super: Mods = .{ .super = true, .sides = .{ .super = .left } };
    try testing.expectEqual(left_super, set.apply(left_ctrl));
}

test "RemapSet: parse aliased modifiers on target side" {
    const testing = std.testing;
    const alloc = testing.allocator;

    var set: RemapSet = .empty;
    defer set.deinit(alloc);

    try set.parse(alloc, "alt=cmd");
    set.finalize();

    const left_alt: Mods = .{ .alt = true, .sides = .{ .alt = .left } };
    const left_super: Mods = .{ .super = true, .sides = .{ .super = .left } };
    try testing.expectEqual(left_super, set.apply(left_alt));
}

test "RemapSet: formatEntry empty" {
    const testing = std.testing;
    const formatterpkg = @import("../config/formatter.zig");

    var buf: std.Io.Writer.Allocating = .init(testing.allocator);
    defer buf.deinit();

    const set: RemapSet = .empty;
    try set.formatEntry(formatterpkg.entryFormatter("key-remap", &buf.writer));
    try testing.expectEqualSlices(u8, "key-remap = \n", buf.written());
}

test "RemapSet: formatEntry single sided" {
    const testing = std.testing;
    const formatterpkg = @import("../config/formatter.zig");

    var buf: std.Io.Writer.Allocating = .init(testing.allocator);
    defer buf.deinit();

    var set: RemapSet = .empty;
    defer set.deinit(testing.allocator);

    try set.parse(testing.allocator, "left_ctrl=super");
    set.finalize();

    try set.formatEntry(formatterpkg.entryFormatter("key-remap", &buf.writer));
    try testing.expectEqualSlices(u8, "key-remap = left_ctrl=left_super\n", buf.written());
}

test "RemapSet: formatEntry unsided creates two entries" {
    const testing = std.testing;
    const formatterpkg = @import("../config/formatter.zig");

    var buf: std.Io.Writer.Allocating = .init(testing.allocator);
    defer buf.deinit();

    var set: RemapSet = .empty;
    defer set.deinit(testing.allocator);

    try set.parse(testing.allocator, "ctrl=super");
    set.finalize();

    try set.formatEntry(formatterpkg.entryFormatter("key-remap", &buf.writer));
    // Unsided creates both left and right mappings
    const written = buf.written();
    try testing.expect(std.mem.indexOf(u8, written, "left_ctrl=left_super") != null);
    try testing.expect(std.mem.indexOf(u8, written, "right_ctrl=left_super") != null);
}

test "RemapSet: formatEntry right sided" {
    const testing = std.testing;
    const formatterpkg = @import("../config/formatter.zig");

    var buf: std.Io.Writer.Allocating = .init(testing.allocator);
    defer buf.deinit();

    var set: RemapSet = .empty;
    defer set.deinit(testing.allocator);

    try set.parse(testing.allocator, "left_alt=right_ctrl");
    set.finalize();

    try set.formatEntry(formatterpkg.entryFormatter("key-remap", &buf.writer));
    try testing.expectEqualSlices(u8, "key-remap = left_alt=right_ctrl\n", buf.written());
}