summaryrefslogtreecommitdiff
path: root/gui-apps/wcm/files/wcm-0.11.0-r21-async-ipc.patch
blob: 9400398033358b09e133e05f6ded872087bc48a2 (plain)
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
diff --git a/src/backgrounds.cpp b/src/backgrounds.cpp
index b835825..1a18134 100644
--- a/src/backgrounds.cpp
+++ b/src/backgrounds.cpp
@@ -7,15 +7,43 @@ namespace
 using json = nlohmann::json;
 json empty_slot() { return {{"image", ""}, {"sizing", "fill"}, {"color", {0,0,0,0}}, {"opacity", 1.0}}; }
 json empty_layout() { return {{"mode", "transparent"}, {"image", empty_slot()}, {"monitors", json::object()}}; }
+void validate_background_snapshot(const json& data)
+{
+    data.at("revision").get<std::string>(); data.at("topology").get<std::string>();
+    data.at("error_message").get<std::string>(); data.at("applied").get<bool>();
+    auto slot = [] (const json& s)
+    {
+        s.at("image").get<std::string>(); s.at("sizing").get<std::string>(); s.at("opacity").get<double>();
+        if (!s.at("color").is_array() || s.at("color").size() != 4) throw std::runtime_error("Invalid background color");
+        for (auto& channel : s.at("color")) channel.get<double>();
+    };
+    auto layout = [&] (const json& l)
+    {
+        l.at("mode").get<std::string>(); slot(l.at("image"));
+        if (!l.at("monitors").is_object()) throw std::runtime_error("Invalid background monitors");
+        for (auto& image : l.at("monitors")) slot(image);
+    };
+    auto& profiles = data.at("settings").at("profiles");
+    if (!profiles.is_object() || !data.at("outputs").is_array()) throw std::runtime_error("Invalid background profiles");
+    for (auto& profile : profiles)
+    {
+        layout(profile.at("default"));
+        if (!profile.at("workspaces").is_object()) throw std::runtime_error("Invalid background workspaces");
+        for (auto& workspace : profile.at("workspaces")) layout(workspace);
+    }
+    for (auto& output : data.at("outputs"))
+    {
+        output.at("name").get<std::string>(); output.at("profile").get<std::string>();
+        if (!output.at("grid").is_array() || output.at("grid").size() != 2 || !output.at("monitors").is_array())
+            throw std::runtime_error("Invalid workspace output");
+        for (auto& dimension : output.at("grid")) dimension.get<int>();
+        for (auto& monitor : output.at("monitors")) monitor.at("name").get<std::string>();
+    }
+}
 void clear(Gtk::Box& box) { for (auto child : box.get_children()) box.remove(*child); }
 void label_style(Gtk::Label& label)
 { label.set_halign(Gtk::ALIGN_START); label.set_line_wrap(); label.set_max_width_chars(75); label.set_selectable(true); }
 }
-BackgroundsPage::json BackgroundsPage::request(const std::string& method, const json& data)
-{
-    wf::json_t input; wf::json_t::parse_string(data.dump(), input);
-    return json::parse(wcm_ipc_request(method, input).serialize());
-}
 BackgroundsPage::BackgroundsPage(const std::string& config) : Gtk::Box(Gtk::ORIENTATION_VERTICAL, 10), config_file(config)
 {
     set_border_width(12); pack_start(tabs, true, true);
@@ -45,11 +73,11 @@ BackgroundsPage::BackgroundsPage(const std::string& config) : Gtk::Box(Gtk::ORIE
             if (selected_workspace == "default") { show_layout(); return; }
             auto profile = state["outputs"][outputs.get_active_row_number()]["profile"].get<std::string>();
             if (draft["profiles"].contains(profile)) draft["profiles"][profile]["workspaces"].erase(selected_workspace);
-            changed();
+            ++edit_serial; changed(); status.set_text("Unapplied workspace background changes");
         } else { auto layout = current_layout(); layout["mode"] = id; store_layout(layout); }
         show_layout();
     });
-    reload.signal_clicked().connect([this] { refresh(); });
+    reload.signal_clicked().connect([this] { refresh(true); });
     apply.signal_clicked().connect([this] { save(); });
     all.signal_clicked().connect([this]
     {
@@ -63,29 +91,43 @@ BackgroundsPage::BackgroundsPage(const std::string& config) : Gtk::Box(Gtk::ORIE
         if (target.is_null()) target = {{"default", empty_layout()}, {"workspaces", json::object()}};
         for (int y=0; y<output["grid"][1]; ++y) for (int x=0; x<output["grid"][0]; ++x)
             target["workspaces"][std::to_string(x)+","+std::to_string(y)] = layout;
-        changed(); show_layout();
+        ++edit_serial; changed(); status.set_text("Unapplied workspace background changes"); show_layout();
     });
-    refresh();
+    signal_map().connect([this] { if (pending_job) check_job(); else if (!available) refresh(); });
+    signal_unmap().connect([this] { refresh_pending = discard_pending = false; ipc.cancel_observation(); });
+    refresh(); changed();
     timer = Glib::signal_timeout().connect([this]
     {
-        if (pending_job)
-        {
-            try
-            {
-                auto next = request("workspace-backgrounds/status");
-                show_memory(next);
-                if (next["completed_job"].get<uint64_t>() == pending_job)
-                {
-                    pending_job = 0;
-                    if (next["job_success"].get<bool>()) refresh();
-                    else { changed(); status.set_text(next["error_message"].get<std::string>()); }
-                }
-            } catch (const std::exception& e) { pending_job = 0; changed(); status.set_text(e.what()); }
-        }
+        if (pending_job && get_mapped() && !ipc.busy()) check_job();
         return true;
     }, 200);
 }
 BackgroundsPage::~BackgroundsPage() { timer.disconnect(); }
+
+void BackgroundsPage::check_job()
+{
+    if (!pending_job || ipc.busy()) return;
+    ipc.send("workspace-backgrounds/status", {}, [this] (WcmIpcResult result)
+    {
+        try
+        {
+            if (!result.error.empty()) throw std::runtime_error(result.error);
+            auto next = json::parse(result.reply.serialize());
+            show_memory(next);
+            if (next["completed_job"].get<uint64_t>() == pending_job)
+            {
+                pending_job = 0;
+                if (next["job_success"].get<bool>()) refresh(true);
+                else { changed(); status.set_text(next["error_message"].get<std::string>()); }
+            }
+        } catch (const std::exception& e)
+        {
+            // This is an observation failure, not evidence that the submitted
+            // renderer job failed. Retain its id and never resubmit the job.
+            status.set_text(std::string(e.what()) + "; still waiting for the background job.");
+        }
+    });
+}
 void BackgroundsPage::show_memory(const json& renderer)
 {
     const auto mib = 1024 * 1024;
@@ -94,14 +136,31 @@ void BackgroundsPage::show_memory(const json& renderer)
     memory.set_text("Image memory: " + std::to_string((used + mib - 1) / mib) + " / " +
         std::to_string(limit / mib) + " MiB. Adjustable in Workspace backgrounds → Texture budget.");
 }
