File: window.c

package info (click to toggle)
rofi 2.0.0-0.2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,472 kB
  • sloc: ansic: 36,245; lex: 957; yacc: 920; xml: 858; sh: 384; makefile: 17
file content (1172 lines) | stat: -rw-r--r-- 37,900 bytes parent folder | download
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
/*
 * rofi
 *
 * MIT/X11 License
 * Copyright © 2013-2023 Qball Cow <qball@gmpclient.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/** The log domain of this dialog. */
#define G_LOG_DOMAIN "Modes.Window"

#include "config.h"

#ifdef WINDOW_MODE

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <xcb/xcb.h>
#include <xcb/xcb_atom.h>
#include <xcb/xcb_ewmh.h>
#include <xcb/xcb_icccm.h>

#include <glib.h>

#include "xcb-internal.h"
#include "xcb.h"

#include "display.h"
#include "helper.h"
#include "modes/window.h"
#include "rofi.h"
#include "settings.h"
#include "widgets/textbox.h"

#include "timings.h"

#include "mode-private.h"
#include "rofi-icon-fetcher.h"

#define WINLIST 32

#define CLIENTSTATE 10
#define CLIENTWINDOWTYPE 10

// Fields to match in window mode
typedef struct {
  char *field_name;
  gboolean enabled;
} WinModeField;

typedef enum {
  WIN_MATCH_FIELD_TITLE,
  WIN_MATCH_FIELD_CLASS,
  WIN_MATCH_FIELD_ROLE,
  WIN_MATCH_FIELD_NAME,
  WIN_MATCH_FIELD_DESKTOP,
  WIN_MATCH_NUM_FIELDS,
} WinModeMatchingFields;

static WinModeField matching_window_fields[WIN_MATCH_NUM_FIELDS] = {
    {
        .field_name = "title",
        .enabled = TRUE,
    },
    {
        .field_name = "class",
        .enabled = TRUE,
    },
    {
        .field_name = "role",
        .enabled = TRUE,
    },
    {
        .field_name = "name",
        .enabled = TRUE,
    },
    {
        .field_name = "desktop",
        .enabled = TRUE,
    }};

static gboolean window_matching_fields_parsed = FALSE;

// a manageable window
typedef struct {
  xcb_window_t window;
  xcb_get_window_attributes_reply_t xattr;
  char *title;
  char *class;
  char *name;
  char *role;
  int states;
  xcb_atom_t state[CLIENTSTATE];
  int window_types;
  xcb_atom_t window_type[CLIENTWINDOWTYPE];
  int active;
  int demands;
  long hint_flags;
  uint32_t wmdesktop;
  char *wmdesktopstr;
  unsigned int wmdesktopstr_len;
  cairo_surface_t *icon;
  gboolean icon_checked;
  uint32_t icon_fetch_uid;
  uint32_t icon_fetch_size;
  guint icon_fetch_scale;
  gboolean thumbnail_checked;
  gboolean icon_theme_checked;
} client;

// window lists
typedef struct {
  xcb_window_t *array;
  client **data;
  int len;
} winlist;

typedef struct {
  unsigned int id;
  winlist *ids;
  // Current window.
  unsigned int index;
  char *cache;
  unsigned int wmdn_len;
  unsigned int clf_len;
  unsigned int name_len;
  unsigned int title_len;
  unsigned int role_len;
  GRegex *window_regex;
  // Hide current active window
  gboolean hide_active_window;
  gboolean prefer_icon_theme;
} WindowModePrivateData;

winlist *cache_client = NULL;

/**
 * Create a window list, pre-seeded with WINLIST entries.
 *
 * @returns A new window list.
 */
static winlist *winlist_new(void) {
  winlist *l = g_malloc(sizeof(winlist));
  l->len = 0;
  l->array = g_malloc_n(WINLIST + 1, sizeof(xcb_window_t));
  l->data = g_malloc_n(WINLIST + 1, sizeof(client *));
  return l;
}

/**
 * @param l The winlist.
 * @param w The window to add.
 * @param d Data pointer.
 *
 * Add one entry. If Full, extend with WINLIST entries.
 *
 * @returns -1 if failed, 0 or higher  is successful.
 */
static int winlist_append(winlist *l, xcb_window_t w, client *d) {
  if (l->len > 0 && !(l->len % WINLIST)) {
    l->array =
        g_realloc(l->array, sizeof(xcb_window_t) * (l->len + WINLIST + 1));
    l->data = g_realloc(l->data, sizeof(client *) * (l->len + WINLIST + 1));
  }
  // Make clang-check happy.
  // TODO: make clang-check clear this should never be 0.
  if (l->data == NULL || l->array == NULL) {
    return -1;
  }

  l->data[l->len] = d;
  l->array[l->len++] = w;
  return l->len - 1;
}

static void client_free(client *c) {
  if (c == NULL) {
    return;
  }
  if (c->icon) {
    cairo_surface_destroy(c->icon);
  }
  g_free(c->title);
  g_free(c->class);
  g_free(c->name);
  g_free(c->role);
  g_free(c->wmdesktopstr);
}
static void winlist_empty(winlist *l) {
  while (l->len > 0) {
    client *c = l->data[--l->len];
    if (c != NULL) {
      client_free(c);
      g_free(c);
    }
  }
}

