flow-wm 0.1.0

A scrolling, infinite-horizontal-canvas tiling window manager for Windows
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
//! Configuration type definitions for FlowWM.
//!
//! # CODE is the single source of truth
//!
//! Every config struct carries a `#[serde(default)]` container attribute, so
//! any field missing from the user's `flow.toml` is filled from the struct's
//! [`Default`] implementation. These `Default` impls — defined inline below —
//! are the **canonical default values**. There is no shipped-defaults TOML
//! merged at runtime.
//!
//! As a result, a user's `flow.toml` may be **partial, empty, or even
//! nested-partial** (e.g. a `[padding]` block with only `window_gap` set).
//! Serde creates a `Default` instance first, then overrides only the fields
//! present in the TOML. This is simpler and more robust than the previous
//! two-layer TOML merge, which silently fell back to stale compiled-in values
//! when the shipped file was absent during development.
//!
//! # `default-config.toml` is an example
//!
//! [`default-config.toml`](../../../../default-config.toml) in the project root
//! is a hand-written, fully-commented **example** file. It is copied verbatim
//! into a user's config directory by `flow config init` (see
//! [`lifecycle::init_config_dir`](crate::config::lifecycle::init_config_dir)).
//! It is **not** read at runtime. It must stay in sync with the compiled
//! defaults; the `default_config_toml_matches_compiled_defaults` test enforces
//! this automatically.
//!
//! # Config File Split
//!
//! Configuration is split across two TOML files:
//!
//! - **`flow.toml`** ([`FlowConfig`]) — Application settings (padding,
//!   animation, etc.). Loaded from `%USERPROFILE%\.config\flow\flow.toml`
//!   (see [`config::dirs`](crate::config::dirs) for the full resolution chain).
//!
//! - **`flow-rules.toml`** ([`WindowRulesConfig`]) — Window classification rules
//!   and default action. Loaded from `%USERPROFILE%\.config\flow\flow-rules.toml`.
//!
//! This separation allows users to edit rules frequently (adding ignore patterns
//! for new apps) without risk of corrupting their app settings, and vice-versa.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::color::Color;

/// Top-level application configuration structure.
///
/// Loaded from `%USERPROFILE%\.config\flow\flow.toml` (see [`config::dirs`](crate::config::dirs)
/// for the full resolution chain including `--config` flag and `FLOW_CONFIG_DIR` env var
/// overrides). The struct carries `#[serde(default)]`, so the file may be partial or even empty —
/// serde fills missing fields from the [`Default`] impl.
///
/// The canonical default values live in the `Default` impl below. The `default-config.toml` file is
/// a hand-written **example** copied to users by `flow config init` — it is not read at runtime.
///
/// This struct contains **application settings only** — padding,
/// animation, etc. Window classification rules live in a separate file
/// ([`WindowRulesConfig`]) to allow independent editing.
///
/// # Column Sizing
///
/// The primary column sizing mode is [`columns_per_screen`](FlowConfig::columns_per_screen):
/// the user specifies how many columns fit on one monitor, and the daemon computes
/// the actual pixel width at runtime from the monitor resolution and [`window_gap`](Padding::window_gap).
///
/// Power users can override this by setting [`column_width`](FlowConfig::column_width)
/// to a fixed pixel value. When `column_width` is `Some`, it takes priority over
/// `columns_per_screen` — the auto-computation is skipped entirely.
///
/// # Example
///
/// ```toml
/// columns_per_screen = 4
/// min_column_width_px = 640
///
/// [padding]
/// window_gap = 16
/// up = 16
/// down = 16
///
/// [animation]
/// enabled = true
/// duration_ms = 240
/// easing = "ease-out-expo"
/// ```
///
/// See `docs/spec/04-config-and-persistence.md` for the full schema.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct FlowConfig {
    /// Number of columns that fit side-by-side on one monitor screen.
    ///
    /// The daemon computes the actual pixel width at startup:
    /// `base_content_width = (monitor_width - (N+1) * window_gap) / N`
    /// where `N = columns_per_screen`.
    ///
    /// If [`column_width`](FlowConfig::column_width) is also set, that value
    /// takes priority and this field is ignored.
    pub columns_per_screen: u32,

    /// Fixed column width in pixels — power-user override.
    ///
    /// When `Some`, this overrides the auto-computation from [`columns_per_screen`](FlowConfig::columns_per_screen).
    /// When `None`, the daemon computes the width from the monitor resolution, `columns_per_screen`,
    /// and `window_gap`.
    ///
    /// This field is **optional** in TOML — most users should rely on `columns_per_screen`.
    /// A missing `Option` field deserializes to `None` automatically.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub column_width: Option<u32>,

    /// Minimum column width in pixels. Columns cannot be resized below this.
    pub min_column_width_px: u32,

    /// Minimum row height in pixels — the floor for any single window's
    /// allocated height inside a column.
    ///
    /// This bounds the maximum number of rows (windows) that can stack inside
    /// one column: a column cannot grow rows beyond `available_height /
    /// min_window_height_px`. It is also the lower clamp for future
    /// drag-resize / IPC continuous-height adjustment of individual rows.
    ///
    /// See (`docs/src/dev-guide/layout/mutations.md`) for the height-
    /// distribution formula and the `merge-column` / `promote` operations.
    pub min_window_height_px: u32,

    /// Padding settings.
    pub padding: Padding,

    /// Animation settings.
    pub animation: AnimationConfig,

    /// Behavior when a minimized tiling window is restored.
    pub minimize_restore: MinimizeRestore,

    /// Window border overlay configuration.
    pub borders: BorderConfig,

    /// Floating window default-size configuration.
    pub floating: FloatingConfig,

    /// Focus reconciliation configuration.
    pub focus: FocusConfig,
}

fn default_window_action() -> WindowAction {
    WindowAction::Float
}

impl Default for FlowConfig {
    fn default() -> Self {
        Self {
            columns_per_screen: 4,
            column_width: None,
            min_column_width_px: 640,
            min_window_height_px: 100,
            padding: Padding::default(),
            animation: AnimationConfig::default(),
            minimize_restore: MinimizeRestore::default(),
            borders: BorderConfig::default(),
            floating: FloatingConfig::default(),
            focus: FocusConfig::default(),
        }
    }
}