-void BackgroundsPage::refresh()
+void BackgroundsPage::refresh(bool discard)
 {
-    try
+    if (discard) discard_serial = edit_serial;
+    if (mutation_pending || pending_job) return;
+    if (ipc.busy()) { refresh_pending = true; discard_pending |= discard; return; }
+    refresh_pending = false; discard |= discard_pending; discard_pending = false;
+    auto serial = discard ? discard_serial : edit_serial;
+    status.set_text("Waiting for workspace backgrounds…");
+    ipc.send("workspace-backgrounds/get", {}, [this, discard, serial] (WcmIpcResult result)
     {
-        auto next = request("workspace-backgrounds/get");
+        try
+        {
+            if (!result.error.empty()) throw std::runtime_error(result.error);
+            auto next = json::parse(result.reply.serialize());
         if (next["version"] != 1) throw std::runtime_error("Unsupported workspace background API");
         if (std::filesystem::weakly_canonical(next["config_file"].get<std::string>()) != std::filesystem::weakly_canonical(config_file))
             throw std::runtime_error("Open WCM with the running session's configuration to edit workspace backgrounds");
+        validate_background_snapshot(next);
+        if (serial != edit_serial || (!discard && available && draft != original))
+        {
+            show_memory(next); status.set_text("Unapplied workspace background changes retained.");
+            if (refresh_pending && get_mapped()) refresh();
+            return;
+        }
+        uncertain = false;
         state = next; draft = original = state["settings"]; available = true;
         show_memory(state);
         loading = true; outputs.remove_all();
@@ -110,12 +169,14 @@ void BackgroundsPage::refresh()
         loading = false; select_output();
         auto error = state["error_message"].get<std::string>();
         status.set_text(!error.empty() ? error : state["applied"].get<bool>() ? "Saved and loaded by the workspace renderer" : "Saved; images are awaiting the workspace renderer");
-    } catch (const std::exception& e)
-    {
-        available = false; loading = false;
-        status.set_text(std::string(e.what()) + "\nWorkspace images need the workspace-backgrounds and ipc plugins with the matching Wayfire build.");
-    }
-    changed();
+        } catch (const std::exception& e)
+        {
+            loading = false; changed();
+            status.set_text(std::string(e.what()) + " Last observed settings and unapplied edits are retained.");
+        }
+        changed();
+        if (refresh_pending && get_mapped()) refresh();
+    });
 }
 void BackgroundsPage::select_output()
 {
@@ -143,15 +204,14 @@ void BackgroundsPage::store_layout(const json& layout)
     auto& target = draft["profiles"][profile];
     if (target.is_null()) target = {{"default", empty_layout()}, {"workspaces", json::object()}};
     if (selected_workspace == "default") target["default"] = layout; else target["workspaces"][selected_workspace] = layout;
-    changed();
+    ++edit_serial; changed(); status.set_text("Unapplied workspace background changes");
 }
 void BackgroundsPage::changed()
 {
-    outputs.set_sensitive(available && !pending_job); selection.set_sensitive(available && !pending_job);
-    mode.set_sensitive(available && !pending_job); editor.set_sensitive(available && !pending_job && mode.get_active_id() != "inherit");
-    apply.set_sensitive(available && !pending_job && draft != original); all.set_sensitive(available && !pending_job);
-    reload.set_sensitive(!pending_job);
-    if (available && draft != original && !pending_job) status.set_text("Unapplied workspace background changes");
+    outputs.set_sensitive(available && !pending_job && !mutation_pending); selection.set_sensitive(available && !pending_job && !mutation_pending);
+    mode.set_sensitive(available && !pending_job && !mutation_pending); editor.set_sensitive(available && !pending_job && !mutation_pending && mode.get_active_id() != "inherit");
+    apply.set_sensitive(available && !pending_job && !mutation_pending && draft != original && !uncertain); all.set_sensitive(available && !pending_job && !mutation_pending);
+    reload.set_sensitive(!pending_job && !mutation_pending);
 }
 void BackgroundsPage::show_layout()
 {
@@ -211,9 +271,25 @@ void BackgroundsPage::image_row(Gtk::Box& parent, const std::string& label, cons
 }
 void BackgroundsPage::save()
 {
-    try
+    if (!available || pending_job || mutation_pending || uncertain || draft == original) return;
+    ipc.cancel_observation(); refresh_pending = discard_pending = false;
+    json request = {{"revision",state["revision"]}, {"topology",state["topology"]}, {"settings",draft}};
+    wf::json_t input; wf::json_t::parse_string(request.dump(), input);
+    mutation_pending = true; changed(); status.set_text("Submitting workspace background changes…");
+    ipc.send("workspace-backgrounds/apply", input, [this] (WcmIpcResult result)
     {
-        auto response = request("workspace-backgrounds/apply", {{"revision",state["revision"]}, {"topology",state["topology"]}, {"settings",draft}});
-        pending_job = response["job"]; status.set_text("Preparing workspace background images…"); changed();
-    } catch (const std::exception& e) { status.set_text(e.what()); }
+        mutation_pending = false;
+        try
+        {
+            if (!result.error.empty()) throw std::runtime_error(result.error);
+            auto response = json::parse(result.reply.serialize());
+            pending_job = response.at("job").get<uint64_t>();
+            if (!pending_job) throw std::runtime_error("Invalid background job response");
+            changed(); status.set_text("Preparing workspace background images…");
+        } catch (const std::exception& e)
+        {
+            uncertain = result.uncertain || result.error.empty(); changed();
+            status.set_text(std::string(e.what()) + (uncertain ? ". Outcome unknown; use Revert workspace changes to reload the saved state before applying again." : ""));
+        }
+    }, true);
 }
diff --git a/src/backgrounds.hpp b/src/backgrounds.hpp
index be75561..d7a2a8d 100644
--- a/src/backgrounds.hpp
+++ b/src/backgrounds.hpp
@@ -1,5 +1,6 @@
 #pragma once
 #include <gtkmm.h>
+#include "ipc.hpp"
 #include <nlohmann/json.hpp>
 
 class BackgroundsPage : public Gtk::Box
@@ -14,11 +15,14 @@ class BackgroundsPage : public Gtk::Box
     Gtk::Button apply{"Apply workspace backgrounds"}, reload{"Revert workspace changes"}, all{"Copy to all workspaces"};
     json state, draft, original;
     std::string config_file, selected_output, selected_workspace = "default";
-    bool loading = false, available = false;
+    bool loading = false, available = false, mutation_pending = false, uncertain = false;
+    bool refresh_pending = false, discard_pending = false;
+    uint64_t edit_serial = 0, discard_serial = 0;
+    WcmIpcClient ipc;
     uint64_t pending_job = 0;
     sigc::connection timer;
-    static json request(const std::string& method, const json& data = json::object());
-    void refresh();
+    void refresh(bool discard = false);
+    void check_job();
     void show_memory(const json& renderer);
     void select_output();
     void show_layout();
diff --git a/src/displays.cpp b/src/displays.cpp
index 0ea8993..ecb50f6 100644
--- a/src/displays.cpp
+++ b/src/displays.cpp
@@ -2,6 +2,8 @@
 #include "displays.hpp"
 #include "backgrounds.hpp"
 #include "ipc.hpp"
+#include <nlohmann/json.hpp>
+#include <cmath>
 #include <gtk-layer-shell.h>
 #include <wayfire/config/types.hpp>
 #include <sys/socket.h>
@@ -40,9 +42,40 @@ void field(Gtk::Grid& grid, int row, const std::string& name, Gtk::Widget& contr
 }
 }
 