/**
 * @param l The winlist entry
 *
 * Free the winlist.
 */
static void winlist_free(winlist *l) {
  if (l != NULL) {
    winlist_empty(l);
    g_free(l->array);
    g_free(l->data);
    g_free(l);
  }
}

/**
 * @param l The winlist.
 * @param w The window to find.
 *
 * Find the window in the list, and return the array entry.
 *
 * @returns -1 if failed, index is successful.
 */
static int winlist_find(winlist *l, xcb_window_t w) {
  if (l == NULL) {
    return -1;
  }
  // iterate backwards. Theory is: windows most often accessed will be
  // nearer the end. Testing with kcachegrind seems to support this...
  int i;

  for (i = (l->len - 1); i >= 0; i--) {
    if (l->array[i] == w) {
      return i;
    }
  }

  return -1;
}
/**
 * Create empty X11 cache for windows and windows attributes.
 */
static void x11_cache_create(void) {
  if (cache_client == NULL) {
    cache_client = winlist_new();
  }
}

/**
 * Free the cache.
 */
static void x11_cache_free(void) {
  winlist_free(cache_client);
  cache_client = NULL;
}

/**
 * @param d Display connection to X server
 * @param w window
 *
 * Get window attributes.
 * This functions uses caching.
 *
 * @returns a XWindowAttributes
 */
static xcb_get_window_attributes_reply_t *
window_get_attributes(xcb_window_t w) {
  xcb_get_window_attributes_cookie_t c =
      xcb_get_window_attributes(xcb->connection, w);
  xcb_get_window_attributes_reply_t *r =
      xcb_get_window_attributes_reply(xcb->connection, c, NULL);
  if (r) {
    return r;
  }
  return NULL;
}
// _NET_WM_STATE_*
static int client_has_state(client *c, xcb_atom_t state) {
  for (int i = 0; i < c->states; i++) {
    if (c->state[i] == state) {
      return 1;
    }
  }

  return 0;
}
static int client_has_window_type(client *c, xcb_atom_t type) {
  for (int i = 0; i < c->window_types; i++) {
    if (c->window_type[i] == type) {
      return 1;
    }
  }

  return 0;
}

static client *window_client(WindowModePrivateData *pd, xcb_window_t win) {
  if (win == XCB_WINDOW_NONE) {
    return NULL;
  }

  int idx = winlist_find(cache_client, win);

  if (idx >= 0) {
    return cache_client->data[idx];
  }

  // if this fails, we're up that creek
  xcb_get_window_attributes_reply_t *attr = window_get_attributes(win);

  if (!attr) {
    return NULL;
  }
  client *c = g_malloc0(sizeof(client));
  c->window = win;

  // copy xattr so we don't have to care when stuff is freed
  memmove(&c->xattr, attr, sizeof(xcb_get_window_attributes_reply_t));

  xcb_get_property_cookie_t cky = xcb_ewmh_get_wm_state(&xcb->ewmh, win);
  xcb_ewmh_get_atoms_reply_t states;
  if (xcb_ewmh_get_wm_state_reply(&xcb->ewmh, cky, &states, NULL)) {
    c->states = MIN(CLIENTSTATE, states.atoms_len);
    memcpy(c->state, states.atoms,
           MIN(CLIENTSTATE, states.atoms_len) * sizeof(xcb_atom_t));
    xcb_ewmh_get_atoms_reply_wipe(&states);
  }
  cky = xcb_ewmh_get_wm_window_type(&xcb->ewmh, win);
  if (xcb_ewmh_get_wm_window_type_reply(&xcb->ewmh, cky, &states, NULL)) {
    c->window_types = MIN(CLIENTWINDOWTYPE, states.atoms_len);
    memcpy(c->window_type, states.atoms,
           MIN(CLIENTWINDOWTYPE, states.atoms_len) * sizeof(xcb_atom_t));
    xcb_ewmh_get_atoms_reply_wipe(&states);
  }

  char *tmp_title = window_get_text_prop(c->window, xcb->ewmh._NET_WM_NAME);
  if (tmp_title == NULL) {
    tmp_title = window_get_text_prop(c->window, XCB_ATOM_WM_NAME);
  }
  if (tmp_title != NULL) {
    c->title = g_markup_escape_text(tmp_title, -1);
  } else {
    c->title = g_strdup("<i>no title set</i>");
  }
  pd->title_len =
      MAX(c->title ? g_utf8_strlen(c->title, -1) : 0, pd->title_len);
  g_free(tmp_title);

  char *tmp_role = window_get_text_prop(c->window, netatoms[WM_WINDOW_ROLE]);
  c->role = g_markup_escape_text(tmp_role ? tmp_role : "", -1);
  pd->role_len = MAX(c->role ? g_utf8_strlen(c->role, -1) : 0, pd->role_len);
  g_free(tmp_role);

  cky = xcb_icccm_get_wm_class(xcb->connection, c->window);
  xcb_icccm_get_wm_class_reply_t wcr;
  if (xcb_icccm_get_wm_class_reply(xcb->connection, cky, &wcr, NULL)) {
    c->class = g_markup_escape_text(wcr.class_name, -1);
    c->name = g_markup_escape_text(wcr.instance_name, -1);
    pd->name_len = MAX(c->name ? g_utf8_strlen(c->name, -1) : 0, pd->name_len);
    xcb_icccm_get_wm_class_reply_wipe(&wcr);
  }

  xcb_get_property_cookie_t cc =
      xcb_icccm_get_wm_hints(xcb->connection, c->window);
  xcb_icccm_wm_hints_t r;
  if (xcb_icccm_get_wm_hints_reply(xcb->connection, cc, &r, NULL)) {
    c->hint_flags = r.flags;
  }

  idx = winlist_append(cache_client, c->window, c);
  // Should never happen.
  if (idx < 0) {
    client_free(c);
    g_free(c);
    c = NULL;
  }
  g_free(attr);
  return c;
}