/// Gap and margin configuration in pixels.
///
/// Gap is applied during the projection step (see [`projection`](crate::layout::projection)),
/// not stored inside window structs. This means [`ActualEntry`](crate::layout::ActualEntry) rects
/// are the **final HWND rects** — they can be passed directly to `SetWindowPos`.
///
/// # Uniform Gap Model
///
/// `window_gap` creates **uniform spacing** everywhere:
///
/// ```text
/// Edge | window_gap | [Window 1] | window_gap | [Window 2] | window_gap | Edge
/// ```
///
/// - `window_gap`: uniform gap between all elements (windows, screen edges)
/// - `up`: top screen margin (reserved space above tiling area)
/// - `down`: bottom screen margin (reserved space below tiling area, e.g., taskbar)
///
/// The slot-based canvas model ensures that expanding a column consumes the
/// inter-column gap so the layout always fills the screen.
///
/// ```text
/// ┌─────────────────── monitor work area ────────────────────┐
/// │ ↑ padding.up                                             │
/// │ ↑ window_gap                                             │
/// │ ┌──── window (HWND) ────┐   ┌──── window (HWND) ────┐    │
/// │ │                       │   │                       │    │
/// │ └───────────────────────┘   └───────────────────────┘    │
/// │ ↓ window_gap                                             │
/// │ ↓ padding.down                                           │
/// └──────────────────────────────────────────────────────────┘
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct Padding {
    /// Uniform gap between all elements (windows and screen edges), in pixels.
    ///
    /// This single value controls horizontal (inter-column), vertical (inter-row),
    /// and edge-to-window spacing. Setting `window_gap = 16` means every gap
    /// everywhere is 16 pixels.
    pub window_gap: i32,
    /// Top screen margin — reserved space above the tiling area.
    pub up: i32,
    /// Bottom screen margin — reserved space below the tiling area (e.g., taskbar).
    pub down: i32,
}

impl Default for Padding {
    fn default() -> Self {
        Self {
            window_gap: 16,
            up: 0,
            down: 0,
        }
    }
}

impl Padding {
    /// Validate that all padding values are non-negative.
    ///
    /// Returns `Err` with a descriptive message for the first invalid field.
    pub fn validate(&self) -> Result<(), String> {
        if self.window_gap < 0 {
            return Err(format!(
                "padding.window_gap must be non-negative, got {}",
                self.window_gap
            ));
        }
        if self.up < 0 {
            return Err(format!("padding.up must be non-negative, got {}", self.up));
        }
        if self.down < 0 {
            return Err(format!(
                "padding.down must be non-negative, got {}",
                self.down
            ));
        }
        Ok(())
    }
}

impl FlowConfig {
    /// Validate config values that serde cannot enforce.
    ///
    /// Call this after deserializing a config file to catch
    /// semantically invalid values like negative padding or
    /// min_column_width_px exceeding column_width.
    ///
    /// When `column_width` is `None`, the comparison against
    /// `min_column_width_px` is deferred to runtime (after the
    /// daemon computes the actual width from `columns_per_screen`).
    pub fn validate(&self) -> Result<(), String> {
        self.padding.validate()?;
        self.borders.validate()?;
        if self.columns_per_screen == 0 {
            return Err("columns_per_screen must be at least 1, got 0".into());
        }
        if self.min_column_width_px == 0 {
            return Err("min_column_width_px must be positive, got 0".into());
        }
        if self.min_window_height_px == 0 {
            return Err("min_window_height_px must be positive, got 0".into());
        }
        if let Some(cw) = self.column_width
            && self.min_column_width_px > cw
        {
            return Err(format!(
                "min_column_width_px ({}) must not exceed column_width ({})",
                self.min_column_width_px, cw
            ));
        }
        Ok(())
    }
}

/// A single window classification rule.
///
/// Rules are evaluated **top-to-bottom, first match wins** against new windows.
/// If no rule matches, [`WindowRulesConfig::default_action`] is used.
///
/// The `match` field uses `#[serde(rename = "match")]` so the TOML key is
/// `match` while the Rust field is `match_` (avoiding the reserved word).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WindowRule {
    /// Criteria to match against a window.
    #[serde(rename = "match")]
    pub match_: MatchRule,
    /// Action to take when matched.
    pub action: WindowAction,
    /// Optional initial column width in pixels.
    ///
    /// When set, a window matching this rule is created at this width instead
    /// of the default `column_width`. The value must fall within the engine's
    /// current bounds (`[min_column_width_px, abs_max_width]`) at apply time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initial_width_px: Option<u32>,
    /// If true, this rule overrides per-app learned state.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub override_persist: bool,
}

/// Match criteria for a window rule.
///
/// All fields are optional — a rule matches if **all specified fields** match
/// (AND logic). Unspecified (`None`) fields are ignored entirely.
///
/// Each field supports a different matching mode:
///
/// - **Exact match** (`exe`, `title`, `class`, `process_path`) — the candidate
///   string must equal the rule value exactly.
///
/// - **Substring match** (`title_contains`) — the rule value must appear as a
///   contiguous substring of the candidate string.
///
/// - **Regex match** (`exe_regex`, `title_regex`, `class_regex`,
///   `process_path_regex`) — the rule value is compiled as a Rust regex and the
///   full candidate string must match (not just a substring). Uses the `regex`
///   crate's syntax.
///
/// # Case Sensitivity
///
/// | Field               | Semantics                                         |
/// |---------------------|---------------------------------------------------|
/// | `exe`               | Case-insensitive (Windows paths are case-insensitive) |
/// | `exe_regex`         | Case-insensitive by default (Windows paths)       |
/// | `title`             | Case-sensitive                                    |
/// | `title_contains`    | Case-sensitive                                    |
/// | `title_regex`       | Case-sensitive (use `(?i)` for case-insensitive)  |
/// | `class`             | Case-sensitive                                    |
/// | `class_regex`       | Case-sensitive (use `(?i)` for case-insensitive)  |
/// | `process_path`      | Case-insensitive (Windows paths)                  |
/// | `process_path_regex` | Case-insensitive by default (Windows paths)      |
///
/// **Why are `exe` and `process_path` case-insensitive?**
///
/// On Windows, the filesystem is case-insensitive — `chrome.exe` and `Chrome.exe`
/// refer to the same file. Window class names (`class`) and titles (`title`) are
/// case-sensitive strings that applications control, so they are matched exactly.
/// Regex fields use the `(?i)` / `(?-i)` inline flags if the user needs different
/// behavior.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct MatchRule {
    /// Exact executable name (e.g., `"code.exe"`). Case-insensitive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exe: Option<String>,

    /// Exact window title. Case-sensitive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Case-sensitive substring match on title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title_contains: Option<String>,

    /// Full regex match on title. Case-sensitive.
    /// Use `(?i)` inline flag for case-insensitive matching.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title_regex: Option<String>,

    /// Exact Win32 window class name. Case-sensitive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class: Option<String>,

    /// Exact full executable path. Case-insensitive (Windows filesystem).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub process_path: Option<String>,

    /// Regex on executable name. Case-insensitive by default.
    /// Use `(?-i)` inline flag to opt into case-sensitive matching.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exe_regex: Option<String>,

    /// Regex on Win32 window class name. Case-sensitive.
    /// Use `(?i)` inline flag for case-insensitive matching.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class_regex: Option<String>,

    /// Regex on full executable path. Case-insensitive by default.
    /// Use `(?-i)` inline flag to opt into case-sensitive matching.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub process_path_regex: Option<String>,
}