-wf::json_t DisplaysPage::request(const std::string& method, wf::json_t data)
+namespace
+{
+void validate_display_snapshot(const wf::json_t& wire)
 {
-    return wcm_ipc_request(method, data);
+    // Validate everything load()/select_monitor() consume before replacing a
+    // last-good observation or rebuilding any draft controls.
+    auto data = nlohmann::json::parse(wire.serialize());
+    data.at("revision").get<std::string>(); data.at("pending").get<bool>();
+    const auto& options = data.at("options");
+    if (!options.is_object()) throw std::runtime_error("Invalid display options");
+    for (const auto& value : options) value.get<std::string>();
+    for (auto key : {"core/window_scope_rules", "core/window_scope", "core/stitch_enabled", "core/stitch_outputs",
+        "core/default_output", "grid/use_virtual", "grid/use_physical", "grid/reset_scope", "grid/next_monitor",
+        "grid/zone_shift", "grid/zone_maximize", "move/activate_zone"}) options.at(key).get<std::string>();
+    std::stoi(options.at("grid/zone_gap").get<std::string>());
+    auto rules = nlohmann::json::parse(options.at("core/window_scope_rules").get<std::string>());
+    if (!rules.is_array()) throw std::runtime_error("Invalid application scope rules");
+    for (auto& rule : rules) { rule.at("app_id").get<std::string>(); rule.at("scope").get<std::string>(); }
+    if (!data.at("physical").is_array()) throw std::runtime_error("Invalid physical monitor list");
+    std::set<std::string> names;
+    for (auto& head : data.at("physical"))
+    {
+        auto name = head.at("name").get<std::string>();
+        if (name.empty() || !names.insert(name).second) throw std::runtime_error("Invalid monitor name");
+        auto prefix = head.at("prefix").get<std::string>(); head.at("description").get<std::string>();
+        for (auto key : {"width", "height", "refresh"}) head.at(key).get<int>();
+        if (!head.at("modes").is_array()) throw std::runtime_error("Invalid monitor modes");
+        for (auto& mode : head.at("modes")) for (auto key : {"width", "height", "refresh"}) mode.at(key).get<int>();
+        for (auto key : {"mode", "masked", "position", "transform"}) options.at(prefix + key).get<std::string>();
+        std::stoi(options.at(prefix + "zone_gap").get<std::string>());
+        auto scale = std::stod(options.at(prefix + "scale").get<std::string>());
+        if (!std::isfinite(scale) || scale <= 0) throw std::runtime_error("Invalid monitor scale");
+    }
+}
 }
 
 DisplaysPage::DisplaysPage(const std::string& config, std::function<void()> on_saved,
@@ -166,6 +199,8 @@ DisplaysPage::DisplaysPage(const std::string& config, std::function<void()> on_s
         std::swap(order[i], order[target]); update_members(); changed();
     };
     left_button.signal_clicked().connect([move] { move(-1); }); right_button.signal_clicked().connect([move] { move(1); });
+    signal_map().connect([this] { refresh(); });
+    signal_unmap().connect([this] { leave(); });
     refresh(true);
     timer = Glib::signal_timeout().connect([this]
     {
@@ -173,16 +208,27 @@ DisplaysPage::DisplaysPage(const std::string& config, std::function<void()> on_s
         {
             --countdown;
             status.set_text("Keep these display settings? Reverting automatically in " + std::to_string(std::max(0, countdown)) + " seconds.");
-            if (countdown <= 0) { transaction.clear(); refresh(true); status.set_text("Display preview expired; previous settings restored."); }
-        } else if (get_mapped() && !dirty) refresh();
+            if (countdown <= 0 && !mutation_pending) { transaction.clear(); refresh(); status.set_text("Display preview deadline reached; checking current settings."); }
+        } else if (get_mapped() && (!dirty || uncertain)) refresh();
         return true;
     }, 1000);
 }
 
 DisplaysPage::~DisplaysPage()
 {
-    timer.disconnect(); identify_timer.disconnect();
-    if (!transaction.empty()) { try { wf::json_t data; data["token"] = transaction; request("displays/revert", data); } catch (...) {} }
+    timer.disconnect(); identify_timer.disconnect(); ipc.cancel_observation();
+    if (!transaction.empty())
+    {
+        wf::json_t data; data["token"] = transaction;
+        wcm_ipc_cleanup("displays/revert", data);
+    }
+}
+
+void DisplaysPage::leave()
+{
+    refresh_pending = discard_pending = false;
+    ipc.cancel_observation(); identify_timer.disconnect(); identifiers.clear();
+    if (!transaction.empty() && !mutation_pending) finish(false);
 }
 
 std::string DisplaysPage::get(const std::string& key) const
@@ -194,28 +240,71 @@ void DisplaysPage::error(const std::string& message) { status.set_text(message);
 
 void DisplaysPage::refresh(bool discard)
 {
-    try
+    if (discard) discard_serial = edit_serial;
+    if (mutation_pending) return;
+    if (ipc.busy()) { refresh_pending = true; discard_pending |= discard; return; }
+    refresh_pending = false; discard |= discard_pending; discard_pending = false;
+    auto serial = discard ? discard_serial : edit_serial;
+    status.set_text("Waiting for display settings…");
+    ipc.send("displays/get", {}, [this, discard, serial] (WcmIpcResult result)
     {
-        auto data = request("displays/get");
-        if (data["version"].as_int() != 1) throw std::runtime_error("Unsupported display-management version");
-        if (std::filesystem::weakly_canonical(data["config_file"].as_string()) != std::filesystem::weakly_canonical(config_file))
-            throw std::runtime_error("WCM is editing a different configuration from the running compositor. Open its session configuration: " + data["config_file"].as_string());
-        if (data["pending"].as_bool() && transaction.empty())
+        try
         {
-            left.set_sensitive(false); right.set_sensitive(false); scope_tab.set_sensitive(false);
-            apply_button.set_sensitive(false); identify_button.set_sensitive(false);
-            status.set_text("A display preview is awaiting confirmation in another window."); return;
+            if (!result.error.empty()) throw std::runtime_error(result.error);
+            auto data = result.reply;
+            if (data["version"].as_int() != 1) throw std::runtime_error("Unsupported display-management version");
+            if (std::filesystem::weakly_canonical(data["config_file"].as_string()) != std::filesystem::weakly_canonical(config_file))
+                throw std::runtime_error("WCM is editing a different configuration from the running compositor. Open its session configuration: " + data["config_file"].as_string());
+            validate_display_snapshot(data);
+            foreign_preview = data["pending"].as_bool() && transaction.empty();
+            if (foreign_preview)
+            {
+                update_controls();
+                status.set_text(uncertain ? "The previous request has an uncertain outcome. A preview is pending; waiting for its automatic rollback." :
+                    "A display preview is awaiting confirmation in another window.");
+            } else
+            {
+                uncertain = false;
+                // A refresh can discard only the draft that existed when it
+                // started. Never overwrite typing done while its reply waited.
+                if (serial == edit_serial && (discard || !dirty) && (discard || revision != data["revision"].as_string())) load(data);
+                available = true; update_controls();
+                status.set_text(dirty ? "Unapplied changes retained. Apply checks the current configuration revision." :
+                    "Changes are previewed for 20 seconds. Keep Changes saves them; leaving this page reverts the preview.");
+            }
+        } catch (const std::exception& e)
+        {
+            loading = false; update_controls();
+            error(std::string(e.what()) + " Last observed settings and unapplied edits are retained.");
         }
-        bool recovering = !available;
-        if (discard || revision != data["revision"].as_string()) load(data);
-        available = true; update_controls();
-        if (recovering && !dirty) status.set_text("Changes are previewed for 20 seconds. Keep Changes saves them; closing WCM lets the preview revert.");
-    } catch (const std::exception& e)
+        if (refresh_pending && get_mapped()) refresh();
+    });
+}
+
+void DisplaysPage::refresh_apps()
+{
+    // This optional observation shares the page's single outstanding slot.
+    if (ipc.busy()) return;
+    ipc.send("window-rules/list-views", {}, [this] (WcmIpcResult result)
     {
-        loading = false; available = false; update_controls();
-        error(std::string(e.what()) + "\nDisplays needs the output-control and ipc plugins from the matching Wayfire package.");
-        apply_button.set_sensitive(false);
-    }
+        if (result.error.empty() && result.reply.is_array())
+        {
+            auto selected_app = running_apps.get_active_id();
+            running_apps.remove_all(); std::set<std::string> apps;
+            auto views = result.reply;
+            for (size_t i = 0; i < views.size(); ++i)
+            {
+                wf::json_t view = views[i];
+                if (view["mapped"].as_bool() && view["role"].as_string() == "toplevel")
+                {
+                    auto app = view["app-id"].as_string();
+                    if (!app.empty() && apps.insert(app).second) running_apps.append(app, app);
+                }
+            }
+            if (!running_apps.set_active_id(selected_app)) running_apps.set_active(0);
+        }
+        if (refresh_pending && get_mapped()) refresh();
+    });
 }
 
 void DisplaysPage::load(const wf::json_t& data)