guint window_reload_timeout = 0;
static gboolean window_client_reload(G_GNUC_UNUSED void *data) {
  window_reload_timeout = 0;
  if (window_mode.private_data) {
    window_mode._destroy(&window_mode);
    window_mode._init(&window_mode);
  }
  if (window_mode_cd.private_data) {
    window_mode_cd._destroy(&window_mode_cd);
    window_mode_cd._init(&window_mode_cd);
  }
  if (window_mode.private_data || window_mode_cd.private_data) {
    rofi_view_reload();
  }
  return G_SOURCE_REMOVE;
}
void window_client_handle_signal(G_GNUC_UNUSED xcb_window_t win,
                                 G_GNUC_UNUSED gboolean create) {
  //  g_idle_add_full(G_PRIORITY_HIGH_IDLE, window_client_reload, NULL, NULL);
  if (window_reload_timeout > 0) {
    g_source_remove(window_reload_timeout);
    window_reload_timeout = 0;
  }
  window_reload_timeout = g_timeout_add(100, window_client_reload, NULL);
}
static int window_match(const Mode *sw, rofi_int_matcher **tokens,
                        unsigned int index) {
  WindowModePrivateData *rmpd =
      (WindowModePrivateData *)mode_get_private_data(sw);
  int match = 1;
  const winlist *ids = (winlist *)rmpd->ids;
  // Want to pull directly out of cache, X calls are not thread safe.
  int idx = winlist_find(cache_client, ids->array[index]);
  g_assert(idx >= 0);
  client *c = cache_client->data[idx];

  if (tokens) {
    for (int j = 0; match && tokens[j] != NULL; j++) {
      int test = 0;
      // Dirty hack. Normally helper_token_match does _all_ the matching,
      // Now we want it to match only one item at the time.
      // If hack not in place it would not match queries spanning multiple
      // fields. e.g. when searching 'title element' and 'class element'
      rofi_int_matcher *ftokens[2] = {tokens[j], NULL};
      if (c->title != NULL && c->title[0] != '\0' &&
          matching_window_fields[WIN_MATCH_FIELD_TITLE].enabled) {
        test = helper_token_match(ftokens, c->title);
      }

      if (test == tokens[j]->invert && c->class != NULL &&
          c->class[0] != '\0' &&
          matching_window_fields[WIN_MATCH_FIELD_CLASS].enabled) {
        test = helper_token_match(ftokens, c->class);
      }

      if (test == tokens[j]->invert && c->role != NULL && c->role[0] != '\0' &&
          matching_window_fields[WIN_MATCH_FIELD_ROLE].enabled) {
        test = helper_token_match(ftokens, c->role);
      }

      if (test == tokens[j]->invert && c->name != NULL && c->name[0] != '\0' &&
          matching_window_fields[WIN_MATCH_FIELD_NAME].enabled) {
        test = helper_token_match(ftokens, c->name);
      }
      if (test == tokens[j]->invert && c->wmdesktopstr != NULL &&
          c->wmdesktopstr[0] != '\0' &&
          matching_window_fields[WIN_MATCH_FIELD_DESKTOP].enabled) {
        test = helper_token_match(ftokens, c->wmdesktopstr);
      }

      if (test == 0) {
        match = 0;
      }
    }
  }

  return match;
}

static void window_mode_parse_fields(void) {
  window_matching_fields_parsed = TRUE;
  char *savept = NULL;
  // Make a copy, as strtok will modify it.
  char *switcher_str = g_strdup(config.window_match_fields);
  const char *const sep = ",#";
  // Split token on ','. This modifies switcher_str.
  for (unsigned int i = 0; i < WIN_MATCH_NUM_FIELDS; i++) {
    matching_window_fields[i].enabled = FALSE;
  }
  for (char *token = strtok_r(switcher_str, sep, &savept); token != NULL;
       token = strtok_r(NULL, sep, &savept)) {
    if (strcmp(token, "all") == 0) {
      for (unsigned int i = 0; i < WIN_MATCH_NUM_FIELDS; i++) {
        matching_window_fields[i].enabled = TRUE;
      }
      break;
    }
    gboolean matched = FALSE;
    for (unsigned int i = 0; i < WIN_MATCH_NUM_FIELDS; i++) {
      const char *field_name = matching_window_fields[i].field_name;
      if (strcmp(token, field_name) == 0) {
        matching_window_fields[i].enabled = TRUE;
        matched = TRUE;
      }
    }
    if (!matched) {
      g_warning("Invalid window field name :%s", token);
    }
  }
  // Free string that was modified by strtok_r
  g_free(switcher_str);
}

