-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow-toggle.c
More file actions
executable file
·2180 lines (2084 loc) · 101 KB
/
Copy pathwindow-toggle.c
File metadata and controls
executable file
·2180 lines (2084 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Window Toggle - Main program
* Supports configure mode and run mode
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <signal.h>
#include <X11/keysymdef.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include "config.h"
#include "window-manager.h"
#include "daemon.h"
#include "ipc.h"
#include "app-binding.h"
/* Forward declaration */
void free_config(Config *config);
static volatile sig_atomic_t grab_timeout = 0;
void configure_mode_with_path(const char *config_path);
void run_mode_with_path(const char *config_path, const char *key_param);
void clean_mode_with_path(const char *config_path);
void start_mode_with_path(const char *config_path);
void show_config(const char *config_path);
static int _show_fx_num(const char *k) {
if (!k || k[0] != 'F') return 99;
int n = 0;
for (const char *p = k + 1; *p; p++) {
if (*p < '0' || *p > '9') return 99;
n = n * 10 + (*p - '0');
}
return n;
}
static int _show_binding_cmp(const void *a, const void *b) {
const AppBinding *A = a, *B = b;
/* 按 F 键数字升序主排序 (F8 在 F12 前面)。同 Fx 按 cmd 字典序稳定 fallback. */
int ka = _show_fx_num(A->key), kb = _show_fx_num(B->key);
if (ka != kb) return ka - kb;
int r = strcmp(A->cmd ? A->cmd : "", B->cmd ? B->cmd : "");
if (r != 0) return r;
return 0;
}
void bind_app_mode_with_path(const char *config_path, const char *key, const char *cmd, const char *wm_class);
void unbind_app_mode_with_path(const char *config_path, const char *key);
void show_app_mode_with_path(const char *config_path);
void run_app_mode_with_path(const char *config_path, const char *key);
int find_next_slot_id(const char *config_path);
/* Get the executable path dynamically */
static int silent_xerror_handler(Display *dpy, XErrorEvent *e) { (void)dpy; (void)e; return 0; }
static void get_exec_path(char *buf, size_t bufsize) {
ssize_t len = readlink("/proc/self/exe", buf, bufsize - 1);
if (len != -1) {
buf[len] = '\0';
} else {
/* Fallback: use argv[0] */
snprintf(buf, bufsize, "window-toggle");
}
}
/* List of window classes to hide from configuration */
static const char *hidden_classes[] = {
"Gjs", /* Desktop Icons */
NULL
};
/* Color codes for output */
#define COLOR_RESET "\033[0m"
#define COLOR_BOLD "\033[1m"
#define COLOR_RED "\033[31m"
#define COLOR_GREEN "\033[32m"
#define COLOR_YELLOW "\033[33m"
#define COLOR_BLUE "\033[34m"
#define COLOR_MAGENTA "\033[35m"
#define COLOR_CYAN "\033[36m"
#define COLOR_GRAY "\033[90m"
#define COLOR_LIGHT_RED "\033[91m"
#define COLOR_LIGHT_GREEN "\033[92m"
#define COLOR_LIGHT_YELLOW "\033[93m"
#define COLOR_LIGHT_BLUE "\033[94m"
#define COLOR_LIGHT_MAGENTA "\033[95m"
#define COLOR_LIGHT_CYAN "\033[96m"
void grab_alarm_handler(int sig) {
grab_timeout = 1;
}
void configure_mode() {
configure_mode_with_path(CONFIG_PATH);
}
void configure_mode_with_path(const char *config_path) {
fprintf(stderr, COLOR_BOLD COLOR_CYAN "=== Window Toggle Configuration ===" COLOR_RESET "\n");
/* Check if config file exists */
int is_first_config = !config_exists(config_path);
if (is_first_config) {
fprintf(stderr, COLOR_GREEN "Creating new configuration..." COLOR_RESET "\n");
} else {
fprintf(stderr, COLOR_GREEN "Adding new shortcut to existing configuration..." COLOR_RESET "\n");
}
/* Step 1: Configure hotkey */
fprintf(stderr, "\n" COLOR_BOLD COLOR_YELLOW "Step 1: Press your desired hotkey combination" COLOR_RESET "\n");
fprintf(stderr, "Recommended: Press " COLOR_BOLD "Ctrl+Alt+F12" COLOR_RESET " or " COLOR_BOLD "Super+F2" COLOR_RESET "\n");
fprintf(stderr, "Also supported: " COLOR_BOLD "F1-F12" COLOR_RESET " alone (no modifier required)\n");
fprintf(stderr, "Or press any key with Ctrl+Alt or Super modifier...\n");
Display *display = XOpenDisplay(NULL);
if (!display) {
fprintf(stderr, COLOR_RED "Failed to open X display" COLOR_RESET "\n");
return;
}
/* Initialize XKB */
int xkb_event_base, xkb_error_base;
if (!XkbQueryExtension(display, NULL, &xkb_event_base, &xkb_error_base, NULL, NULL)) {
fprintf(stderr, COLOR_RED "XKB extension not available" COLOR_RESET "\n");
XCloseDisplay(display);
return;
}
fprintf(stderr, "Waiting for hotkey... (Press Ctrl+Alt+F12 or your combination)\n");
fprintf(stderr, "Press ESC to cancel\n");
fprintf(stderr, "Auto-timeout in 10 seconds if no input\n");
fflush(stderr);
/* Set up signal handler for grab timeout */
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = grab_alarm_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGALRM, &sa, NULL);
/* Try to grab keyboard with timeout protection */
Window root = DefaultRootWindow(display);
int grab_status;
int grab_succeeded = 0;
fprintf(stderr, "Attempting to grab keyboard (will timeout in 2 seconds if frozen)...\n");
fflush(stderr);
/* Set alarm for 2 seconds */
alarm(2);
grab_status = XGrabKeyboard(display, root, True, GrabModeAsync, GrabModeAsync, CurrentTime);
alarm(0); /* Cancel alarm */
if (grab_status == GrabSuccess) {
fprintf(stderr, "Keyboard grabbed successfully! Press your hotkey now...\n");
fflush(stderr);
grab_succeeded = 1;
} else {
fprintf(stderr, "Could not grab keyboard (status=%d). Using fallback method.\n", grab_status);
fprintf(stderr, "Falling back to root window event listening.\n");
fflush(stderr);
XSelectInput(display, root, KeyPressMask | KeyReleaseMask);
}
char selected_key[64] = "F12";
int have_hotkey = 0;
int detected_modifiers = 0; /* 0 = none, 1 = Ctrl+Alt, 2 = Super */
int timeout_counter = 0;
const int MAX_TIMEOUT = 1000; /* 10 seconds at 100ms intervals */
while (!have_hotkey && timeout_counter < MAX_TIMEOUT) {
XEvent event;
/* Use a timeout to avoid infinite blocking */
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100000; /* 100ms */
int fd = ConnectionNumber(display);
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
int ret = select(fd + 1, &fds, NULL, NULL, &tv);
if (ret > 0 && FD_ISSET(fd, &fds)) {
XNextEvent(display, &event);
} else {
/* Timeout occurred */
timeout_counter++;
continue;
}
if (event.type != KeyPress) {
continue;
}
if (event.type == KeyPress) {
/* Get the keycode */
KeyCode keycode = event.xkey.keycode;
/* Try both XKB and standard X11 keysym conversion */
KeySym keysym = XKeycodeToKeysym(display, keycode, 0);
if (keysym == NoSymbol) {
keysym = XkbKeycodeToKeysym(display, keycode, 0, 0);
}
/* Check for ESC key (using hex value) */
if (keysym == 0xff1b) { /* XK_Escape = 0xff1b */
fprintf(stderr, "Configuration cancelled\n");
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
XCloseDisplay(display);
return;
}
/* Check for Fx keys first (works with or without modifiers) */
int is_f_key = (keysym >= 0xffbe && keysym <= 0xffc9);
if (is_f_key) {
int f_num = (int)(keysym - 0xffbe + 1);
snprintf(selected_key, sizeof(selected_key), "F%d", f_num);
/* Determine which modifiers were used.
* 0=none, 1=Ctrl+Alt, 2=Super, 3=Ctrl, 4=Ctrl+Shift */
int has_ctrl = (event.xkey.state & ControlMask);
int has_alt = (event.xkey.state & Mod1Mask);
int has_super= (event.xkey.state & Mod4Mask);
int has_shift= (event.xkey.state & ShiftMask);
int is_ctrl_alt = has_ctrl && has_alt;
int is_ctrl_shift = has_ctrl && has_shift && !has_alt && !has_super;
int is_ctrl_only = has_ctrl && !has_alt && !has_super && !has_shift;
int is_super = has_super;
char modifier_str[64] = "";
if (is_ctrl_alt) {
strcpy(modifier_str, "Ctrl+Alt");
detected_modifiers = 1;
} else if (is_ctrl_shift) {
strcpy(modifier_str, "Ctrl+Shift");
detected_modifiers = 4;
} else if (is_ctrl_only) {
strcpy(modifier_str, "Ctrl");
detected_modifiers = 3;
} else if (is_super) {
strcpy(modifier_str, "Super");
detected_modifiers = 2;
} else {
/* No modifiers - Fx key alone */
strcpy(modifier_str, "(none)");
detected_modifiers = 0;
}
fprintf(stderr, "\nHotkey detected: %s+%s\n", modifier_str, selected_key);
have_hotkey = 1;
/* CRITICAL: Release keyboard grab before window selection */
if (grab_succeeded) {
fprintf(stderr, "Releasing keyboard grab for window selection...\n");
fflush(stderr);
XUngrabKeyboard(display, CurrentTime);
grab_succeeded = 0;
}
}
/* Check for other keys only with modifiers (Tab, Return, Space, 0-9, A-Z) */
else if (event.xkey.state & (ControlMask | Mod1Mask | Mod4Mask)) {
/* Determine which modifiers were used */
char modifier_str[64] = "";
int has_ctrl = (event.xkey.state & ControlMask);
int has_alt = (event.xkey.state & Mod1Mask);
int has_super= (event.xkey.state & Mod4Mask);
int has_shift= (event.xkey.state & ShiftMask);
int is_ctrl_alt = has_ctrl && has_alt;
int is_ctrl_shift = has_ctrl && has_shift && !has_alt && !has_super;
int is_ctrl_only = has_ctrl && !has_alt && !has_super && !has_shift;
if (is_ctrl_alt) {
strcpy(modifier_str, "Ctrl+Alt");
detected_modifiers = 1;
} else if (is_ctrl_shift) {
strcpy(modifier_str, "Ctrl+Shift");
detected_modifiers = 4;
} else if (is_ctrl_only) {
strcpy(modifier_str, "Ctrl");
detected_modifiers = 3;
} else if (has_super) {
strcpy(modifier_str, "Super");
detected_modifiers = 2;
}
/* Determine the key based on keysym value */
strcpy(selected_key, "Unknown");
if (keysym == 0xff09) { /* Tab */
strcpy(selected_key, "Tab");
}
else if (keysym == 0xff0d) { /* Return */
strcpy(selected_key, "Return");
}
else if (keysym == 0xff20) { /* space */
strcpy(selected_key, "Space");
}
else if (keysym >= 0x30 && keysym <= 0x39) { /* 0-9 */
snprintf(selected_key, sizeof(selected_key), "%c", (char)keysym);
}
else if (keysym >= 0x41 && keysym <= 0x5a) { /* A-Z */
snprintf(selected_key, sizeof(selected_key), "%c", (char)(keysym + 32));
}
else {
/* Unknown key with modifier, skip */
continue;
}
fprintf(stderr, "\nHotkey detected: %s+%s\n", modifier_str, selected_key);
have_hotkey = 1;
/* CRITICAL: Release keyboard grab before window selection */
if (grab_succeeded) {
fprintf(stderr, "Releasing keyboard grab for window selection...\n");
fflush(stderr);
XUngrabKeyboard(display, CurrentTime);
grab_succeeded = 0;
}
}
} else if (event.type == ClientMessage && event.xclient.message_type == XInternAtom(display, "WM_PROTOCOLS", True)) {
/* Window close event - cancel configuration */
fprintf(stderr, "Configuration cancelled (window closed)\n");
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
XCloseDisplay(display);
return;
}
}
/* Check if we timed out */
if (timeout_counter >= MAX_TIMEOUT) {
fprintf(stderr, "Configuration timed out - using default hotkey (Ctrl+Alt+F12)\n");
strcpy(selected_key, "F12");
detected_modifiers = 1; /* Ctrl+Alt */
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
}
/* Step 2: Scan and display windows */
fprintf(stderr, "\n" COLOR_BOLD COLOR_YELLOW "Step 2: Scanning all windows..." COLOR_RESET "\n");
Window *windows = NULL;
int count = scan_all_windows(&windows);
if (count == 0) {
fprintf(stderr, "No windows found\n");
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
XCloseDisplay(display);
return;
}
fprintf(stderr, "Found %d windows:\n", count);
/* Collect all window info first */
typedef struct {
int index;
char *title;
char *class;
Window window;
} WindowInfo;
WindowInfo *window_info = malloc(count * sizeof(WindowInfo));
for (int i = 0; i < count; i++) {
window_info[i].index = i + 1;
window_info[i].title = get_window_title(display, windows[i]);
window_info[i].class = get_window_class(display, windows[i]);
window_info[i].window = windows[i];
}
/* Group windows by application (window_class) */
typedef struct {
char *class_name;
int window_count;
WindowInfo **windows;
} AppGroup;
/* First, count unique classes */
int max_apps = count;
AppGroup *app_groups = malloc(max_apps * sizeof(AppGroup));
int app_count = 0;
for (int i = 0; i < count; i++) {
/* Skip hidden window classes */
int should_skip = 0;
for (int h = 0; hidden_classes[h] != NULL; h++) {
if (strstr(window_info[i].class, hidden_classes[h])) {
should_skip = 1;
break;
}
}
if (should_skip) continue;
/* Find if class already exists (exact match only) */
int found = -1;
for (int j = 0; j < app_count; j++) {
if (strcmp(app_groups[j].class_name, window_info[i].class) == 0) {
found = j;
break;
}
}
if (found == -1) {
/* New app class */
app_groups[app_count].class_name = strdup(window_info[i].class);
app_groups[app_count].window_count = 0;
app_groups[app_count].windows = malloc(count * sizeof(WindowInfo*));
app_groups[app_count].windows[0] = &window_info[i];
app_groups[app_count].window_count = 1;
app_count++;
} else {
/* Existing app class, add window to it */
app_groups[found].windows[app_groups[found].window_count] = &window_info[i];
app_groups[found].window_count++;
}
}
/* Display grouped windows */
int window_counter = 1;
for (int app = 0; app < app_count; app++) {
/* Choose color based on app class */
const char *class_name = app_groups[app].class_name;
const char *color;
if (strstr(class_name, "Nautilus")) {
color = COLOR_BLUE;
} else if (strstr(class_name, "chrome") || strstr(class_name, "firefox") || strstr(class_name, "edge")) {
color = COLOR_CYAN;
} else if (strstr(class_name, "Code") || strstr(class_name, "editor")) {
color = COLOR_MAGENTA;
} else if (strstr(class_name, "terminal") || strstr(class_name, "Terminator")) {
color = COLOR_GREEN;
} else if (strstr(class_name, "wechat") || strstr(class_name, "qq") || strstr(class_name, "weixin")) {
color = COLOR_LIGHT_GREEN;
} else {
color = COLOR_YELLOW;
}
fprintf(stderr, COLOR_BOLD "%s" COLOR_RESET " (%d window%s):\n",
class_name,
app_groups[app].window_count,
app_groups[app].window_count == 1 ? "" : "s");
for (int i = 0; i < app_groups[app].window_count; i++) {
fprintf(stderr, " " COLOR_BOLD "[" COLOR_LIGHT_BLUE "%d" COLOR_BOLD "]" COLOR_RESET " %s%s%s\n",
window_counter,
color,
app_groups[app].windows[i]->title,
COLOR_RESET);
app_groups[app].windows[i]->index = window_counter;
window_counter++;
}
}
/* Free temporary grouping structures */
for (int app = 0; app < app_count; app++) {
free(app_groups[app].class_name);
free(app_groups[app].windows);
}
free(app_groups);
/* Step 3: User selection */
fprintf(stderr, "\n" COLOR_BOLD COLOR_YELLOW "Step 3: Select target window" COLOR_RESET "\n");
fprintf(stderr, "Enter window number " COLOR_BOLD "(1-%d)" COLOR_RESET ": ", count);
fflush(stdout);
int choice;
if (scanf("%d", &choice) != 1 || choice < 1 || choice > count) {
fprintf(stderr, "Invalid selection\n");
free_window_list(windows);
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
XCloseDisplay(display);
return;
}
/* Find window by displayed index */
Window selected = 0;
char *title = NULL;
char *class = NULL;
for (int i = 0; i < count; i++) {
/* Skip hidden window classes during selection too */
int should_skip = 0;
for (int h = 0; hidden_classes[h] != NULL; h++) {
if (strstr(window_info[i].class, hidden_classes[h])) {
should_skip = 1;
break;
}
}
if (should_skip) continue;
if (window_info[i].index == choice) {
selected = window_info[i].window;
title = window_info[i].title;
class = window_info[i].class;
break;
}
}
if (selected == 0) {
fprintf(stderr, COLOR_RED "Error: Could not find selected window" COLOR_RESET "\n");
free_window_list(windows);
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
XCloseDisplay(display);
return;
}
fprintf(stderr, "\n" COLOR_BOLD COLOR_GREEN "Selected window:" COLOR_RESET "\n");
fprintf(stderr, " " COLOR_YELLOW "Title:" COLOR_RESET " %s\n", title);
fprintf(stderr, " " COLOR_YELLOW "Class:" COLOR_RESET " %s\n", class);
fprintf(stderr, " " COLOR_YELLOW "ID:" COLOR_RESET " " COLOR_CYAN "0x%lx" COLOR_RESET "\n", selected);
fprintf(stderr, "\n");
/* Step 4: Save configuration */
Config config;
memset(&config, 0, sizeof(Config));
/* Use detected modifiers */
if (detected_modifiers == 1) { /* Ctrl+Alt */
config.modifiers[0] = strdup("Ctrl");
config.modifiers[1] = strdup("Alt");
config.modifiers[2] = NULL;
} else if (detected_modifiers == 2) { /* Super */
config.modifiers[0] = strdup("Super");
config.modifiers[1] = NULL;
} else if (detected_modifiers == 3) { /* Ctrl only */
config.modifiers[0] = strdup("Ctrl");
config.modifiers[1] = NULL;
} else if (detected_modifiers == 4) { /* Ctrl+Shift */
config.modifiers[0] = strdup("Ctrl");
config.modifiers[1] = strdup("Shift");
config.modifiers[2] = NULL;
}
config.key = strdup(selected_key);
config.target_window = selected;
config.window_title = title;
config.window_class = class;
/* Build the shortcut string (e.g., "Super+F2", "Ctrl+F1") */
char shortcut_str[128];
if (detected_modifiers == 1) { /* Ctrl+Alt */
snprintf(shortcut_str, sizeof(shortcut_str), "Ctrl+Alt+%s", selected_key);
} else if (detected_modifiers == 2) { /* Super */
snprintf(shortcut_str, sizeof(shortcut_str), "Super+%s", selected_key);
} else if (detected_modifiers == 3) { /* Ctrl only */
snprintf(shortcut_str, sizeof(shortcut_str), "Ctrl+%s", selected_key);
} else if (detected_modifiers == 4) { /* Ctrl+Shift */
snprintf(shortcut_str, sizeof(shortcut_str), "Ctrl+Shift+%s", selected_key);
} else {
snprintf(shortcut_str, sizeof(shortcut_str), "%s", selected_key);
}
/* Save the shortcut mapping (append mode) */
save_shortcut_mapping(config_path, shortcut_str, selected, title, class, -1); /* -1 means no slot_id set yet */
fprintf(stderr, "Configuration saved to: %s\n", config_path);
/* Step 5: Show system shortcut configuration */
fprintf(stderr, "\n" COLOR_BOLD COLOR_CYAN "=== Configuration Complete ===" COLOR_RESET "\n");
fprintf(stderr, COLOR_GREEN "Shortcut added:" COLOR_RESET " " COLOR_BOLD COLOR_MAGENTA "%s" COLOR_RESET " -> %s\n", shortcut_str, title);
fprintf(stderr, COLOR_GREEN "Total shortcuts:" COLOR_RESET " Check " COLOR_CYAN "%s" COLOR_RESET "\n", config_path);
fprintf(stderr, "\n" COLOR_YELLOW "Setting up system shortcut automatically..." COLOR_RESET "\n");
/* Generate automatic configuration */
char shortcut_key[64];
if (detected_modifiers == 1) {
snprintf(shortcut_key, sizeof(shortcut_key), "<Control><Alt>%s", selected_key);
} else if (detected_modifiers == 2) {
snprintf(shortcut_key, sizeof(shortcut_key), "<Super>%s", selected_key);
} else if (detected_modifiers == 3) {
snprintf(shortcut_key, sizeof(shortcut_key), "<Control>%s", selected_key);
} else if (detected_modifiers == 4) {
snprintf(shortcut_key, sizeof(shortcut_key), "<Control><Shift>%s", selected_key);
} else {
/* Fx key alone - use just the key name */
snprintf(shortcut_key, sizeof(shortcut_key), "%s", selected_key);
}
/* Find the next slot ID - always allocate new slot */
int next_id = find_next_slot_id(config_path);
fprintf(stderr, COLOR_YELLOW "Using shortcut slot:" COLOR_RESET " custom%d\n", next_id);
/* Now set up the new shortcut */
char command[4096];
/* STEP 1: Add to custom-keybindings list FIRST (required before setting other properties) */
fprintf(stderr, COLOR_YELLOW "=== Step 1: Adding slot to custom-keybindings list ===" COLOR_RESET "\n");
/* Get the current list of custom keybindings */
FILE *fp = popen("gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings 2>/dev/null", "r");
if (!fp) {
fprintf(stderr, COLOR_RED " Failed to query existing shortcuts\n" COLOR_RESET);
} else {
char buffer[8192];
if (fgets(buffer, sizeof(buffer), fp) == NULL) {
fprintf(stderr, COLOR_RED " Could not read shortcuts\n" COLOR_RESET);
pclose(fp);
} else {
pclose(fp);
/* Build the new custom keybinding path */
char custom_path[256];
snprintf(custom_path, sizeof(custom_path), "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom%d/", next_id);
/* Handle @as [] (empty array) case */
char new_list[8192];
if (strncmp(buffer, "@as []", 6) == 0) {
snprintf(new_list, sizeof(new_list), "['%s']", custom_path);
} else {
char *bracket = strrchr(buffer, ']');
if (bracket) {
*bracket = '\0';
snprintf(new_list, sizeof(new_list), "%s, '%s']", buffer, custom_path);
} else {
snprintf(new_list, sizeof(new_list), "%s, '%s']", buffer, custom_path);
}
}
/* Use dconf to update the list */
snprintf(command, sizeof(command),
"dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings \"%s\"",
new_list);
fprintf(stderr, COLOR_YELLOW "Executing:" COLOR_RESET " %s\n", command);
int list_result = system(command);
if (list_result == 0) {
fprintf(stderr, COLOR_GREEN "✓ Added to keybindings list successfully" COLOR_RESET "\n");
} else {
fprintf(stderr, COLOR_RED "✗ Failed to add to keybindings list (exit code: %d)" COLOR_RESET "\n", list_result);
}
}
}
/* Small delay to ensure the schema is created */
usleep(100000);
/* STEP 2: Set the binding - use dconf write with GVariant format */
fprintf(stderr, COLOR_YELLOW "=== Step 2: Setting up binding ===" COLOR_RESET "\n");
snprintf(command, sizeof(command),
"dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom%d/binding \"%s%s%s\"",
next_id, "'", shortcut_key, "'");
fprintf(stderr, COLOR_YELLOW "Executing:" COLOR_RESET " %s\n", command);
if (system(command) == 0) {
fprintf(stderr, COLOR_GREEN "✓ Binding set successfully" COLOR_RESET "\n");
} else {
fprintf(stderr, COLOR_RED "✗ Failed to set binding\n" COLOR_RESET);
}
/* STEP 3: Set the command - use dconf write with GVariant format */
/* Get executable path dynamically */
char exec_path[4096];
get_exec_path(exec_path, sizeof(exec_path));
fprintf(stderr, COLOR_YELLOW "=== Step 3: Setting up command ===" COLOR_RESET "\n");
fprintf(stderr, "Using executable: %s\n", exec_path);
snprintf(command, sizeof(command),
"dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom%d/command \"%s%s --run --key %s%s\"",
next_id, "'", exec_path, shortcut_str, "'");
fprintf(stderr, COLOR_YELLOW "Executing:" COLOR_RESET " %s\n", command);
if (system(command) == 0) {
fprintf(stderr, COLOR_GREEN "✓ Command set successfully" COLOR_RESET "\n");
} else {
fprintf(stderr, COLOR_RED "✗ Failed to set command\n" COLOR_RESET);
}
/* STEP 4: Set the name - use dconf write with GVariant format */
fprintf(stderr, COLOR_YELLOW "=== Step 4: Setting up name ===" COLOR_RESET "\n");
snprintf(command, sizeof(command),
"dconf write /org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom%d/name \"%s%s%s\"",
next_id, "'", "window-toggle", "'");
fprintf(stderr, COLOR_YELLOW "Executing:" COLOR_RESET " %s\n", command);
if (system(command) == 0) {
fprintf(stderr, COLOR_GREEN "✓ Name set successfully" COLOR_RESET "\n");
} else {
fprintf(stderr, COLOR_RED "✗ Failed to set name\n" COLOR_RESET);
}
fprintf(stderr, COLOR_BOLD COLOR_GREEN "✓ Shortcut configured automatically!" COLOR_RESET " Press " COLOR_BOLD COLOR_YELLOW "%s" COLOR_RESET " to test.\n",
shortcut_str);
/* Update configuration file with slot_id (append mode) */
save_shortcut_mapping(config_path, shortcut_str, selected, title, class, next_id);
fprintf(stderr, COLOR_CYAN "Configuration updated with slot ID:" COLOR_RESET " %d\n", next_id);
configuration_complete:
/* Cleanup */
if (config.modifiers[0]) free(config.modifiers[0]);
if (config.modifiers[1]) free(config.modifiers[1]);
if (config.key) free(config.key);
/* Free per-window title/class strdup's before freeing the array itself.
* Each get_window_title / get_window_class returns a fresh strdup, so
* we can safely free them here. The selected window's pointers (title
* and class) are referenced by config.window_title / config.window_class
* but config doesn't own them, so we must free them via the array. */
if (window_info) {
for (int i = 0; i < count; i++) {
free(window_info[i].title);
free(window_info[i].class);
}
}
free(window_info);
free_window_list(windows);
if (grab_succeeded) XUngrabKeyboard(display, CurrentTime);
XCloseDisplay(display);
}
void run_mode() {
run_mode_with_path(CONFIG_PATH, NULL);
}
void run_mode_with_path(const char *config_path, const char *key_param) {
fprintf(stderr, "Window Toggle: Running...\n");
Config *config = NULL;
Window target_window = 0;
/* If key_param is provided, find the corresponding window from mappings */
if (key_param) {
fprintf(stderr, "Key pressed: %s\n", key_param);
target_window = find_window_by_key(config_path, key_param);
if (!target_window) {
fprintf(stderr, "No window found for key %s\n", key_param);
fprintf(stderr, "Config path: %s\n", config_path);
return;
}
fprintf(stderr, "Target window: 0x%lx\n", target_window);
} else {
/* Load configuration */
config = load_config(config_path);
if (!config) {
fprintf(stderr, "No configuration found at %s. Run with --configure first.\n", config_path);
return;
}
target_window = config->target_window;
fprintf(stderr, "Target window: 0x%lx\n", target_window);
}
/* Try daemon mode first */
if (daemon_is_running()) {
fprintf(stderr, "Using daemon for window operation...\n");
int32_t resp = -1;
uint32_t resp_size = sizeof(resp);
if (daemon_send_request(IPC_TOGGLE_WINDOW, &target_window, sizeof(target_window), &resp, &resp_size)) {
if (resp == 0) {
fprintf(stderr, COLOR_GREEN "Window toggled via daemon" COLOR_RESET "\n");
} else {
fprintf(stderr, COLOR_RED "Daemon operation failed" COLOR_RESET "\n");
}
} else {
fprintf(stderr, COLOR_YELLOW "Daemon request failed, falling back to direct X" COLOR_RESET "\n");
/* Fall through to direct X mode */
}
if (config) free_config(config);
return;
}
/* Fallback: direct X operations (for backward compatibility) */
fprintf(stderr, "Daemon not running, using direct X connection...\n");
Display *display = XOpenDisplay(NULL);
if (!display) {
fprintf(stderr, COLOR_RED "Failed to open X display" COLOR_RESET "\n");
if (config) free_config(config);
return;
}
WindowState current_state = read_state_file();
fprintf(stderr, "Current state: %d\n", current_state);
/* Perform toggle action */
int window_state = get_window_state(display, target_window);
fprintf(stderr, "Window state: %d (0=not running, 1=hidden, 2=visible)\n", window_state);
if (window_state == STATE_NOT_RUNNING) {
fprintf(stderr, COLOR_RED "Error: Window no longer exists. Please reconfigure with a currently open window." COLOR_RESET "\n");
XCloseDisplay(display);
if (config) free_config(config);
return;
}
/* 区分 "被压在底下" vs "在最前":mutter 只标 _NET_WM_STATE_HIDDEN,
* 不告诉用户 z-order。被压的窗口 minimize 后用户看不到,所以只 raise。 */
int was_on_top = is_window_on_top(display, target_window);
if (window_state == STATE_HIDDEN) {
activate_window(display, target_window);
write_active_window(target_window);
write_state_file(STATE_VISIBLE);
fprintf(stderr, COLOR_GREEN "Window activated" COLOR_RESET "\n");
} else if (was_on_top) {
/* 可见且在最前 → minimize,toggle 的"藏起来"那半 */
minimize_window(display, target_window);
write_active_window(target_window);
write_state_file(STATE_HIDDEN);
fprintf(stderr, COLOR_GREEN "Window minimized" COLOR_RESET "\n");
} else {
/* 可见但被压在底下 → 只 raise,不 minimize,让用户看到窗口跳出来 */
raise_window(display, target_window);
fprintf(stderr, COLOR_GREEN "Window raised" COLOR_RESET "\n");
}
XCloseDisplay(display);
if (config) free_config(config);
fprintf(stderr, COLOR_GREEN "Done." COLOR_RESET "\n");
}
/* Find the next available slot ID - skip invalid slots */
int find_next_slot_id(const char *config_path) {
int start = 0;
/* If config exists, count shortcuts to determine starting point */
if (config_exists(config_path)) {
FILE *fp = fopen(config_path, "r");
if (fp) {
int count = 0;
char line[512];
while (fgets(line, sizeof(line), fp)) {
if (line[0] != '\0') { /* Non-empty line = shortcut */
count++;
}
}
fclose(fp);
/* Start from count if config exists */
start = count;
}
}
/* Find first slot not in dconf list, starting from 'start' */
for (int i = start; i < 100; i++) {
/* First check if slot is in custom-keybindings list (use regex to avoid matching custom51 when searching for custom5) */
char list_check[512];
snprintf(list_check, sizeof(list_check),
"gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings | grep -oE 'custom%d[^0-9]' | wc -l",
i);
FILE *list_fp = popen(list_check, "r");
if (list_fp) {
char list_count[32];
if (fgets(list_count, sizeof(list_count), list_fp)) {
/* Remove newline from list_count */
list_count[strcspn(list_count, "\r\n")] = 0;
int in_list = atoi(list_count);
pclose(list_fp);
if (in_list > 0) {
continue; /* Skip slots already in list */
}
} else {
pclose(list_fp);
}
}
/* Slot not in list, it's available */
return i;
}
return start;
}
void start_mode_with_path(const char *config_path) {
fprintf(stderr, COLOR_BOLD COLOR_CYAN "=== Window Toggle Daemon Mode ===" COLOR_RESET "\n");
(void)config_path; /* unused */
if (daemon_is_running()) {
fprintf(stderr, COLOR_YELLOW "Daemon is already running." COLOR_RESET "\n");
daemon_status();
return;
}
fprintf(stderr, "Starting daemon...\n");
int ret = daemon_start();
if (ret == 0) {
fprintf(stderr, COLOR_GREEN "✓ Daemon started successfully" COLOR_RESET "\n");
} else if (ret < 0) {
fprintf(stderr, COLOR_RED "✗ Failed to start daemon" COLOR_RESET "\n");
}
}
void show_config(const char *config_path) {
/* App bindings (XDG) shown first. Use the merged (Ctrl(S+A)+Fx) format
* so a single app+Fx trio prints one row instead of three. */
{
char xdg_path[1024];
app_binding_xdg_path(xdg_path, sizeof(xdg_path));
AppBinding *list = NULL; int count = 0;
app_binding_load(xdg_path, &list, &count);
if (count > 0) {
fprintf(stderr, COLOR_BOLD COLOR_CYAN "=== App Bindings (%d, from %s) ===" COLOR_RESET "\n", count, xdg_path);
Display *disp = XOpenDisplay(NULL);
if (disp) { XSync(disp, False); XSetErrorHandler(silent_xerror_handler); }
qsort(list, count, sizeof(AppBinding), _show_binding_cmp);
int i = 0;
while (i < count) {
const char *gcmd = list[i].cmd ? list[i].cmd : "?";
const char *gwc = list[i].wm_class ? list[i].wm_class : "?";
const char *gkey = list[i].key ? list[i].key : "?";
int j = i;
while (j < count &&
strcmp(list[j].cmd ? list[j].cmd : "", gcmd) == 0 &&
strcmp(list[j].wm_class ? list[j].wm_class : "", gwc) == 0 &&
strcmp(list[j].key ? list[j].key : "", gkey) == 0) j++;
unsigned long anchor = 0;
int has_ctrl = 0, has_super = 0, has_alt = 0, has_other = 0;
for (int k = i; k < j; k++) {
const AppBinding *b = &list[k];
if (b->target_window != 0 && anchor == 0) anchor = b->target_window;
const char *m = b->modifiers ? b->modifiers : "";
if (strcmp(m, "Ctrl") == 0) has_ctrl = 1;
else if (strcmp(m, "Super") == 0) has_super = 1;
else if (strcmp(m, "Alt") == 0) has_alt = 1;
else has_other = 1;
}
const char *status = "not-started";
if (anchor != 0 && disp) {
XWindowAttributes attrs;
if (XGetWindowAttributes(disp, (Window)anchor, &attrs)) status = "alive";
else status = "dead";
} else if (anchor != 0) status = "anchored";
char shortcut[128];
if (has_ctrl && has_super && has_alt && !has_other)
snprintf(shortcut, sizeof(shortcut), "Ctrl(S+A)+%s", gkey);
else if (has_ctrl && has_super && !has_alt && !has_other)
snprintf(shortcut, sizeof(shortcut), "Ctrl+S+%s", gkey);
else if (has_ctrl && has_alt && !has_super && !has_other)
snprintf(shortcut, sizeof(shortcut), "Ctrl+A+%s", gkey);
else if (has_super && has_alt && !has_ctrl && !has_other)
snprintf(shortcut, sizeof(shortcut), "Super+Alt+%s", gkey);
else if (has_ctrl && !has_super && !has_alt && !has_other)
snprintf(shortcut, sizeof(shortcut), "Ctrl+%s", gkey);
else {
int pos = 0;
for (int k = i; k < j; k++) {
const char *m = list[k].modifiers ? list[k].modifiers : "";
if (m[0]) pos += snprintf(shortcut + pos, sizeof(shortcut) - pos, "%s%s", pos ? " / " : "", m);
pos += snprintf(shortcut + pos, sizeof(shortcut) - pos, "%s%s", m[0] ? "+" : "", gkey);
}
}
fprintf(stderr, " " COLOR_BOLD "%s" COLOR_RESET " → %s (%s) [anchor: 0x%lx, %s]\n",
shortcut, gcmd, gwc, anchor, status);
i = j;
}
if (disp) XCloseDisplay(disp);
app_binding_free(list, count);
fprintf(stderr, "\n");
}
}
fprintf(stderr, COLOR_BOLD COLOR_CYAN "=== Window Toggle Configuration ===" COLOR_RESET "\n");
if (!config_exists(config_path)) {
fprintf(stderr, COLOR_YELLOW "No configuration found at %s" COLOR_RESET "\n", config_path);
fprintf(stderr, "Run with " COLOR_BOLD "--configure" COLOR_RESET " to create a new configuration.\n");
return;
}
/* Read config file */
FILE *fp = fopen(config_path, "r");
if (!fp) {
fprintf(stderr, COLOR_RED "Failed to open config file: %s" COLOR_RESET "\n", config_path);
return;
}
fprintf(stderr, COLOR_YELLOW "Configuration file:" COLOR_RESET " %s\n", config_path);
char line[512];
int shortcut_count = 0;
/* Collect all shortcuts */
typedef struct {
char *shortcut;
char *window_title;
char *window_class;
Window window_id;
} ShortcutInfo;
ShortcutInfo *shortcuts = NULL;
int max_count = 10;
/* Allocate initial memory */
shortcuts = malloc(max_count * sizeof(ShortcutInfo));
/* Parse JSON format */
char current_modifiers[64] = "";
char current_key[32] = "";
unsigned long current_window_id = 0;
char current_window_title[256] = "";
char current_window_class[128] = "";
int in_config_block = 0;
while (fgets(line, sizeof(line), fp)) {
/* Remove newline */
line[strcspn(line, "\r\n")] = 0;
/* Skip empty lines */
if (line[0] == '\0') {
/* 空行结束一个 slot block。空 modifiers(裸 Fx)合法,
* 不该被这条多余的条件过滤掉。 */
if (current_key[0] != '\0' && current_window_id != 0) {
/* Build shortcut string */
char shortcut[128];
if (strlen(current_modifiers) > 0 && strcmp(current_modifiers, "Super") != 0 && strcmp(current_modifiers, "Ctrl+Alt") != 0) {
snprintf(shortcut, sizeof(shortcut), "%s+%s", current_modifiers, current_key);
} else {
snprintf(shortcut, sizeof(shortcut), "%s", current_key);
}
/* Add to shortcuts array */
if (shortcut_count >= max_count) {
max_count *= 2;
shortcuts = realloc(shortcuts, max_count * sizeof(ShortcutInfo));
}
shortcuts[shortcut_count].shortcut = strdup(shortcut);
shortcuts[shortcut_count].window_title = strdup(current_window_title);
shortcuts[shortcut_count].window_class = strdup(current_window_class);
shortcuts[shortcut_count].window_id = (Window)current_window_id;
shortcut_count++;
/* Reset for next block */
current_modifiers[0] = '\0';
current_key[0] = '\0';
current_window_id = 0;
current_window_title[0] = '\0';
current_window_class[0] = '\0';
}
continue;
}
/* Parse JSON lines */
if (strncmp(line, "modifiers:", 10) == 0) {
char *p = line + 10;
while (*p == ' ' || *p == '\t') p++;
strncpy(current_modifiers, p, sizeof(current_modifiers) - 1);
current_modifiers[sizeof(current_modifiers) - 1] = '\0';
} else if (strncmp(line, "key:", 4) == 0) {
char *p = line + 4;
while (*p == ' ' || *p == '\t') p++;
strncpy(current_key, p, sizeof(current_key) - 1);
current_key[sizeof(current_key) - 1] = '\0';
} else if (strncmp(line, "window_id:", 10) == 0) {
char *p = line + 10;
while (*p == ' ' || *p == '\t') p++;
sscanf(p, "0x%lx", ¤t_window_id);
} else if (strncmp(line, "window_title:", 13) == 0) {
char *p = line + 13;
while (*p == ' ' || *p == '\t') p++;
strncpy(current_window_title, p, sizeof(current_window_title) - 1);
current_window_title[sizeof(current_window_title) - 1] = '\0';
} else if (strncmp(line, "window_class:", 13) == 0) {
char *p = line + 13;
while (*p == ' ' || *p == '\t') p++;
strncpy(current_window_class, p, sizeof(current_window_class) - 1);
current_window_class[sizeof(current_window_class) - 1] = '\0';
}
}
fclose(fp);
if (shortcut_count == 0) {
fprintf(stderr, COLOR_YELLOW "No shortcuts found in configuration." COLOR_RESET "\n");
return;
}
fprintf(stderr, COLOR_GREEN "Found %d shortcut(s):" COLOR_RESET "\n", shortcut_count);
/* Group by application (window_class) */
typedef struct {
char *class_name;
int count;
ShortcutInfo *items;
} AppGroup;
/* First, count unique classes */
int max_classes = shortcut_count;
AppGroup *groups = malloc(max_classes * sizeof(AppGroup));
int group_count = 0;
for (int i = 0; i < shortcut_count; i++) {
/* Find if class already exists (with smart matching) */
int found = -1;
for (int j = 0; j < group_count; j++) {
/* Exact match */
if (strcmp(groups[j].class_name, shortcuts[i].window_class) == 0) {
found = j;
break;
}
/* Smart match: check if one contains the other (for cases like X-terminal-emulator vs ~:X-terminal-emulator) */
if (strstr(groups[j].class_name, shortcuts[i].window_class) ||
strstr(shortcuts[i].window_class, groups[j].class_name)) {
found = j;
break;
}
}
if (found == -1) {
/* New class */