@@ -260,25 +349,11 @@ void DisplaysPage::load(const wf::json_t& data)
                 rule.has_member("scope") && rule["scope"].is_string())
                 append_rule(rule["app_id"].as_string(), rule["scope"].as_string());
         }
-    running_apps.remove_all();
-    try
-    {
-        auto views = request("window-rules/list-views"); std::set<std::string> apps;
-        for (size_t i = 0; i < views.size(); ++i)
-        {
-            wf::json_t view = views[i];
-            if (view["mapped"].as_bool() && view["role"].as_string() == "toplevel")
-            {
-                auto app = view["app-id"].as_string();
-                if (!app.empty() && apps.insert(app).second) running_apps.append(app, app);
-            }
-        }
-        running_apps.set_active(0);
-    } catch (...) {} // Rules remain editable when ipc-rules is disabled.
+    refresh_apps();
     std::istringstream input(get("core/stitch_outputs")); std::string name;
     while (input >> name) if (heads.count(name)) order.push_back(name);
     combined.set_active(get("core/stitch_enabled") == "true");
-    gap.set_value(std::stoi(get("grid/zone_gap"))); shift.set_active(get("move/zone_shift") == "true");
+    gap.set_value(std::stoi(get("grid/zone_gap"))); shift.set_active(get("grid/zone_shift") == "true");
     zone_binding.set_text(get("grid/zone_maximize")); drag_binding.set_text(get("move/activate_zone"));
     update_defaults();
     if (!heads.count(selected)) selected = heads.empty() ? "" : heads.begin()->first;
@@ -334,13 +409,14 @@ void DisplaysPage::update_defaults()
 void DisplaysPage::changed()
 {
     if (loading) return;
+    ++edit_serial;
     set("core/stitch_enabled", combined.get_active() ? "true" : "false");
     set("core/default_output", default_output.get_active_id());
     set("core/window_scope", default_scope.get_active_id());
     set("grid/use_virtual", virtual_binding.get_text()); set("grid/use_physical", physical_binding.get_text());
     set("grid/reset_scope", reset_binding.get_text()); set("grid/next_monitor", next_binding.get_text());
     set("grid/zone_gap", std::to_string(gap.get_value_as_int()));
-    set("move/zone_shift", shift.get_active() ? "true" : "false");
+    set("grid/zone_shift", shift.get_active() ? "true" : "false");
     set("grid/zone_maximize", zone_binding.get_text()); set("move/activate_zone", drag_binding.get_text());
     if (heads.count(selected))
     {
@@ -348,7 +424,10 @@ void DisplaysPage::changed()
         set(pre + "masked", role.get_active_id() == "masked" ? "true" : "false");
         set(pre + "mode", role.get_active_id() == "off" ? "off" : std::string(mode.get_active_id()));
         set(pre + "position", position.get_text());
-        std::ostringstream numeric; numeric << scale.get_value(); set(pre + "scale", numeric.str());
+        if (std::stod(get(pre + "scale")) != scale.get_value())
+        {
+            std::ostringstream numeric; numeric << scale.get_value(); set(pre + "scale", numeric.str());
+        }
         set(pre + "transform", rotation.get_active_id());
         set(pre + "zone_gap", std::to_string(local_gap.get_value_as_int()));
         auto it = std::find(order.begin(), order.end(), selected);
@@ -363,12 +442,14 @@ void DisplaysPage::changed()
 void DisplaysPage::update_controls()
 {
     bool preview = !transaction.empty();
+    bool locked = preview || mutation_pending || foreign_preview || uncertain;
     settings_state.set_visible_child("settings");
     diagram.set_visible(available && settings_tabs.get_current_page() != 3);
-    left.set_sensitive(available && !preview); right.set_sensitive(available && !preview);
-    scope_tab.set_sensitive(available && !preview); refresh_button.set_sensitive(!preview);
-    identify_button.set_sensitive(available && !heads.empty() && !preview);
-    keep_button.set_visible(preview); revert_button.set_visible(preview); apply_button.set_visible(!preview); apply_button.set_sensitive(available && dirty && !preview);
+    left.set_sensitive(available && !locked); right.set_sensitive(available && !locked);
+    scope_tab.set_sensitive(available && !locked); refresh_button.set_sensitive(!preview && !mutation_pending);
+    identify_button.set_sensitive(available && !heads.empty() && !locked);
+    keep_button.set_visible(preview); revert_button.set_visible(preview); apply_button.set_visible(!preview); apply_button.set_sensitive(available && dirty && !locked);
+    keep_button.set_sensitive(!mutation_pending && !uncertain); revert_button.set_sensitive(!mutation_pending);
     bool desktop = role.get_active_id() == "desktop";
     include.set_sensitive(desktop);
     local_gap.set_sensitive(desktop && include.get_active());
@@ -381,30 +462,66 @@ void DisplaysPage::update_controls()
 
 void DisplaysPage::apply()
 {
-    try
+    if (!available || !dirty || mutation_pending || foreign_preview || uncertain || !transaction.empty()) return;
+    ipc.cancel_observation(); refresh_pending = discard_pending = false;
+    wf::json_t options, data;
+    for (auto& [key, value] : draft) if (!original.count(key) || original.at(key) != value) options[key] = value;
+    data["options"] = options; data["revision"] = revision;
+    mutation_pending = true; update_controls(); status.set_text("Waiting for the display preview…");
+    auto started = g_get_monotonic_time();
+    ipc.send("displays/apply", data, [this, started] (WcmIpcResult result)
     {
-        wf::json_t options, data;
-        for (auto& [key, value] : draft) if (!original.count(key) || original.at(key) != value) options[key] = value;
-        data["options"] = options; data["revision"] = revision;
-        auto response = request("displays/apply", data);
-        transaction = response["token"].as_string(); countdown = response["timeout"].as_int();
-        status.set_text("Keep these display settings? They revert automatically in 20 seconds."); update_controls();
-        keep_button.grab_focus();
-    } catch (const std::exception& e) { error(e.what()); }
+        mutation_pending = false;
+        if (!result.error.empty() || !result.reply["token"].is_string() || result.reply["token"].as_string().empty())
+        {
+            uncertain = result.uncertain || result.error.empty();
+            update_controls();
+            error((result.error.empty() ? "Invalid display preview response" : result.error) +
+                (uncertain ? ". Outcome unknown; any unconfirmed preview will revert automatically. Refresh to check." : ""));
+            return;
+        }
+        transaction = result.reply["token"].as_string();
+        countdown = std::max(0, result.reply["timeout"].as_int() - int((g_get_monotonic_time() - started + 999999) / 1000000));
+        if (!get_mapped()) { finish(false); return; }
+        status.set_text("Keep these display settings? They revert automatically after the preview deadline.");
+        update_controls(); keep_button.grab_focus();
+    }, true, [] (WcmIpcResult result)
+    {
+        if (result.reply["token"].is_string() && !result.reply["token"].as_string().empty())
+        {
+            wf::json_t data; data["token"] = result.reply["token"].as_string();
+            wcm_ipc_cleanup("displays/revert", data);
+        }
+    });
 }
 
 void DisplaysPage::finish(bool keep)
 {
-    try
+    if (transaction.empty() || mutation_pending) return;
+    ipc.cancel_observation(); refresh_pending = discard_pending = false;
+    wf::json_t data; data["token"] = transaction;
+    transaction.clear(); mutation_pending = true; update_controls();
+    status.set_text(keep ? "Waiting for display confirmation…" : "Waiting for display rollback…");
+    ipc.send(keep ? "displays/confirm" : "displays/revert", data, [this, keep] (WcmIpcResult result)
     {
-        wf::json_t data; data["token"] = transaction;
-        request(keep ? "displays/confirm" : "displays/revert", data);
-        transaction.clear(); if (keep) saved(); refresh(true);
-        status.set_text(keep ? "Display settings saved." : "Previous display settings restored.");
-    } catch (const std::exception& e)
+        mutation_pending = false;
+        if (!result.error.empty())
+        {
+            uncertain = result.uncertain; update_controls();
+            error(result.error + (uncertain ? ". Outcome unknown; the request was not repeated. Refresh to check." : ""));
+            return;
+        }
+        uncertain = false;
+        if (keep) { dirty = false; saved(); }
+        if (get_mapped()) refresh(keep);
+        update_controls();
+        status.set_text(keep ? "Display settings saved." : "Previous display settings restored; unapplied edits retained.");
+    }, true, [keep, data] (WcmIpcResult result)
     {
-        transaction.clear(); refresh(true); error(e.what());
-    }
+        // An uncertain confirmation may still own a preview. A revert is a
+        // distinct cleanup action, scoped to its token, never a confirm retry.
+        if (keep && !result.error.empty()) wcm_ipc_cleanup("displays/revert", data);
+    });
 }
 
 bool DisplaysPage::draw(const Cairo::RefPtr<Cairo::Context>& cr)