static unsigned int window_mode_get_num_entries(const Mode *sw) {
  const WindowModePrivateData *pd =
      (const WindowModePrivateData *)mode_get_private_data(sw);

  return pd->ids ? pd->ids->len : 0;
}
/**
 * Small helper function to find the right entry in the ewmh reply.
 * Is there a call for this?
 */
const char *invalid_desktop_name = "n/a";
static const char *_window_name_list_entry(const char *str, uint32_t length,
                                           int entry) {
  uint32_t offset = 0;
  int index = 0;
  while (index < entry && offset < length) {
    if (str[offset] == 0) {
      index++;
    }
    offset++;
  }
  if (offset >= length) {
    return invalid_desktop_name;
  }
  return &str[offset];
}
static void _window_mode_load_data(Mode *sw, unsigned int cd) {
  WindowModePrivateData *pd =
      (WindowModePrivateData *)mode_get_private_data(sw);
  // find window list
  xcb_window_t curr_win_id;
  int found = 0;

  // Create cache

  x11_cache_create();
  xcb_get_property_cookie_t c =
      xcb_ewmh_get_active_window(&(xcb->ewmh), xcb->screen_nbr);
  if (!xcb_ewmh_get_active_window_reply(&xcb->ewmh, c, &curr_win_id, NULL)) {
    curr_win_id = 0;
  }

  // Get the current desktop.
  unsigned int current_desktop = 0;
  c = xcb_ewmh_get_current_desktop(&xcb->ewmh, xcb->screen_nbr);
  if (!xcb_ewmh_get_current_desktop_reply(&xcb->ewmh, c, &current_desktop,
                                          NULL)) {
    current_desktop = 0;
  }

  g_debug("Get list from: %d", xcb->screen_nbr);
  c = xcb_ewmh_get_client_list_stacking(&xcb->ewmh, xcb->screen_nbr);
  xcb_ewmh_get_windows_reply_t clients = {
      0,
  };
  if (xcb_ewmh_get_client_list_stacking_reply(&xcb->ewmh, c, &clients, NULL)) {
    found = 1;
  } else {
    c = xcb_ewmh_get_client_list(&xcb->ewmh, xcb->screen_nbr);
    if (xcb_ewmh_get_client_list_reply(&xcb->ewmh, c, &clients, NULL)) {
      found = 1;
    }
  }
  if (!found) {
    return;
  }

  if (clients.windows_len > 0) {
    int i;
    // windows we actually display. May be slightly different to
    // _NET_CLIENT_LIST_STACKING if we happen to have a window destroyed while
    // we're working...
    pd->ids = winlist_new();

    int has_names = FALSE;
    ssize_t ws_names_length = 0;
    char *ws_names = NULL;
    xcb_get_property_cookie_t prop_cookie =
        xcb_ewmh_get_desktop_names(&xcb->ewmh, xcb->screen_nbr);
    xcb_ewmh_get_utf8_strings_reply_t names;
    if (xcb_ewmh_get_desktop_names_reply(&xcb->ewmh, prop_cookie, &names,
                                         NULL)) {
      ws_names_length = names.strings_len;
      ws_names = g_malloc0_n(names.strings_len + 1, sizeof(char));
      memcpy(ws_names, names.strings, names.strings_len);
      has_names = TRUE;
      xcb_ewmh_get_utf8_strings_reply_wipe(&names);
    }
    // calc widths of fields
    for (i = clients.windows_len - 1; i > -1; i--) {
      client *winclient = window_client(pd, clients.windows[i]);
      if ((winclient != NULL) && !winclient->xattr.override_redirect &&
          !client_has_window_type(winclient,
                                  xcb->ewmh._NET_WM_WINDOW_TYPE_DOCK) &&
          !client_has_window_type(winclient,
                                  xcb->ewmh._NET_WM_WINDOW_TYPE_DESKTOP) &&
          !client_has_state(winclient, xcb->ewmh._NET_WM_STATE_SKIP_PAGER) &&
          !client_has_state(winclient, xcb->ewmh._NET_WM_STATE_SKIP_TASKBAR)) {
        pd->clf_len =
            MAX(pd->clf_len, (winclient->class != NULL)
                                 ? (g_utf8_strlen(winclient->class, -1))
                                 : 0);

        if (client_has_state(winclient,
                             xcb->ewmh._NET_WM_STATE_DEMANDS_ATTENTION)) {
          winclient->demands = TRUE;
        }
        if ((winclient->hint_flags & XCB_ICCCM_WM_HINT_X_URGENCY) != 0) {
          winclient->demands = TRUE;
        }

        if (winclient->window == curr_win_id) {
          winclient->active = TRUE;
        }
        // find client's desktop.
        xcb_get_property_cookie_t cookie;
        xcb_get_property_reply_t *r;

        winclient->wmdesktop = 0xFFFFFFFF;
        cookie = xcb_get_property(xcb->connection, 0, winclient->window,
                                  xcb->ewmh._NET_WM_DESKTOP, XCB_ATOM_CARDINAL,
                                  0, 1);
        r = xcb_get_property_reply(xcb->connection, cookie, NULL);
        if (r) {
          if (r->type == XCB_ATOM_CARDINAL) {
            winclient->wmdesktop = *((uint32_t *)xcb_get_property_value(r));
          }
          free(r);
        }
        if (winclient->wmdesktop != 0xFFFFFFFF) {
          if (has_names) {
            if ((current_window_manager & WM_PANGO_WORKSPACE_NAMES) ==
                WM_PANGO_WORKSPACE_NAMES) {
              char *output = NULL;
              if (pango_parse_markup(
                      _window_name_list_entry(ws_names, ws_names_length,
                                              winclient->wmdesktop),
                      -1, 0, NULL, &output, NULL, NULL)) {
                winclient->wmdesktopstr = g_strdup(_window_name_list_entry(
                    ws_names, ws_names_length, winclient->wmdesktop));
                winclient->wmdesktopstr_len = g_utf8_strlen(output, -1);
                pd->wmdn_len = MAX(pd->wmdn_len, winclient->wmdesktopstr_len);
                g_free(output);
              } else {
                winclient->wmdesktopstr = g_strdup("Invalid name");
                winclient->wmdesktopstr_len =
                    g_utf8_strlen(winclient->wmdesktopstr, -1);
                pd->wmdn_len = MAX(pd->wmdn_len, winclient->wmdesktopstr_len);
              }
            } else {
              winclient->wmdesktopstr = g_markup_escape_text(
                  _window_name_list_entry(ws_names, ws_names_length,
                                          winclient->wmdesktop),
                  -1);
              winclient->wmdesktopstr_len =
                  g_utf8_strlen(winclient->wmdesktopstr, -1);
              pd->wmdn_len = MAX(pd->wmdn_len, winclient->wmdesktopstr_len);
            }
          } else {
            winclient->wmdesktopstr =
                g_strdup_printf("%u", (uint32_t)winclient->wmdesktop);
            winclient->wmdesktopstr_len =
                g_utf8_strlen(winclient->wmdesktopstr, -1);
            pd->wmdn_len = MAX(pd->wmdn_len, winclient->wmdesktopstr_len);
          }
        } else {
          winclient->wmdesktopstr = g_strdup("");
          winclient->wmdesktopstr_len =
              g_utf8_strlen(winclient->wmdesktopstr, -1);
          pd->wmdn_len = MAX(pd->wmdn_len, winclient->wmdesktopstr_len);
        }
        if (cd && winclient->wmdesktop != current_desktop) {
          continue;
        }
        if (!pd->hide_active_window || winclient->window != curr_win_id) {
          winlist_append(pd->ids, winclient->window, NULL);
        }
      }
    }

    if (has_names) {
      g_free(ws_names);
    }
  }
  xcb_ewmh_get_windows_reply_wipe(&clients);
}
static int window_mode_init(Mode *sw) {
  if (mode_get_private_data(sw) == NULL) {

    WindowModePrivateData *pd = g_malloc0(sizeof(*pd));
    ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE);
    Property *p =
        rofi_theme_find_property(wid, P_BOOLEAN, "hide-active-window", FALSE);
    if (p && p->type == P_BOOLEAN && p->value.b == TRUE) {
      pd->hide_active_window = TRUE;
    }
    // prefer icon theme selection
    p = rofi_theme_find_property(wid, P_BOOLEAN, "prefer-icon-theme", FALSE);
    if (p && p->type == P_BOOLEAN && p->value.b == TRUE) {
      pd->prefer_icon_theme = TRUE;
    }
    pd->window_regex = g_regex_new("{[-\\w]+(:-?[0-9]+)?}", 0, 0, NULL);
    mode_set_private_data(sw, (void *)pd);
    _window_mode_load_data(sw, FALSE);
    if (!window_matching_fields_parsed) {
      window_mode_parse_fields();
    }
  }
  return TRUE;
}
static int window_mode_init_cd(Mode *sw) {
  if (mode_get_private_data(sw) == NULL) {
    WindowModePrivateData *pd = g_malloc0(sizeof(*pd));

    ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE);
    Property *p =
        rofi_theme_find_property(wid, P_BOOLEAN, "hide-active-window", FALSE);
    if (p && p->type == P_BOOLEAN && p->value.b == TRUE) {
      pd->hide_active_window = TRUE;
    }
    pd->window_regex = g_regex_new("{[-\\w]+(:-?[0-9]+)?}", 0, 0, NULL);
    mode_set_private_data(sw, (void *)pd);
    _window_mode_load_data(sw, TRUE);
    if (!window_matching_fields_parsed) {
      window_mode_parse_fields();
    }
  }
  return TRUE;
}