/// Action to apply when a window rule matches.
///
/// - `Tile` — managed by [`ScrollingSpace`](crate::workspace::ScrollingSpace)
/// - `Float` — free-floating, user-positioned, not tiled
/// - `Ignore` — excluded from tiling entirely (e.g., fullscreen apps)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum WindowAction {
    /// Managed by [`ScrollingSpace`](crate::workspace::ScrollingSpace).
    Tile,
    /// Free-floating, user-positioned, not tiled.
    Float,
    /// Excluded from tiling entirely (e.g., fullscreen apps).
    Ignore,
}

/// Window classification configuration, loaded from `flow-rules.toml`.
///
/// This is the user-facing window rules file. Rules are evaluated top-to-bottom,
/// first match wins. If no rule matches, `default_action` is used.
///
/// Loaded from `%USERPROFILE%\.config\flow\flow-rules.toml` (see [`config::dirs`](crate::config::dirs)
/// for overrides). If the file doesn't exist,
/// defaults to an empty rule list with `default_action: float`.
///
/// # Example
///
/// ```toml
/// default_action = "float"
///
/// [[rules]]
/// match = { exe = "explorer.exe", title_contains = "Open" }
/// action = "ignore"
///
/// [[rules]]
/// match = { class = "Chrome_WidgetWin_1" }
/// action = "tile"
/// initial_width_px = 960
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WindowRulesConfig {
    /// Default action for windows not matching any rule.
    pub default_action: WindowAction,

    /// Window classification rules (first match wins).
    #[serde(default)]
    pub rules: Vec<WindowRule>,
}

impl Default for WindowRulesConfig {
    /// Returns a default config with `float` as the default action and no rules.
    fn default() -> Self {
        Self {
            default_action: default_window_action(),
            rules: Vec::new(),
        }
    }
}

/// Named easing curves available in user configuration.
///
/// Each variant corresponds to an easing function implemented in
/// [`crate::animation::easing::EasingStyle`]. The variant names use
/// CSS-like kebab-case when serialized to TOML (e.g. `EaseOutExpo` →
/// `"ease-out-expo"`).
///
/// The full set mirrors the 31 named curves in the animation engine.
/// `CubicBezier` is excluded because it requires four `f64` parameters
/// that cannot be expressed as a simple serde enum variant.
///
/// # Design Decision
///
/// This enum lives in the `config/` layer (not `animation/`) to honour
/// the module dependency hierarchy: `config/` may only import from
/// `common/`, never from `animation/`. The conversion from
/// `ConfigEasing` → `EasingStyle` is performed in the `daemon/` layer
/// (see [`crate::daemon::config_derive`]).
///
/// # Example
///
/// ```toml
/// [animation]
/// easing = "ease-in-out-cubic"
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum ConfigEasing {
    /// Constant-velocity linear interpolation.
    Linear,
    /// Accelerating sine curve.
    EaseInSine,
    /// Decelerating sine curve.
    EaseOutSine,
    /// Symmetric sine ease-in-out.
    EaseInOutSine,
    /// Accelerating quadratic curve.
    EaseInQuad,
    /// Decelerating quadratic curve.
    EaseOutQuad,
    /// Symmetric quadratic ease-in-out.
    EaseInOutQuad,
    /// Accelerating cubic curve.
    EaseInCubic,
    /// Decelerating cubic curve.
    EaseOutCubic,
    /// Symmetric cubic ease-in-out.
    EaseInOutCubic,
    /// Accelerating quartic curve.
    EaseInQuart,
    /// Decelerating quartic curve.
    EaseOutQuart,
    /// Symmetric quartic ease-in-out.
    EaseInOutQuart,
    /// Accelerating quintic curve.
    EaseInQuint,
    /// Decelerating quintic curve.
    EaseOutQuint,
    /// Symmetric quintic ease-in-out.
    EaseInOutQuint,
    /// Accelerating exponential curve.
    EaseInExpo,
    /// Decelerating exponential curve.
    #[default]
    EaseOutExpo,
    /// Symmetric exponential ease-in-out.
    EaseInOutExpo,
    /// Accelerating circular curve.
    EaseInCirc,
    /// Decelerating circular curve.
    EaseOutCirc,
    /// Symmetric circular ease-in-out.
    EaseInOutCirc,
    /// Slight pull-back before departure.
    EaseInBack,
    /// Slight overshoot past the target.
    EaseOutBack,
    /// Symmetric back ease-in-out.
    EaseInOutBack,
    /// Elastic oscillation on departure.
    EaseInElastic,
    /// Elastic oscillation on arrival.
    EaseOutElastic,
    /// Symmetric elastic ease-in-out.
    EaseInOutElastic,
    /// Bounce on departure.
    EaseInBounce,
    /// Bounce on arrival.
    EaseOutBounce,
    /// Symmetric bounce ease-in-out.
    EaseInOutBounce,
}

/// Animation configuration for layout transitions.
///
/// When disabled, all window position changes are applied instantly
/// without animation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct AnimationConfig {
    /// Whether layout transitions are animated.
    pub enabled: bool,
    /// Animation duration in milliseconds.
    pub duration_ms: u32,
    /// Easing curve applied to window position channels (x, y).
    ///
    /// See [`ConfigEasing`] for the full list of supported curves.
    /// Defaults to [`ConfigEasing::EaseOutExpo`].
    pub easing: ConfigEasing,
}