@@ -444,10 +561,15 @@ bool DisplaysPage::draw(const Cairo::RefPtr<Cairo::Context>& cr)
 
 void DisplaysPage::identify()
 {
-    try
+    if (ipc.busy() || mutation_pending) return;
+    identifiers.clear(); identify_timer.disconnect();
+    status.set_text("Waiting to identify displays…");
+    ipc.send("displays/get", {}, [this] (WcmIpcResult result)
     {
-        identifiers.clear(); identify_timer.disconnect();
-        auto live = request("displays/get"); wf::json_t desktops = live["desktops"];
+        try
+        {
+            if (!result.error.empty()) throw std::runtime_error(result.error);
+            wf::json_t desktops = result.reply["desktops"];
         auto display = Gdk::Display::get_default();
         for (size_t i = 0; i < desktops.size(); ++i)
         {
@@ -483,7 +605,9 @@ void DisplaysPage::identify()
             }
         }
         identify_timer = Glib::signal_timeout().connect([this] { identifiers.clear(); return false; }, 3000);
-    } catch (const std::exception& e) { error(e.what()); }
+        } catch (const std::exception& e) { error(e.what()); }
+        if (refresh_pending && get_mapped()) refresh();
+    });
 }
 
 
diff --git a/src/displays.hpp b/src/displays.hpp
index dc5664b..692c6fe 100644
--- a/src/displays.hpp
+++ b/src/displays.hpp
@@ -1,5 +1,6 @@
 #pragma once
 #include <gtkmm.h>
+#include "ipc.hpp"
 #include <wayfire/nonstd/json.hpp>
 #include <map>
 #include <vector>
@@ -48,12 +49,17 @@ class DisplaysPage : public Gtk::Box
     wf::json_t state;
     std::string revision, transaction, selected, config_file;
     bool loading = false, dirty = false, available = false;
+    bool refresh_pending = false, discard_pending = false, mutation_pending = false;
+    bool foreign_preview = false, uncertain = false;
+    uint64_t edit_serial = 0, discard_serial = 0;
+    WcmIpcClient ipc;
     int countdown = 0;
     sigc::connection timer, identify_timer;
     std::vector<std::unique_ptr<Gtk::Window>> identifiers;
     std::function<void()> saved, show_shell, show_zones;
 
-    wf::json_t request(const std::string& method, wf::json_t data = {});
+    void leave();
+    void refresh_apps();
     void refresh(bool discard = false);
     void load(const wf::json_t& data);
     void select_monitor();