static inline int act_on_window(xcb_window_t window) {
  int retv = TRUE;
  char **args = NULL;
  int argc = 0;
  char window_regex[100]; /* We are probably safe here */

  g_snprintf(window_regex, sizeof window_regex, "%d", window);

  helper_parse_setup(config.window_command, &args, &argc, "{window}",
                     window_regex, (char *)0);

  GError *error = NULL;
  g_spawn_async(NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL,
                &error);
  if (error != NULL) {
    char *msg = g_strdup_printf(
        "Failed to execute action for window: '%s'\nError: '%s'", window_regex,
        error->message);
    rofi_view_error_dialog(msg, FALSE);
    g_free(msg);
    // print error.
    g_error_free(error);
    retv = FALSE;
  }

  // Free the args list.
  g_strfreev(args);
  return retv;
}

static ModeMode window_mode_result(Mode *sw, int mretv,
                                   G_GNUC_UNUSED char **input,
                                   unsigned int selected_line) {
  WindowModePrivateData *rmpd =
      (WindowModePrivateData *)mode_get_private_data(sw);
  ModeMode retv = MODE_EXIT;
  if ((mretv & (MENU_OK))) {
    if (mretv & MENU_CUSTOM_ACTION) {
      act_on_window(rmpd->ids->array[selected_line]);
    } else {
      // Disable reverting input focus to previous window.
      xcb->focus_revert = 0;
      rofi_view_hide();
      if ((current_window_manager & WM_DO_NOT_CHANGE_CURRENT_DESKTOP) == 0) {
        // Get the desktop of the client to switch to
        uint32_t wmdesktop = 0;
        xcb_get_property_cookie_t cookie;
        xcb_get_property_reply_t *r;
        // Get the current desktop.
        unsigned int current_desktop = 0;
        xcb_get_property_cookie_t c =
            xcb_ewmh_get_current_desktop(&xcb->ewmh, xcb->screen_nbr);
        if (!xcb_ewmh_get_current_desktop_reply(&xcb->ewmh, c, &current_desktop,
                                                NULL)) {
          current_desktop = 0;
        }

        cookie = xcb_get_property(
            xcb->connection, 0, rmpd->ids->array[selected_line],
            xcb->ewmh._NET_WM_DESKTOP, XCB_ATOM_CARDINAL, 0, 1);
        r = xcb_get_property_reply(xcb->connection, cookie, NULL);
        if (r && r->type == XCB_ATOM_CARDINAL) {
          wmdesktop = *((uint32_t *)xcb_get_property_value(r));
        }
        if (r && r->type != XCB_ATOM_CARDINAL) {
          // Assume the client is on all desktops.
          wmdesktop = current_desktop;
        }
        free(r);

        // If we have to switch the desktop, do
        if (wmdesktop != current_desktop) {
          xcb_ewmh_request_change_current_desktop(&xcb->ewmh, xcb->screen_nbr,
                                                  wmdesktop, XCB_CURRENT_TIME);
        }
      }
      // Activate the window
      xcb_ewmh_request_change_active_window(
          &xcb->ewmh, xcb->screen_nbr, rmpd->ids->array[selected_line],
          XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER, XCB_CURRENT_TIME,
          rofi_view_get_window());
      xcb_flush(xcb->connection);
    }
  } else if ((mretv & (MENU_ENTRY_DELETE)) == MENU_ENTRY_DELETE) {
    xcb_ewmh_request_close_window(
        &(xcb->ewmh), xcb->screen_nbr, rmpd->ids->array[selected_line],
        XCB_CURRENT_TIME, XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER);
    xcb_flush(xcb->connection);
    ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE);
    Property *p =
        rofi_theme_find_property(wid, P_BOOLEAN, "close-on-delete", TRUE);
    if (p && p->type == P_BOOLEAN && p->value.b == FALSE) {

      return RELOAD_DIALOG;
    }
  } else if ((mretv & MENU_CUSTOM_INPUT) && *input != NULL &&
             *input[0] != '\0') {
    GError *error = NULL;
    gboolean run_in_term = ((mretv & MENU_CUSTOM_ACTION) == MENU_CUSTOM_ACTION);
    gsize lf_cmd_size = 0;
    gchar *lf_cmd = g_locale_from_utf8(*input, -1, NULL, &lf_cmd_size, &error);
    if (error != NULL) {
      g_warning("Failed to convert command to locale encoding: %s",
                error->message);
      g_error_free(error);
      return RELOAD_DIALOG;
    }

    RofiHelperExecuteContext context = {.name = NULL};
    if (!helper_execute_command(NULL, lf_cmd, run_in_term,
                                run_in_term ? &context : NULL)) {
      retv = RELOAD_DIALOG;
    }
    g_free(lf_cmd);
  } else if (mretv & MENU_CUSTOM_COMMAND) {
    retv = (mretv & MENU_LOWER_MASK);
  }
  return retv;
}