impl Default for AnimationConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            duration_ms: 240,
            easing: ConfigEasing::EaseOutExpo,
        }
    }
}

/// Strategy for restoring minimized tiling windows.
///
/// - `OriginalSlot` — put the window back where it was before minimize
/// - `RightOfFocused` — insert as a new column to the right of focused
/// - `AppendRight` — append as the rightmost column on the canvas
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct MinimizeRestore {
    /// Strategy for placing restored windows.
    pub strategy: MinimizeRestoreStrategy,
}

impl Default for MinimizeRestore {
    fn default() -> Self {
        Self {
            strategy: MinimizeRestoreStrategy::OriginalSlot,
        }
    }
}

/// Available minimize restore strategies.
///
/// See [`MinimizeRestore`] for the semantics of each variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MinimizeRestoreStrategy {
    /// Put the window back where it was before minimize.
    OriginalSlot,
    /// Insert as a new column to the right of focused.
    RightOfFocused,
    /// Append as the rightmost column on the canvas.
    AppendRight,
}

/// Window border overlay configuration.
///
/// The border crate draws a thin colored ring around each managed window as a
/// separate layered overlay window that follows the target HWND's geometry
/// (driven by `EVENT_OBJECT_LOCATIONCHANGE`). The daemon shrinks the actual
/// window rect by `(thickness - overlap)` pixels on each side so the colored
/// ring sits in the surrounding gap and overlaps the visible content by
/// `overlap` px (closing the DWM hairline gap). See
/// `docs/src/dev-guide/borders.md` for the full coordinate-space model.
///
/// # Example
///
/// ```toml
/// [borders]
/// enabled = true
/// thickness = 3
/// overlap = 1
/// focused_color = "#00AAFF"
/// unfocused_color = "#555555"
/// floating_color = "#AA00FF"
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct BorderConfig {
    /// Master switch. When `false`, no overlay windows are created and any
    /// existing overlays are detached.
    pub enabled: bool,
    /// Border ring thickness in pixels, applied uniformly on all four sides.
    ///
    /// The ring is drawn in the outer `thickness` px of each window's layout
    /// slot. The visible window content shrinks by `(thickness - overlap)` px
    /// per edge (see `overlap`), so the ring overlaps the content by `overlap`
    /// px rather than leaving a gap. (`docs/src/dev-guide/borders.md`)
    pub thickness: u32,
    /// How many pixels the border ring overlaps the window's visible content.
    ///
    /// Komorebi-style overlap. `0` keeps the ring entirely in the reserved
    /// gap (window shrinks by the full `thickness`); higher values pull the
    /// content edge outward until, at `overlap == thickness`, the content
    /// fills the whole layout slot and the ring sits fully on top of it. The
    /// default of `1` closes the 1px DWM-client-edge hairline that otherwise
    /// shows between an unfocused ring and the window content. Capped at
    /// `thickness` by [`BorderConfig::validate`]. (`docs/src/dev-guide/borders.md`)
    pub overlap: u32,
    /// Border color for the focused/active window.
    pub focused_color: Color,
    /// Border color for tiled-but-not-focused windows.
    pub unfocused_color: Color,
    /// Border color for floating windows.
    pub floating_color: Color,
}

impl Default for BorderConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            thickness: 3,
            overlap: 1,
            focused_color: Color::rgb(0x00, 0xAA, 0xFF),
            unfocused_color: Color::rgb(0x55, 0x55, 0x55),
            floating_color: Color::rgb(0xAA, 0x00, 0xFF),
        }
    }
}

impl BorderConfig {
    /// Validate that field values are within sane bounds.
    ///
    /// `thickness` is capped at 50 px — anything wider is almost certainly a
    /// misconfiguration that would shrink windows into nothing. `overlap` must
    /// not exceed `thickness`, otherwise the effective inset `(thickness -
    /// overlap)` goes negative and the window would expand beyond its layout
    /// slot. Color values are parsed at TOML load time, so they are already
    /// well-formed here.
    pub fn validate(&self) -> Result<(), String> {
        const MAX_THICKNESS: u32 = 50;
        if self.thickness > MAX_THICKNESS {
            return Err(format!(
                "borders.thickness must be at most {MAX_THICKNESS} px, got {}",
                self.thickness
            ));
        }
        if self.overlap > self.thickness {
            return Err(format!(
                "borders.overlap must be at most borders.thickness ({}), got {}",
                self.thickness, self.overlap
            ));
        }
        Ok(())
    }
}

/// Focus reconciliation configuration.
///
/// `EVENT_SYSTEM_FOREGROUND` is a best-effort stream: under rapid window churn
/// (e.g. a browser tearing down tabs on close) the OS may settle the foreground
/// without emitting the final foreground event, leaving flow's internal focus
/// stranded on a stale window. To close that gap, the daemon periodically
/// reconciles its tracked focus against the authoritative `GetForegroundWindow()`
/// query on the main loop. (`docs/src/dev-guide/event-pipelines.md`)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct FocusConfig {
    /// Interval between foreground-reconciliation passes, in milliseconds.
    ///
    /// Lower values catch drift sooner at the cost of more wakeups; the
    /// per-pass work is a single `GetForegroundWindow()` read (~microseconds)
    /// that no-ops when the tracked focus already matches reality. Tunable at
    /// runtime via config hot-reload.
    pub foreground_sync_interval_ms: u64,
}

impl Default for FocusConfig {
    fn default() -> Self {
        Self {
            foreground_sync_interval_ms: 250,
        }
    }
}