diff --git a/src/ipc.cpp b/src/ipc.cpp
new file mode 100644
index 0000000..9414de9
--- /dev/null
+++ b/src/ipc.cpp
@@ -0,0 +1,198 @@
+#include "ipc.hpp"
+#include <gio/gio.h>
+#include <glib-unix.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <endian.h>
+#include <cstring>
+#include <cerrno>
+#include <algorithm>
+#include <stdexcept>
+
+namespace
+{
+constexpr size_t max_reply = 4 * 1024 * 1024;
+constexpr unsigned deadline_ms = 3000;
+
+class Request : public std::enable_shared_from_this<Request>
+{
+    int fd = -1;
+    guint io = 0, timeout = 0, initial = 0;
+    GApplication *application = nullptr;
+    std::string path, output, input;
+    size_t sent = 0, received = 0;
+    uint32_t length = 0;
+    bool connecting = false, header = true, done = false;
+    gint64 deadline = 0;
+    WcmIpcClient::Callback callback;
+
+    using Ref = std::shared_ptr<Request>;
+    static void release(gpointer p) { delete static_cast<Ref*>(p); }
+    static void remove(guint& id) { if (id) { auto old = id; id = 0; g_source_remove(old); } }
+    void watch(GIOCondition condition)
+    {
+        remove(io);
+        io = g_unix_fd_add_full(G_PRIORITY_DEFAULT, fd, condition, [](int, GIOCondition, gpointer p) -> gboolean
+        {
+            auto self = *static_cast<Ref*>(p);
+            try { self->advance(); }
+            catch (const std::exception& e) { self->finish({{}, e.what(), self->sent != 0}); }
+            return G_SOURCE_CONTINUE;
+        }, new Ref(shared_from_this()), release);
+    }
+    void connect_socket()
+    {
+        if (path.empty()) throw std::runtime_error("Open WCM from the running Wayfire session (WAYFIRE_SOCKET is missing).");
+        sockaddr_un addr{}; addr.sun_family = AF_UNIX;
+        if (path.size() >= sizeof addr.sun_path) throw std::runtime_error("Wayfire socket path is too long");
+        std::strcpy(addr.sun_path, path.c_str());
+        fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
+        if (fd < 0) throw std::runtime_error("Cannot open Wayfire socket");
+        if (connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr))
+        {
+            // AF_UNIX EAGAIN means a full backlog, not a pending connection.
+            if (errno != EINPROGRESS) throw std::runtime_error("Cannot connect to Wayfire");
+            connecting = true;
+        }
+        watch(GIOCondition(G_IO_OUT | G_IO_ERR | G_IO_HUP));
+    }
+    void advance()
+    {
+        if (g_get_monotonic_time() >= deadline) throw std::runtime_error("Wayfire request timed out");
+        if (connecting)
+        {
+            int error = 0; socklen_t size = sizeof error;
+            if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &size) || error)
+                throw std::runtime_error("Cannot connect to Wayfire");
+            connecting = false;
+        }
+        if (!sent)
+        {
+            ucred peer{}; socklen_t size = sizeof peer;
+            if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &peer, &size) || peer.uid != getuid())
+                throw std::runtime_error("Wayfire socket belongs to another user");
+        }
+        size_t budget = 64 * 1024; // Yield between chunks, even for a fast peer.
+        while (sent < output.size() && budget)
+        {
+            auto n = send(fd, output.data() + sent, std::min(output.size() - sent, budget), MSG_NOSIGNAL);
+            if (n < 0 && errno == EINTR) continue;
+            if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return;
+            if (n <= 0) throw std::runtime_error("Wayfire request failed");
+            sent += n; budget -= n;
+        }
+        if (sent < output.size()) return;
+        // Replace the write watch once; the read watch must not spin on OUT.
+        if (input.empty() && header && !received)
+        {
+            input.resize(sizeof length);
+            watch(GIOCondition(G_IO_IN | G_IO_ERR | G_IO_HUP));
+        }
+        while (budget)
+        {
+            auto n = recv(fd, input.data() + received, std::min(input.size() - received, budget), 0);
+            if (n < 0 && errno == EINTR) continue;
+            if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return;
+            if (n <= 0) throw std::runtime_error("Wayfire disconnected before replying");
+            received += n; budget -= n;
+            if (received != input.size()) continue;
+            if (header)
+            {
+                std::memcpy(&length, input.data(), sizeof length); length = le32toh(length);
+                if (!length || length > max_reply) throw std::runtime_error("Invalid Wayfire response size");
+                header = false; input.resize(length); received = 0;
+            } else
+            {
+                wf::json_t reply;
+                if (wf::json_t::parse_string(input, reply) || (!reply.is_object() && !reply.is_array()))
+                    throw std::runtime_error("Invalid Wayfire response");
+                if (reply.has_member("error"))
+                {
+                    if (!reply["error"].is_string()) throw std::runtime_error("Invalid Wayfire error response");
+                    finish({reply, reply["error"].as_string(), false});
+                } else finish({reply, {}, false});
+                return;
+            }
+        }
+    }
+    void finish(WcmIpcResult result)
+    {
+        if (done) return;
+        auto self = shared_from_this();
+        done = true; remove(initial); remove(io); remove(timeout);
+        if (fd >= 0) { close(fd); fd = -1; }
+        auto completion = std::move(callback);
+        try { if (completion) completion(std::move(result)); }
+        catch (const std::exception& e) { g_warning("WCM IPC completion: %s", e.what()); }
+        if (application) { g_application_release(application); g_object_unref(application); application = nullptr; }
+    }
+  public:
+    static Ref start(const std::string& method, wf::json_t data, WcmIpcClient::Callback callback, bool mutation)
+    {
+        auto request = std::make_shared<Request>();
+        request->callback = std::move(callback);
+        if (auto path = g_getenv("WAYFIRE_SOCKET")) request->path = path;
+        wf::json_t message; message["method"] = method; message["data"] = data;
+        auto bytes = message.serialize();
+        uint32_t length = htole32(bytes.size());
+        request->output.assign(reinterpret_cast<char*>(&length), sizeof length); request->output += bytes;
+        if (mutation && g_application_get_default())
+        {
+            request->application = G_APPLICATION(g_object_ref(g_application_get_default()));
+            g_application_hold(request->application);
+        }
+        request->deadline = g_get_monotonic_time() + deadline_ms * 1000;
+        request->timeout = g_timeout_add_full(G_PRIORITY_DEFAULT, deadline_ms, [](gpointer p) -> gboolean
+        {
+            auto self = *static_cast<Ref*>(p); self->timeout = 0;
+            self->finish({{}, "Wayfire request timed out", self->sent != 0}); return G_SOURCE_REMOVE;
+        }, new Ref(request), release);
+        request->initial = g_idle_add_full(G_PRIORITY_DEFAULT, [](gpointer p) -> gboolean
+        {
+            auto self = *static_cast<Ref*>(p); self->initial = 0;
+            try { self->connect_socket(); }
+            catch (const std::exception& e) { self->finish({{}, e.what(), false}); }
+            return G_SOURCE_REMOVE;
+        }, new Ref(request), release);
+        return request;
+    }
+    void cancel() { callback = {}; finish({}); }
+};
+}
+
+struct WcmIpcClient::State
+{
+    std::shared_ptr<Request> request;
+    bool mutation = false;
+};
+WcmIpcClient::WcmIpcClient() : state(std::make_shared<State>()) {}
+WcmIpcClient::~WcmIpcClient() { cancel_observation(); }
+bool WcmIpcClient::busy() const { return bool(state->request); }
+void WcmIpcClient::cancel_observation()
+{
+    if (state->request && !state->mutation) { state->request->cancel(); state->request.reset(); }
+}
+bool WcmIpcClient::send(const std::string& method, wf::json_t data, Callback callback, bool mutation, Callback orphan)
+{
+    if (busy()) return false;
+    state->mutation = mutation;
+    std::weak_ptr<State> weak = state;
+    state->request = Request::start(method, data,
+        [weak, callback = std::move(callback), orphan = std::move(orphan)] (WcmIpcResult result)
+        {
+            if (auto current = weak.lock())
+            {
+                current->request.reset();
+                if (callback) callback(std::move(result));
+            } else if (orphan) orphan(std::move(result));
+        }, mutation);
+    return true;
+}
+void wcm_ipc_cleanup(const std::string& method, wf::json_t data)
+{
+    Request::start(method, data, [](WcmIpcResult result)
+    {
+        if (!result.error.empty()) g_warning("WCM cleanup: %s", result.error.c_str());
+    }, true);
+}
diff --git a/src/ipc.hpp b/src/ipc.hpp
index dc6acec..040292f 100644
--- a/src/ipc.hpp
+++ b/src/ipc.hpp
@@ -1,59 +1,37 @@
 #pragma once
 #include <wayfire/nonstd/json.hpp>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <unistd.h>
-#include <endian.h>
-#include <cstring>
-#include <cerrno>
-#include <stdexcept>
+#include <functional>
+#include <memory>
+#include <string>
 