static void window_mode_destroy(Mode *sw) {
  WindowModePrivateData *rmpd =
      (WindowModePrivateData *)mode_get_private_data(sw);
  if (rmpd != NULL) {
    winlist_free(rmpd->ids);
    x11_cache_free();
    g_free(rmpd->cache);
    g_regex_unref(rmpd->window_regex);
    g_free(rmpd);
    mode_set_private_data(sw, NULL);
  }
}
struct arg {
  const WindowModePrivateData *pd;
  const client *c;
};

static void helper_eval_add_str(GString *str, const char *input, int l,
                                int max_len, int nc) {
  // g_utf8 does not work with NULL string.
  const char *input_nn = input ? input : "";
  // Both l and max_len are in characters, not bytes.
  int spaces = 0;
  if (l > 0) {
    if (nc > l) {
      int bl = g_utf8_offset_to_pointer(input_nn, l) - input_nn;
      char *tmp = g_markup_escape_text(input_nn, bl);
      g_string_append(str, tmp);
      g_free(tmp);
    } else {
      spaces = l - nc;
      char *tmp = g_markup_escape_text(input_nn, -1);
      g_string_append(str, tmp);
      g_free(tmp);
    }
  } else {
    g_string_append(str, input_nn);
    if (l == 0) {
      spaces = MAX(0, max_len - nc);
    }
  }
  while (spaces--) {
    g_string_append_c(str, ' ');
  }
}
static gboolean helper_eval_cb(const GMatchInfo *info, GString *str,
                               gpointer data) {
  struct arg *d = (struct arg *)data;
  gchar *match;
  // Get the match
  match = g_match_info_fetch(info, 0);
  if (match != NULL) {
    int l = 0;
    if (match[2] == ':') {
      l = (int)g_ascii_strtoll(&match[3], NULL, 10);
    }
    if (match[1] == 'w') {
      helper_eval_add_str(str, d->c->wmdesktopstr, l, d->pd->wmdn_len,
                          d->c->wmdesktopstr_len);
    } else if (match[1] == 'c') {
      helper_eval_add_str(str, d->c->class, l, d->pd->clf_len,
                          g_utf8_strlen(d->c->class, -1));
    } else if (match[1] == 't') {
      helper_eval_add_str(str, d->c->title, l, d->pd->title_len,
                          g_utf8_strlen(d->c->title, -1));
    } else if (match[1] == 'n') {
      helper_eval_add_str(str, d->c->name, l, d->pd->name_len,
                          g_utf8_strlen(d->c->name, -1));
    } else if (match[1] == 'r') {
      helper_eval_add_str(str, d->c->role, l, d->pd->role_len,
                          g_utf8_strlen(d->c->role, -1));
    }

    g_free(match);
  }
  return FALSE;
}
static char *_generate_display_string(const WindowModePrivateData *pd,
                                      const client *c) {
  struct arg d = {pd, c};
  char *res = g_regex_replace_eval(pd->window_regex, config.window_format, -1,
                                   0, 0, helper_eval_cb, &d, NULL);
  return g_strchomp(res);
}