/// Floating window size configuration.
///
/// Both fields are optional explicit pixel sizes. When a field is `None`, the
/// daemon falls back to a built-in policy: 60% × 80% of the monitor work area,
/// capped so ultrawide / 4K monitors don't produce absurdly large popups. The
/// fallback constants live in `src/daemon/dispatch.rs` (the sole consumer).
///
/// An explicit pixel value is always respected as-is — the cap applies only to
/// the fallback path.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct FloatingConfig {
    /// Explicit default float width in pixels. `None` → built-in fallback.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_width: Option<i32>,
    /// Explicit default float height in pixels. `None` → built-in fallback.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_height: Option<i32>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_config_roundtrips_toml() {
        let config = FlowConfig::default();
        let toml_str = toml::to_string(&config).expect("serialize");
        let parsed: FlowConfig = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(parsed.columns_per_screen, 4);
        assert_eq!(parsed.column_width, None);
        assert_eq!(parsed.min_column_width_px, 640);
        assert_eq!(parsed.min_window_height_px, 100);
        assert_eq!(parsed.padding.window_gap, 16);
        assert_eq!(parsed.padding.up, 0);
        assert_eq!(parsed.padding.down, 0);
        assert_eq!(parsed.animation.duration_ms, 240);
        assert_eq!(parsed.animation.easing, ConfigEasing::EaseOutExpo);
    }

    #[test]
    fn config_from_toml_with_settings() {
        // Full TOML exercises every field end-to-end. (Serde defaults now exist,
        // but a complete file is the clearest way to verify full-population.)
        let toml_str = r#"
columns_per_screen = 3
column_width = 1200
min_column_width_px = 400

[padding]
window_gap = 8
up = 10
down = 40

[animation]
enabled = false
duration_ms = 180
easing = "ease-out-expo"

[minimize_restore]
strategy = "original_slot"
"#;
        let config: FlowConfig = toml::from_str(toml_str).expect("parse");
        assert_eq!(config.columns_per_screen, 3);
        assert_eq!(config.column_width, Some(1200));
        assert_eq!(config.padding.window_gap, 8);
        assert_eq!(config.padding.up, 10);
        assert_eq!(config.padding.down, 40);
        assert!(!config.animation.enabled);
    }

    /// Positive: empty TOML deserializes to compiled defaults.
    ///
    /// Because `FlowConfig` carries `#[serde(default)]` at the container level,
    /// an empty file
    /// (or a file with no recognized keys) yields a fully-defaulted [`FlowConfig`].
    /// This is the core of the "code is the source of truth" model: there is no
    /// separate shipped-defaults file to merge.
    #[test]
    fn config_from_empty_toml_uses_defaults() {
        let config: FlowConfig = toml::from_str("").expect("empty TOML should use defaults");
        assert_eq!(config, FlowConfig::default());
    }

    /// Positive: partial TOML (a single field) fills the rest from defaults.
    #[test]
    fn config_from_partial_toml_uses_defaults() {
        let config: FlowConfig =
            toml::from_str("columns_per_screen = 3\n").expect("partial TOML should parse");
        assert_eq!(config.columns_per_screen, 3);
        // Everything else comes from defaults.
        assert_eq!(config.min_column_width_px, 640);
        assert_eq!(config.padding.window_gap, 16);
        assert_eq!(config.animation.duration_ms, 240);
    }

    /// Positive: a nested-partial `[padding]` block fills missing sub-fields.
    ///
    /// Only `window_gap` is set; `up` and `down` must come from their serde
    /// defaults. This verifies the per-field defaults reach inside nested structs.
    #[test]
    fn config_from_nested_partial_toml_uses_defaults() {
        let toml_str = "[padding]\nwindow_gap = 20\n";
        let config: FlowConfig = toml::from_str(toml_str).expect("nested-partial should parse");
        assert_eq!(config.padding.window_gap, 20);
        assert_eq!(config.padding.up, 0);
        assert_eq!(config.padding.down, 0);
        // Top-level defaults still apply.
        assert_eq!(config.columns_per_screen, 4);
    }

    /// Positive: a nested-partial `[animation]` block fills missing fields.
    ///
    /// Only `duration_ms` is set; `enabled` and `easing` must come from serde
    /// defaults. This verifies per-field defaults inside `AnimationConfig`.
    #[test]
    fn config_from_nested_partial_animation_uses_defaults() {
        let toml_str = "[animation]\nduration_ms = 500\n";
        let config: FlowConfig =
            toml::from_str(toml_str).expect("nested-partial animation should parse");
        assert_eq!(config.animation.duration_ms, 500);
        // Missing fields should be their compiled defaults.
        assert!(
            config.animation.enabled,
            "animation.enabled should default to true"
        );
        assert_eq!(
            config.animation.easing,
            ConfigEasing::EaseOutExpo,
            "animation.easing should default to ease-out-expo"
        );
    }

    /// Sync guard: the hand-written `default-config.toml` example must parse to
    /// exactly the compiled [`FlowConfig::default()`].
    ///
    /// This enforces the AGENTS.md rule that `default-config.toml` stays in sync
    /// with the compiled `Default` impl. If you change a
    /// default in code, update the example file too (or this test fails).
    #[test]
    fn default_config_toml_matches_compiled_defaults() {
        let example: &str = include_str!("../../default-config.toml");
        let parsed: FlowConfig =
            toml::from_str(example).expect("default-config.toml must parse as FlowConfig");
        assert_eq!(
            parsed,
            FlowConfig::default(),
            "default-config.toml drifted from compiled defaults; \
             update one to match the other"
        );
    }

    /// Positive: `FocusConfig::default()` ships `foreground_sync_interval_ms = 250`
    /// — the tuned ~4 Hz foreground-reconciliation cadence that balances
    /// focus-drift detection latency against wakeup cost.
    ///
    /// A regression to a much larger value would let the post-close-cascade
    /// settle window slip past the next poll (visible focus desync), while a
    /// much smaller value burns wakeups on a microsecond-scale no-op. The
    /// `default-config.toml` sync test catches this only if the example file is
    /// also updated; this focused check guards the compiled `Default` impl
    /// independently, mirroring `border_config_default_overlap_is_one`.
    #[test]
    fn focus_config_default_interval_is_250ms() {
        assert_eq!(FocusConfig::default().foreground_sync_interval_ms, 250);
    }

    // --- Integration: Full field preservation through round-trip ---

    #[test]
    fn config_roundtrip_preserves_all_fields() {
        // Positive: every field survives TOML → FlowConfig → TOML
        let config = FlowConfig {
            columns_per_screen: 3,
            column_width: Some(1200),
            min_column_width_px: 400,
            min_window_height_px: 120,
            padding: Padding {
                window_gap: 6,
                up: 10,
                down: 40,
            },
            animation: AnimationConfig {
                enabled: false,
                duration_ms: 250,
                easing: ConfigEasing::EaseInOutCubic,
            },
            minimize_restore: MinimizeRestore {
                strategy: MinimizeRestoreStrategy::AppendRight,
            },
            borders: BorderConfig {
                enabled: false,
                thickness: 7,
                overlap: 2,
                focused_color: Color::rgb(0x10, 0x20, 0x30),
                unfocused_color: Color::rgb(0x40, 0x50, 0x60),
                floating_color: Color::rgb(0x70, 0x80, 0x90),
            },
            floating: FloatingConfig {
                default_width: Some(1200),
                default_height: Some(800),
            },
            focus: FocusConfig {
                foreground_sync_interval_ms: 400,
            },
        };

        let toml_str = toml::to_string(&config).expect("serialize all fields");
        let parsed: FlowConfig = toml::from_str(&toml_str).expect("deserialize all fields");

        assert_eq!(parsed.columns_per_screen, 3);
        assert_eq!(parsed.column_width, Some(1200));
        assert_eq!(parsed.min_column_width_px, 400);
        assert_eq!(parsed.min_window_height_px, 120);
        assert_eq!(parsed.padding.window_gap, 6);
        assert_eq!(parsed.padding.up, 10);
        assert_eq!(parsed.padding.down, 40);
        assert!(!parsed.animation.enabled);
        assert_eq!(parsed.animation.duration_ms, 250);
        assert_eq!(parsed.animation.easing, ConfigEasing::EaseInOutCubic);
        assert_eq!(
            parsed.minimize_restore.strategy,
            MinimizeRestoreStrategy::AppendRight
        );
        assert!(!parsed.borders.enabled);
        assert_eq!(parsed.borders.thickness, 7);
        assert_eq!(parsed.borders.overlap, 2);
        assert_eq!(parsed.borders.focused_color, Color::rgb(0x10, 0x20, 0x30));
        assert_eq!(parsed.borders.unfocused_color, Color::rgb(0x40, 0x50, 0x60));
        assert_eq!(parsed.borders.floating_color, Color::rgb(0x70, 0x80, 0x90));
        assert_eq!(parsed.floating.default_width, Some(1200));
        assert_eq!(parsed.floating.default_height, Some(800));
        assert_eq!(parsed.focus.foreground_sync_interval_ms, 400);
    }

    #[test]
    fn config_validate_rejects_negative_window_padding() {
        let config = FlowConfig {
            padding: Padding {
                window_gap: -1,
                ..Padding::default()
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(
            config
                .validate()
                .unwrap_err()
                .contains("padding.window_gap")
        );
    }

    #[test]
    fn config_validate_rejects_negative_up_padding() {
        let config = FlowConfig {
            padding: Padding {
                up: -5,
                ..Padding::default()
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(config.validate().unwrap_err().contains("padding.up"));
    }

    #[test]
    fn config_validate_rejects_negative_down_padding() {
        let config = FlowConfig {
            padding: Padding {
                down: -10,
                ..Padding::default()
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(config.validate().unwrap_err().contains("padding.down"));
    }

    #[test]
    fn config_validate_accepts_zero_padding() {
        let config = FlowConfig {
            padding: Padding {
                window_gap: 0,
                up: 0,
                down: 0,
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn config_validate_accepts_default_config() {
        assert!(FlowConfig::default().validate().is_ok());
    }

    #[test]
    fn config_validate_rejects_overlap_exceeding_thickness() {
        let config = FlowConfig {
            borders: BorderConfig {
                thickness: 3,
                overlap: 4,
                ..BorderConfig::default()
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(config.validate().unwrap_err().contains("borders.overlap"));
    }

    #[test]
    fn config_validate_accepts_overlap_equal_to_thickness() {
        // overlap == thickness is the boundary: content fills the whole slot.
        let config = FlowConfig {
            borders: BorderConfig {
                thickness: 3,
                overlap: 3,
                ..BorderConfig::default()
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_ok());
    }

    /// Positive: `BorderConfig::default()` ships `overlap = 1` — the komorebi
    /// default that closes the 1 px DWM-client-edge hairline gap between an
    /// unfocused ring and the window content.
    ///
    /// A regression to `0` would silently reintroduce the gap for every user
    /// relying on the shipped defaults. The `default-config.toml` sync test
    /// catches this only if the example file is also updated; this focused
    /// check guards the compiled `Default` impl independently.
    #[test]
    fn border_config_default_overlap_is_one() {
        assert_eq!(BorderConfig::default().overlap, 1);
    }

    /// Positive: `overlap = 0` (komorebi-style overlap disabled) is accepted
    /// by validation. This is the backward-compat value — the window shrinks
    /// by the full `thickness` and the ring sits wholly in the reserved gap,
    /// never overlapping the content.
    #[test]
    fn config_validate_accepts_overlap_zero() {
        let config = FlowConfig {
            borders: BorderConfig {
                thickness: 3,
                overlap: 0,
                ..BorderConfig::default()
            },
            ..FlowConfig::default()
        };
        assert!(config.validate().is_ok());
    }

    /// Positive: an explicit `overlap = 0` survives a TOML serialize →
    /// deserialize round-trip on `BorderConfig`.
    ///
    /// Guards against a regression where a `skip_serializing_if` attribute
    /// would silently drop the field at its "default-ish" value and lose the
    /// user's explicit "komorebi off" choice on the next config write.
    #[test]
    fn config_overlap_zero_roundtrips_toml() {
        let config = BorderConfig {
            thickness: 5,
            overlap: 0,
            ..BorderConfig::default()
        };
        let toml_str = toml::to_string(&config).expect("serialize");
        let parsed: BorderConfig = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(parsed.overlap, 0);
        assert_eq!(parsed.thickness, 5);
    }

    #[test]
    fn config_validate_rejects_zero_min_column_width() {
        let config = FlowConfig {
            min_column_width_px: 0,
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(
            config
                .validate()
                .unwrap_err()
                .contains("min_column_width_px")
        );
    }

    #[test]
    fn config_validate_rejects_zero_min_window_height() {
        // Negative: min_window_height_px == 0 is invalid (would allow zero-
        // height windows). The validation must reject it with a descriptive
        // error message naming the field.
        let config = FlowConfig {
            min_window_height_px: 0,
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(
            config
                .validate()
                .unwrap_err()
                .contains("min_window_height_px"),
            "error message must name the offending field"
        );
    }

    #[test]
    fn config_validate_rejects_min_exceeding_column_width() {
        let config = FlowConfig {
            min_column_width_px: 1000,
            column_width: Some(960),
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(
            config
                .validate()
                .unwrap_err()
                .contains("min_column_width_px")
        );
    }

    #[test]
    fn config_validate_accepts_min_equal_to_column_width() {
        // When column_width is explicitly set, min must be <= it (equality is ok).
        let config = FlowConfig {
            min_column_width_px: 960,
            column_width: Some(960),
            ..FlowConfig::default()
        };
        assert!(config.validate().is_ok());
    }

    #[test]
    fn config_validate_rejects_zero_columns_per_screen() {
        let config = FlowConfig {
            columns_per_screen: 0,
            ..FlowConfig::default()
        };
        assert!(config.validate().is_err());
        assert!(
            config
                .validate()
                .unwrap_err()
                .contains("columns_per_screen")
        );
    }

    #[test]
    fn config_validate_accepts_column_width_none() {
        // When column_width is None (auto-compute mode), min check is deferred.
        let config = FlowConfig {
            column_width: None,
            min_column_width_px: 9999,
            ..FlowConfig::default()
        };
        assert!(config.validate().is_ok());
    }

    // --- WindowRulesConfig tests ---

    #[test]
    fn window_rules_config_default_roundtrips() {
        let config = WindowRulesConfig::default();
        let toml_str = toml::to_string(&config).expect("serialize");
        let parsed: WindowRulesConfig = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(parsed.default_action, WindowAction::Float);
        assert!(parsed.rules.is_empty());
    }

    #[test]
    fn window_rules_config_from_toml() {
        let toml_str = r#"
default_action = "float"

[[rules]]
match = { exe = "explorer.exe", title_contains = "Open" }
action = "ignore"

[[rules]]
match = { class = "Chrome_WidgetWin_1" }
action = "tile"
initial_width_px = 960
"#;
        let config: WindowRulesConfig = toml::from_str(toml_str).expect("parse");
        assert_eq!(config.default_action, WindowAction::Float);
        assert_eq!(config.rules.len(), 2);
        assert_eq!(config.rules[0].action, WindowAction::Ignore);
        assert_eq!(config.rules[1].initial_width_px, Some(960));
    }

    /// Positive: TOML with only `default_action` parses correctly (rules defaults to empty).
    #[test]
    fn window_rules_config_minimal_toml() {
        let toml_str = "default_action = \"float\"\n";
        let config: WindowRulesConfig = toml::from_str(toml_str).expect("parse");
        assert_eq!(config.default_action, WindowAction::Float);
        assert!(config.rules.is_empty());
    }

    /// Negative: empty TOML fails because `default_action` is required.
    #[test]
    fn window_rules_config_empty_toml_is_rejected() {
        let toml_str = "";
        let result = toml::from_str::<WindowRulesConfig>(toml_str);
        assert!(
            result.is_err(),
            "empty TOML should fail without serde defaults on default_action"
        );
    }

    #[test]
    fn window_rules_config_with_regex_fields_roundtrips() {
        let config = WindowRulesConfig {
            default_action: WindowAction::Ignore,
            rules: vec![WindowRule {
                match_: MatchRule {
                    exe: None,
                    title: None,
                    title_contains: None,
                    title_regex: Some("^Settings".into()),
                    class: Some("SettingsApp".into()),
                    class_regex: Some("Settings.*".into()),
                    process_path: None,
                    exe_regex: Some("chrome\\.exe".into()),
                    process_path_regex: Some(".*\\\\Google\\\\Chrome\\\\.*".into()),
                },
                action: WindowAction::Float,
                initial_width_px: None,
                override_persist: false,
            }],
        };

        let toml_str = toml::to_string(&config).expect("serialize");
        let parsed: WindowRulesConfig = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(parsed.default_action, WindowAction::Ignore);
        assert_eq!(parsed.rules.len(), 1);
        assert_eq!(
            parsed.rules[0].match_.exe_regex,
            Some("chrome\\.exe".into())
        );
        assert_eq!(
            parsed.rules[0].match_.class_regex,
            Some("Settings.*".into())
        );
        assert_eq!(
            parsed.rules[0].match_.process_path_regex,
            Some(".*\\\\Google\\\\Chrome\\\\.*".into())
        );
    }

    #[test]
    fn window_rules_config_all_window_actions_parse() {
        for action_str in ["tile", "float", "ignore"] {
            let toml_str = format!("default_action = \"{action_str}\"");
            let config: WindowRulesConfig = toml::from_str(&toml_str).expect(&toml_str);
            assert_eq!(
                config.default_action,
                match action_str {
                    "tile" => WindowAction::Tile,
                    "float" => WindowAction::Float,
                    "ignore" => WindowAction::Ignore,
                    _ => unreachable!(),
                },
                "action mismatch for {action_str}"
            );
        }
    }

    #[test]
    fn window_rules_config_invalid_enum_rejects() {
        let toml_str = r#"
default_action = "foobar"
"#;
        let result = toml::from_str::<WindowRulesConfig>(toml_str);
        assert!(result.is_err(), "invalid enum value should reject");
    }

    // --- ConfigEasing-specific tests ---

    /// Positive: all 31 ConfigEasing variants round-trip through TOML
    /// serialize → deserialize.
    ///
    /// This validates that `#[serde(rename_all = "kebab-case")]` produces
    /// the expected kebab-case strings and that serde can parse them back
    /// to the correct variant.
    ///
    /// Standalone `toml::to_string(&enum_variant)` is unsupported by the
    /// `toml` crate, so we embed each variant inside a `AnimationConfig`
    /// wrapper and verify the serialized TOML contains the expected
    /// kebab-case string.
    #[test]
    fn config_easing_roundtrips_all_variants() {
        for (variant, expected_kebab) in [
            (ConfigEasing::Linear, "linear"),
            (ConfigEasing::EaseInSine, "ease-in-sine"),
            (ConfigEasing::EaseOutSine, "ease-out-sine"),
            (ConfigEasing::EaseInOutSine, "ease-in-out-sine"),
            (ConfigEasing::EaseInQuad, "ease-in-quad"),
            (ConfigEasing::EaseOutQuad, "ease-out-quad"),
            (ConfigEasing::EaseInOutQuad, "ease-in-out-quad"),
            (ConfigEasing::EaseInCubic, "ease-in-cubic"),
            (ConfigEasing::EaseOutCubic, "ease-out-cubic"),
            (ConfigEasing::EaseInOutCubic, "ease-in-out-cubic"),
            (ConfigEasing::EaseInQuart, "ease-in-quart"),
            (ConfigEasing::EaseOutQuart, "ease-out-quart"),
            (ConfigEasing::EaseInOutQuart, "ease-in-out-quart"),
            (ConfigEasing::EaseInQuint, "ease-in-quint"),
            (ConfigEasing::EaseOutQuint, "ease-out-quint"),
            (ConfigEasing::EaseInOutQuint, "ease-in-out-quint"),
            (ConfigEasing::EaseInExpo, "ease-in-expo"),
            (ConfigEasing::EaseOutExpo, "ease-out-expo"),
            (ConfigEasing::EaseInOutExpo, "ease-in-out-expo"),
            (ConfigEasing::EaseInCirc, "ease-in-circ"),
            (ConfigEasing::EaseOutCirc, "ease-out-circ"),
            (ConfigEasing::EaseInOutCirc, "ease-in-out-circ"),
            (ConfigEasing::EaseInBack, "ease-in-back"),
            (ConfigEasing::EaseOutBack, "ease-out-back"),
            (ConfigEasing::EaseInOutBack, "ease-in-out-back"),
            (ConfigEasing::EaseInElastic, "ease-in-elastic"),
            (ConfigEasing::EaseOutElastic, "ease-out-elastic"),
            (ConfigEasing::EaseInOutElastic, "ease-in-out-elastic"),
            (ConfigEasing::EaseInBounce, "ease-in-bounce"),
            (ConfigEasing::EaseOutBounce, "ease-out-bounce"),
            (ConfigEasing::EaseInOutBounce, "ease-in-out-bounce"),
        ] {
            // Serialize inside an AnimationConfig wrapper
            let wrapper = AnimationConfig {
                easing: variant,
                ..AnimationConfig::default()
            };
            let toml_str =
                toml::to_string(&wrapper).unwrap_or_else(|_| panic!("serialize {expected_kebab}"));
            assert!(
                toml_str.contains(&format!("easing = \"{expected_kebab}\"")),
                "serialization should contain 'easing = \"{expected_kebab}\"', got:\n{toml_str}"
            );

            // Verify deserialization produces the original variant
            let parsed: AnimationConfig = toml::from_str(&toml_str)
                .unwrap_or_else(|_| panic!("deserialize {expected_kebab}"));
            assert_eq!(
                parsed.easing, variant,
                "round-trip mismatch for {expected_kebab}"
            );
        }
    }

    /// Negative: an unknown easing string is rejected by serde.
    ///
    /// This prevents silent misconfiguration — a typo like `"ease-out-exp"` should
    /// fail fast at parse time, not silently fall back to the default.
    #[test]
    fn config_easing_invalid_string_is_rejected() {
        let invalid_values = [
            "ease-out-exp",  // typo: missing 'o'
            "linear ",       // trailing whitespace
            "Linear",        // PascalCase — kebab-case only
            "EASE-OUT-EXPO", // uppercase
            "ease_out_expo", // snake_case
            "foobar",        // completely unknown
        ];
        for bad in &invalid_values {
            let result = toml::from_str::<ConfigEasing>(bad);
            assert!(
                result.is_err(),
                "expected rejection for invalid easing value: {bad:?}"
            );
        }
    }

    #[test]
    fn match_rule_with_new_regex_fields_serializes_correctly() {
        let rule = MatchRule {
            exe_regex: Some("msedge\\.exe".into()),
            class_regex: Some("Edge.*".into()),
            process_path_regex: Some(".*\\\\Microsoft\\\\Edge.*".into()),
            ..Default::default()
        };
        let toml_str = toml::to_string(&rule).expect("serialize");
        // Verify round-trip: deserialize back and check values match
        let parsed: MatchRule = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(parsed.exe_regex, Some("msedge\\.exe".into()));
        assert_eq!(parsed.class_regex, Some("Edge.*".into()));
        assert_eq!(
            parsed.process_path_regex,
            Some(".*\\\\Microsoft\\\\Edge.*".into())
        );
    }

    // --- FloatingConfig tests ---
    //
    // `FloatingConfig` carries two optional explicit pixel sizes. When a field
    // is `None`, the daemon falls back to a built-in fraction-of-work-area
    // policy (tested in `src/daemon/dispatch.rs::fallback_float_size`). These
    // tests pin the serde + Default contract: explicit values round-trip, and
    // omitted keys parse to `None`.

    /// Positive: `FloatingConfig::default()` is `{None, None}` — both fields
    /// are optional, so the daemon's built-in fallback applies.
    #[test]
    fn floating_config_default_is_none_none() {
        let cfg = FloatingConfig::default();
        assert_eq!(cfg.default_width, None);
        assert_eq!(cfg.default_height, None);
    }

    /// Positive: explicit `Some(pixel)` values survive TOML serialize →
    /// deserialize without being altered or dropped.
    #[test]
    fn floating_config_explicit_values_roundtrip() {
        let toml_str = r#"
[floating]
default_width = 1200
default_height = 800
"#;
        let parsed: FlowConfig = toml::from_str(toml_str).expect("parse");
        assert_eq!(parsed.floating.default_width, Some(1200));
        assert_eq!(parsed.floating.default_height, Some(800));

        // Re-serialize and parse once more to confirm a full round-trip.
        let reserialized = toml::to_string(&parsed).expect("serialize");
        let reparsed: FlowConfig = toml::from_str(&reserialized).expect("deserialize");
        assert_eq!(reparsed.floating.default_width, Some(1200));
        assert_eq!(reparsed.floating.default_height, Some(800));
    }

    /// Positive: an empty `[floating]` block (both keys omitted) parses to
    /// `{None, None}`. The daemon then applies the built-in fallback. This
    /// matches what `default-config.toml` ships (commented-out keys).
    #[test]
    fn floating_config_omitted_keys_parse_to_none() {
        let toml_str = "[floating]\n";
        let parsed: FlowConfig = toml::from_str(toml_str).expect("parse");
        assert_eq!(parsed.floating.default_width, None);
        assert_eq!(parsed.floating.default_height, None);
        // The rest of the config still comes from compiled defaults.
        assert_eq!(parsed, FlowConfig::default());
    }

    /// Positive: a partial `[floating]` block (only one key) fills the other
    /// from the field's serde default (`None`). Guards against a regression
    /// where setting one dimension would force the other to a non-None value.
    #[test]
    fn floating_config_partial_width_only_preserves_height_none() {
        let toml_str = "[floating]\ndefault_width = 1000\n";
        let parsed: FlowConfig = toml::from_str(toml_str).expect("parse");
        assert_eq!(parsed.floating.default_width, Some(1000));
        assert_eq!(parsed.floating.default_height, None);
    }
}