-inline wf::json_t wcm_ipc_request(const std::string& method, wf::json_t data = {})
+struct WcmIpcResult
 {
-    auto path = getenv("WAYFIRE_SOCKET");
-    if (!path || !*path) throw std::runtime_error("Open WCM from the running Wayfire session (WAYFIRE_SOCKET is missing).");
-    sockaddr_un addr{}; addr.sun_family = AF_UNIX;
-    if (strlen(path) >= sizeof addr.sun_path) throw std::runtime_error("Wayfire socket path is too long");
-    strcpy(addr.sun_path, path);
-    int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
-    if (fd < 0) throw std::runtime_error("Cannot open Wayfire socket");
-    try
-    {
-        timeval timeout{3, 0};
-        setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
-        setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout);
-        if (connect(fd, reinterpret_cast<sockaddr*>(&addr), sizeof addr)) throw std::runtime_error("Cannot connect to Wayfire");
-        ucred peer{}; socklen_t size = sizeof peer;
-        if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &peer, &size) || peer.uid != getuid()) throw std::runtime_error("Wayfire socket belongs to another user");
-        wf::json_t message; message["method"] = method; message["data"] = data;
-        auto bytes = message.serialize(); uint32_t length = htole32(bytes.size());
-        auto write_all = [&] (const char *p, size_t n)
-        {
-            while (n)
-            {
-                auto r = send(fd, p, n, MSG_NOSIGNAL);
-                if (r < 0 && errno == EINTR) continue;
-                if (r <= 0) throw std::runtime_error("Wayfire request failed");
-                p += r; n -= r;
-            }
-        };
-        auto read_all = [&] (char *p, size_t n)
-        {
-            while (n)
-            {
-                auto r = recv(fd, p, n, 0);
-                if (r < 0 && errno == EINTR) continue;
-                if (r <= 0) throw std::runtime_error("Wayfire did not respond");
-                p += r; n -= r;
-            }
-        };
-        write_all(reinterpret_cast<char*>(&length), sizeof length); write_all(bytes.data(), bytes.size());
-        read_all(reinterpret_cast<char*>(&length), sizeof length); length = le32toh(length);
-        if (length > 4 * 1024 * 1024) throw std::runtime_error("Invalid Wayfire response size");
-        bytes.resize(length); read_all(bytes.data(), length);
-        wf::json_t reply;
-        if (wf::json_t::parse_string(bytes, reply)) throw std::runtime_error("Invalid Wayfire response");
-        if (reply.has_member("error")) throw std::runtime_error(reply["error"].as_string());
-        close(fd); return reply;
-    } catch (...) { close(fd); throw; }
-}
+    wf::json_t reply;
+    std::string error;
+    // A transport failure after sending bytes cannot establish mutation outcome.
+    bool uncertain = false;
+};
+
+// Main-context-only channel. One request at a time; page code coalesces reads.
+// Destruction cancels observations. Mutations finish without touching the page,
+// then run a value-only orphan callback (for preview/overlay cleanup).
+class WcmIpcClient
+{
+  public:
+    using Callback = std::function<void(WcmIpcResult)>;
+    WcmIpcClient();
+    ~WcmIpcClient();
+    WcmIpcClient(const WcmIpcClient&) = delete;
+    WcmIpcClient& operator=(const WcmIpcClient&) = delete;
+    bool busy() const;
+    bool send(const std::string& method, wf::json_t data, Callback callback,
+        bool mutation = false, Callback orphan = {});
+    void cancel_observation();
+  private:
+    struct State;
+    std::shared_ptr<State> state;
+};
+
+// A single bounded, best-effort cleanup, never retried. Holds the application
+// while its window closes so cleanup can finish without blocking GTK.
+void wcm_ipc_cleanup(const std::string& method, wf::json_t data);
diff --git a/src/meson.build b/src/meson.build
index 9eebcf2..de9b8ff 100644
--- a/src/meson.build
+++ b/src/meson.build
@@ -10,7 +10,7 @@ layer_shell = dependency('gtk-layer-shell-0')
 dep_list = [xml, gtkmm, wf_config, wf_protos, evdev, xkbregistry, libintl, libfmt, wf_json, layer_shell,
   dependency('nlohmann_json'), dependency('threads')]
 
-sources = files('main.cpp', 'metadata.cpp', 'wcm.cpp', 'utils.cpp', 'displays.cpp', 'backgrounds.cpp', 'move-snap.cpp', 'vendor/wf-json.cpp')
+sources = files('main.cpp', 'metadata.cpp', 'wcm.cpp', 'utils.cpp', 'ipc.cpp', 'displays.cpp', 'backgrounds.cpp', 'move-snap.cpp', 'vendor/wf-json.cpp')
 
 executable(meson.project_name(), sources,
                      install : true,
diff --git a/src/metadata.hpp b/src/metadata.hpp
index 18056b2..3585fb2 100644
--- a/src/metadata.hpp
+++ b/src/metadata.hpp
@@ -66,7 +66,7 @@ struct var_data
     double min;
     double max;
     double precision;
-    hint_type hints;
+    hint_type hints = static_cast<hint_type>(0);
 };
 
 using opt_data = std::variant<int, std::string, double>;
diff --git a/src/move-snap.cpp b/src/move-snap.cpp
index 1eccdef..6e2e305 100644
--- a/src/move-snap.cpp
+++ b/src/move-snap.cpp
@@ -1,5 +1,6 @@
 #include "move-snap.hpp"
 #include "ipc.hpp"
+#include <nlohmann/json.hpp>
 #include <filesystem>
 #include <algorithm>
 #include <cmath>