static char *_get_display_value(const Mode *sw, unsigned int selected_line,
                                int *state, G_GNUC_UNUSED GList **list,
                                int get_entry) {
  WindowModePrivateData *rmpd = mode_get_private_data(sw);
  const client *c = window_client(rmpd, rmpd->ids->array[selected_line]);
  if (c == NULL) {
    return get_entry ? g_strdup("Window has vanished") : NULL;
  }
  if (c->demands) {
    *state |= URGENT;
  }
  if (c->active) {
    *state |= ACTIVE;
  }
  *state |= MARKUP;
  return get_entry ? _generate_display_string(rmpd, c) : NULL;
}

/**
 * Icon code borrowed from https://github.com/olejorgenb/extract-window-icon
 */
static cairo_user_data_key_t data_key;

/** Create a surface object from this image data.
 * \param width The width of the image.
 * \param height The height of the image
 * \param data The image's data in ARGB format, will be copied by this
 * function.
 */
static cairo_surface_t *draw_surface_from_data(uint32_t width, uint32_t height,
                                               uint32_t const *const data) {
  // limit surface size.
  if (width >= 65536 || height >= 65536) {
    return NULL;
  }
  uint32_t len = width * height;
  uint32_t i;
  uint32_t *buffer = g_new0(uint32_t, len);
  cairo_surface_t *surface;

  /* Cairo wants premultiplied alpha, meh :( */
  for (i = 0; i < len; i++) {
    uint8_t a = (data[i] >> 24) & 0xff;
    double alpha = a / 255.0;
    uint8_t r = ((data[i] >> 16) & 0xff) * alpha;
    uint8_t g = ((data[i] >> 8) & 0xff) * alpha;
    uint8_t b = ((data[i] >> 0) & 0xff) * alpha;
    buffer[i] = (a << 24) | (r << 16) | (g << 8) | b;
  }

  surface = cairo_image_surface_create_for_data(
      (unsigned char *)buffer, CAIRO_FORMAT_ARGB32, width, height, width * 4);
  /* This makes sure that buffer will be freed */
  cairo_surface_set_user_data(surface, &data_key, buffer, g_free);

  return surface;
}
static cairo_surface_t *ewmh_window_icon_from_reply(xcb_get_property_reply_t *r,
                                                    uint32_t preferred_size) {
  uint32_t *data, *end, *found_data = 0;
  uint32_t found_size = 0;

  if (!r || r->type != XCB_ATOM_CARDINAL || r->format != 32 || r->length < 2) {
    return 0;
  }

  data = (uint32_t *)xcb_get_property_value(r);
  if (!data) {
    return 0;
  }

  end = data + r->length;

  /* Goes over the icon data and picks the icon that best matches the size
   * preference. In case the size match is not exact, picks the closest bigger
   * size if present, closest smaller size otherwise.
   */
  while (data + 1 < end) {
    /* check whether the data size specified by width and height fits into the
     * array we got */
    uint64_t data_size = (uint64_t)data[0] * data[1];
    if (data_size > (uint64_t)(end - data - 2)) {
      break;
    }

    /* use the greater of the two dimensions to match against the preferred
     * size
     */
    uint32_t size = MAX(data[0], data[1]);

    /* pick the icon if it's a better match than the one we already have */
    gboolean found_icon_too_small = found_size < preferred_size;
    gboolean found_icon_too_large = found_size > preferred_size;
    gboolean icon_empty = data[0] == 0 || data[1] == 0;
    gboolean better_because_bigger = found_icon_too_small && size > found_size;
    gboolean better_because_smaller =
        found_icon_too_large && size >= preferred_size && size < found_size;
    if (!icon_empty &&
        (better_because_bigger || better_because_smaller || found_size == 0)) {
      found_data = data;
      found_size = size;
    }

    data += data_size + 2;
  }

  if (!found_data) {
    return 0;
  }

  return draw_surface_from_data(found_data[0], found_data[1], found_data + 2);
}
/** Get NET_WM_ICON. */
static cairo_surface_t *get_net_wm_icon(xcb_window_t xid,
                                        uint32_t preferred_size) {
  xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(
      xcb->connection, FALSE, xid, xcb->ewmh._NET_WM_ICON, XCB_ATOM_CARDINAL, 0,
      UINT32_MAX);
  xcb_get_property_reply_t *r =
      xcb_get_property_reply(xcb->connection, cookie, NULL);
  cairo_surface_t *surface = ewmh_window_icon_from_reply(r, preferred_size);
  free(r);
  return surface;
}
static cairo_surface_t *_get_icon(const Mode *sw, unsigned int selected_line,
                                  unsigned int size) {
  WindowModePrivateData *rmpd = mode_get_private_data(sw);
  const guint scale = display_scale();
  client *c = window_client(rmpd, rmpd->ids->array[selected_line]);
  if (c == NULL) {
    return NULL;
  }
  if (c->icon_fetch_size != size || c->icon_fetch_scale != scale) {
    if (c->icon) {
      cairo_surface_destroy(c->icon);
      c->icon = NULL;
    }
    c->thumbnail_checked = FALSE;
    c->icon_checked = FALSE;
    c->icon_theme_checked = FALSE;
  }
  // TODO: apply scaling to the following two routines
  if (config.window_thumbnail && c->thumbnail_checked == FALSE) {
    c->icon = x11_helper_get_screenshot_surface_window(c->window, size);
    c->thumbnail_checked = TRUE;
  }
  if (rmpd->prefer_icon_theme == FALSE) {
    if (c->icon == NULL && c->icon_checked == FALSE) {
      c->icon = get_net_wm_icon(rmpd->ids->array[selected_line], size);
      c->icon_checked = TRUE;
    }
    if (c->icon == NULL && c->class && c->icon_theme_checked == FALSE) {
      if (c->icon_fetch_uid == 0) {
        char *class_lower = g_utf8_strdown(c->class, -1);
        c->icon_fetch_uid = rofi_icon_fetcher_query(class_lower, size);
        g_free(class_lower);
        c->icon_fetch_size = size;
        c->icon_fetch_scale = scale;
      }
      c->icon_theme_checked =
          rofi_icon_fetcher_get_ex(c->icon_fetch_uid, &(c->icon));
      if (c->icon) {
        cairo_surface_reference(c->icon);
      }
    }
  } else {
    if (c->icon == NULL && c->class && c->icon_theme_checked == FALSE) {
      if (c->icon_fetch_uid == 0 || c->icon_fetch_size != size ||
          c->icon_fetch_scale != scale) {
        char *class_lower = g_utf8_strdown(c->class, -1);
        c->icon_fetch_uid = rofi_icon_fetcher_query(class_lower, size);
        g_free(class_lower);
        c->icon_fetch_size = size;
        c->icon_fetch_scale = scale;
      }
      c->icon_theme_checked =
          rofi_icon_fetcher_get_ex(c->icon_fetch_uid, &(c->icon));
      if (c->icon) {
        cairo_surface_reference(c->icon);
      }
    }
    if (c->icon_theme_checked == TRUE && c->icon == NULL &&
        c->icon_checked == FALSE) {
      c->icon = get_net_wm_icon(rmpd->ids->array[selected_line], size);
      c->icon_checked = TRUE;
    }
  }
  c->icon_fetch_size = size;
  c->icon_fetch_scale = scale;
  return c->icon;
}

#include "mode-private.h"
Mode window_mode = {.name = "window",
                    .cfg_name_key = "display-window",
                    ._init = window_mode_init,
                    ._get_num_entries = window_mode_get_num_entries,
                    ._result = window_mode_result,
                    ._destroy = window_mode_destroy,
                    ._token_match = window_match,
                    ._get_display_value = _get_display_value,
                    ._get_icon = _get_icon,
                    ._get_completion = NULL,
                    ._preprocess_input = NULL,
                    .private_data = NULL,
                    .free = NULL,
                    .type = MODE_TYPE_SWITCHER};
Mode window_mode_cd = {.name = "windowcd",
                       .cfg_name_key = "display-windowcd",
                       ._init = window_mode_init_cd,
                       ._get_num_entries = window_mode_get_num_entries,
                       ._result = window_mode_result,
                       ._destroy = window_mode_destroy,
                       ._token_match = window_match,
                       ._get_display_value = _get_display_value,
                       ._get_icon = _get_icon,
                       ._get_completion = NULL,
                       ._preprocess_input = NULL,
                       .private_data = NULL,
                       .free = NULL,
                       .type = MODE_TYPE_SWITCHER};

#endif // WINDOW_MODE