@@ -7,6 +8,27 @@
 
 namespace
 {
+void validate_snap_snapshot(const wf::json_t& wire)
+{
+    auto data = nlohmann::json::parse(wire.serialize());
+    data.at("enabled").get<bool>();
+    for (auto key : {"edge", "corner", "delay"}) data.at(key).get<int>();
+    auto rectangle = [] (const nlohmann::json& r)
+    {
+        for (auto key : {"x", "y", "width", "height"})
+            if (!std::isfinite(r.at(key).get<double>())) throw std::runtime_error("Invalid snap region geometry");
+    };
+    if (!data.at("monitors").is_array()) throw std::runtime_error("Invalid snap monitor list");
+    for (auto& monitor : data.at("monitors"))
+    {
+        monitor.at("name").get<std::string>(); rectangle(monitor.at("geometry"));
+        if (!monitor.at("regions").is_array()) throw std::runtime_error("Invalid snap regions");
+        for (auto& region : monitor.at("regions"))
+        {
+            region.at("slot").get<std::string>(); rectangle(region.at("geometry")); rectangle(region.at("target"));
+        }
+    }
+}
 struct Rect { double x, y, w, h; };
 Rect rect(const wf::json_t& j)
 {
@@ -69,37 +91,62 @@ MoveSnapPage::MoveSnapPage(const std::string& config, std::function<void(bool,in
     delay.signal_value_changed().connect(sigc::mem_fun(*this, &MoveSnapPage::changed));
     scope.signal_changed().connect([this] { if (!loading) { hovered.clear(); target = {}; update(); } });
     monitor.signal_changed().connect([this] { if (loading) return; hovered.clear(); target = {}; diagram.queue_draw(); });
-    overlay.signal_toggled().connect([this] { if (!loading) update(); });
+    overlay.signal_toggled().connect([this] { if (!loading) { if (overlay.get_active()) update(); else stop_overlay(); } });
     refresh.signal_clicked().connect([this] { update(); });
+    enabled.set_sensitive(false); edge.set_sensitive(false); corner.set_sensitive(false); delay.set_sensitive(false); overlay.set_sensitive(false);
     signal_map().connect([this] { update(); });
-    signal_unmap().connect([this] { stop_overlay(); });
+    signal_unmap().connect([this] { refresh_pending = false; ipc.cancel_observation(); stop_overlay(); });
     poll = Glib::signal_timeout().connect([this] { if (get_mapped() && !delayed_save.connected()) update(); return true; }, 1000);
 }
 
 MoveSnapPage::~MoveSnapPage()
 {
-    delayed_save.disconnect(); poll.disconnect(); stop_overlay();
+    delayed_save.disconnect(); poll.disconnect(); ipc.cancel_observation(); stop_overlay();
 }
 
 void MoveSnapPage::stop_overlay()
 {
-    if (!overlay.get_active()) return;
     loading = true; overlay.set_active(false); loading = false;
-    try { wf::json_t request; request["owner"] = owner; request["visible"] = false; wcm_ipc_request("move/snap-regions",request); } catch (...) {}
+    if (!overlay_owned && !cleanup_pending) return;
+    cleanup_pending = true;
+    if (ipc.busy()) return; // Hide only after a pending show has completed.
+    cleanup_pending = false; overlay_owned = false;
+    wf::json_t data; data["owner"] = owner; data["visible"] = false;
+    ipc.send("move/snap-regions", data, [this] (WcmIpcResult result)
+    {
+        if (!result.error.empty()) status.set_text(result.error + "; the snap overlay lease will expire.");
+        if (refresh_pending && get_mapped()) { refresh_pending = false; update(); }
+    }, true);
 }
 
 void MoveSnapPage::update()
 {
-    try
+    if (!get_mapped()) return;
+    if (ipc.busy()) { refresh_pending = true; return; }
+    if (cleanup_pending) { stop_overlay(); return; }
+    refresh_pending = false;
+    wf::json_t request; auto requested_scope = scope.get_active_id().raw();
+    request["scope"] = requested_scope;
+    bool visible = overlay.get_active();
+    // Ordinary polling is read-only. Showing zones explicitly renews their
+    // compositor lease; a failed renewal turns the toggle off, never retries it.
+    if (visible) { request["owner"] = owner; request["visible"] = true; overlay_owned = true; }
+    auto serial = edit_serial;
+    status.set_text("Waiting for snap zones…");
+    ipc.send("move/snap-regions", request, [this, serial, requested_scope] (WcmIpcResult result)
     {
-        wf::json_t request; request["scope"] = std::string(scope.get_active_id());
-        request["owner"] = owner; request["visible"] = overlay.get_active();
-        auto reply = wcm_ipc_request("move/snap-regions",request);
+        if (cleanup_pending || !get_mapped()) { stop_overlay(); return; }
+        try
+        {
+            if (!result.error.empty()) throw std::runtime_error(result.error);
+            auto reply = result.reply;
+            if (requested_scope != scope.get_active_id()) { update(); return; }
         if (reply["version"].as_int() != 1) throw std::runtime_error("This compositor's snap-zone interface is not supported.");
         if (std::filesystem::weakly_canonical(reply["config_file"].as_string()) != std::filesystem::weakly_canonical(config_file))
             throw std::runtime_error("Open WCM with the running session's configuration to edit snap zones.");
+        validate_snap_snapshot(reply);
         loading = true;
-        if (!delayed_save.connected()) { enabled.set_active(reply["enabled"].as_bool()); edge.set_value(reply["edge"].as_int()); corner.set_value(reply["corner"].as_int()); delay.set_value(reply["delay"].as_int()); }
+        if (serial == edit_serial && !delayed_save.connected()) { enabled.set_active(reply["enabled"].as_bool()); edge.set_value(reply["edge"].as_int()); corner.set_value(reply["corner"].as_int()); delay.set_value(reply["delay"].as_int()); }
         std::vector<std::string> names; auto monitors = reply["monitors"];
         for (size_t i = 0; i < monitors.size(); ++i) names.push_back(monitors[i]["name"].as_string());
         if (names != monitor_names)
@@ -114,17 +161,26 @@ void MoveSnapPage::update()
         status.set_text(reply["enabled"].as_bool() ? "Changes save immediately. Regions include panel space and monitor gaps; select a monitor for a closer view." :
             "Enable Snap to activate drag snapping.");
         diagram.queue_draw();
-    } catch (const std::exception& e)
+        } catch (const std::exception& e)
+        {
+            loading = false; stop_overlay();
+            enabled.set_sensitive(available); edge.set_sensitive(available);
+            corner.set_sensitive(available); delay.set_sensitive(available); overlay.set_sensitive(available);
+            status.set_text(std::string(e.what()) + " Last observed zones and edits are retained. Enable Move and IPC in the running Wayfire session.");
+            diagram.queue_draw();
+        }
+        if (refresh_pending && get_mapped() && !ipc.busy()) { refresh_pending = false; update(); }
+    }, visible, [owner = owner] (WcmIpcResult)
     {
-        loading = false; available = false; stop_overlay();
-        enabled.set_sensitive(false); edge.set_sensitive(false); corner.set_sensitive(false); delay.set_sensitive(false); overlay.set_sensitive(false);
-        status.set_text(std::string(e.what()) + " Enable Move and IPC in the running Wayfire session."); diagram.queue_draw();
-    }
+        wf::json_t data; data["owner"] = owner; data["visible"] = false;
+        wcm_ipc_cleanup("move/snap-regions", data);
+    });
 }
 
 void MoveSnapPage::changed()
 {
     if (loading || !available) return;
+    ++edit_serial;
     delayed_save.disconnect();
     delayed_save = Glib::signal_timeout().connect([this]
     {
diff --git a/src/move-snap.hpp b/src/move-snap.hpp
index 239076f..26e88e4 100644
--- a/src/move-snap.hpp
+++ b/src/move-snap.hpp
@@ -1,5 +1,6 @@
 #pragma once
 #include <gtkmm.h>
+#include "ipc.hpp"
 #include <wayfire/nonstd/json.hpp>
 
 class MoveSnapPage : public Gtk::Box
@@ -19,6 +20,9 @@ class MoveSnapPage : public Gtk::Box
     std::function<void(bool, int, int, int)> save;
     sigc::connection poll, delayed_save;
     bool loading = false, available = false;
+    bool refresh_pending = false, cleanup_pending = false, overlay_owned = false;
+    uint64_t edit_serial = 0;
+    WcmIpcClient ipc;
     double zoom = 1, dx = 0, dy = 0;
     wf::json_t target;
     void update();
diff --git a/src/wcm.cpp b/src/wcm.cpp
index 1327c2b..ed998c0 100644
--- a/src/wcm.cpp
+++ b/src/wcm.cpp
@@ -1517,11 +1517,12 @@ void WCM::set_plugin_enabled(Plugin *plugin, bool enabled)
 
 void WCM::create_main_layout()
 {
-    window->signal_key_press_event().connect([] (GdkEventKey *event)
+    window->signal_key_press_event().connect([this] (GdkEventKey *event)
     {
         if (event->state & GDK_CONTROL_MASK && (event->keyval == GDK_KEY_q))
         {
-            std::exit(0);
+            window->close();
+            return true;
         }
 
         return false;
@@ -1550,7 +1551,7 @@ void WCM::create_main_layout()
     main_left_panel_layout.pack_start(search_entry, false, false);
 
     close_button.property_margin().set_value(10);
-    close_button.signal_clicked().connect([] { std::exit(0); });
+    close_button.signal_clicked().connect([this] { window->close(); });
     main_left_panel_layout.pack_end(close_button, false, false);
 
     output_config_button.property_margin().set_value(10);
diff --git a/src/wcm.hpp b/src/wcm.hpp
index ca53963..c7f5eb1 100644
--- a/src/wcm.hpp
+++ b/src/wcm.hpp
@@ -151,6 +151,7 @@ class OptionWidget : public Gtk::Box
     std::vector<std::unique_ptr<Gtk::Widget>> widgets;
     Gtk::Button reset_button;
     sigc::trackable tracker;
+    WcmIpcClient discovery;
 
     guint int_sb_handle;
     guint animate_sb_handle;