summaryrefslogtreecommitdiff
path: root/mcwm.c
blob: c93a8e6cf63a202571eb51f1208ed1a78a2b8331 (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
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
/*
 * mcwm, a small window manager for the X Window System using the X
 * protocol C Binding libraries.
 *
 * For 'user' configurable stuff, see config.h.
 *
 * MC, mc at the domain hack.org
 * http://hack.org/mc/
 *
 * Copyright (c) 2010 Michael Cardell Widerkrantz, mc at the domain hack.org.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>

#include <xcb/xcb.h>
#include <xcb/xcb_keysyms.h>
#include <xcb/xcb_atom.h>
#include <xcb/xcb_icccm.h>

#include <X11/keysym.h>

/* Check here for user configurable parts: */
#include "config.h"

#ifdef DMALLOC
#include "dmalloc.h"
#endif

#ifdef DEBUG
#define PDEBUG(Args...) \
  do { fprintf(stderr, "mcwm: "); fprintf(stderr, ##Args); } while(0)
#define D(x) x
#else
#define PDEBUG(Args...)
#define D(x)
#endif


/* Internal Constants. */
#define MCWM_MOVE 2
#define MCWM_RESIZE 3


/* Types. */
typedef enum {
    KEY_H,
    KEY_J,
    KEY_K,
    KEY_L,
    KEY_M,
    KEY_R,
    KEY_RET,
    KEY_X,
    KEY_TAB,
    KEY_MAX
} key_enum_t;
    

/* Globals */
xcb_connection_t *conn;         /* Connection to X server. */
xcb_screen_t *screen;           /* Our current screen.  */
char *terminal = TERMINAL;      /* Path to terminal to start. */
xcb_drawable_t focuswin;        /* Current focus window. */

struct keys
{
    xcb_keysym_t keysym;
    xcb_keycode_t keycode;
} keys[KEY_MAX] =
{
    { USERKEY_MOVE_LEFT, 0 },
    { USERKEY_MOVE_DOWN, 0 },
    { USERKEY_MOVE_UP, 0 },
    { USERKEY_MOVE_RIGHT, 0 },
    { USERKEY_MAXVERT, 0 },
    { USERKEY_RAISE, 0 },
    { USERKEY_TERMINAL, 0 },
    { USERKEY_MAX, 0 },
    { USERKEY_CHANGE, 0 }    
};    

struct conf
{
    bool borders;
} conf;


/* Functions declerations. */
void newwin(xcb_window_t win);
void setupwin(xcb_window_t win);
xcb_keycode_t keysymtokeycode(xcb_keysym_t keysym, xcb_key_symbols_t *keysyms);
int setupkeys(void);
int setupscreen(void);
void raisewindow(xcb_drawable_t win);
void raiseorlower(xcb_drawable_t win);
void movewindow(xcb_drawable_t win, uint16_t x, uint16_t y);
void setunfocus(xcb_drawable_t win);
void setfocus(xcb_drawable_t win);
int start_terminal(void);
void resize(xcb_drawable_t win, uint32_t width, uint32_t height);
void resizestep(xcb_drawable_t win, char direction);
void mousemove(xcb_drawable_t win, int rel_x, int rel_y);
void mouseresize(xcb_drawable_t win, int rel_x, int rel_y);
void movestep(xcb_drawable_t win, char direction);
void maximize(xcb_drawable_t win);
void maxvert(xcb_drawable_t win);
void handle_keypress(xcb_drawable_t win, xcb_key_press_event_t *ev);


/* Function bodies. */

/*
 * Set position, geometry and attributes of a new window and show it
 * on the screen.
 */
void newwin(xcb_window_t win)
{
    xcb_query_pointer_reply_t *pointer;
    xcb_get_geometry_reply_t *geom;
    int x;
    int y;
    int32_t width;
    int32_t height;

    /* Get pointer position so we can move the window to the cursor. */
    pointer = xcb_query_pointer_reply(
        conn, xcb_query_pointer(conn, screen->root), 0);

    if (NULL == pointer)
    {
        x = 0;
        y = 0;
    }
    else
    {
        x = pointer->root_x;
        y = pointer->root_y;

        free(pointer);
    }

    /*
     * Get window geometry so we can check if it fits on the screen
     * where the cursor is.
     */
    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);
    if (NULL == geom)
    {
        return;
    }

    width = geom->width;
    height = geom->height;
    
    /* FIXME: XCB_SIZE_HINT_BASE_SIZE */
    
    /*
     * If the window is larger than our screen, just place it in the
     * corner and resize.
     */
    if (width > screen->width_in_pixels)
    {
        x = 0;
        width = screen->width_in_pixels - BORDERWIDTH * 2;;
        resize(win, width, height);
    }
    else if (x + width + BORDERWIDTH * 2 > screen->width_in_pixels)
    {
        x = screen->width_in_pixels - (width + BORDERWIDTH * 2);
    }

    if (height > screen->height_in_pixels)
    {
        y = 0;
        height = screen->height_in_pixels - BORDERWIDTH * 2;
        resize(win, width, height);
    }
    else if (y + height + BORDERWIDTH * 2 > screen->height_in_pixels)
    {
        y = screen->height_in_pixels - (height + BORDERWIDTH * 2);
    }
    
    /* Move the window to cursor position. */
    movewindow(win, x, y);

    /* Set up stuff and raise the window. */
    setupwin(win);
    raisewindow(win);

    /* Show window on screen. */
    xcb_map_window(conn, win);

    /*
     * Move cursor into the middle of the window so we don't lose the
     * pointer to another window.
     */
    xcb_warp_pointer(conn, XCB_NONE, win, 0, 0, 0, 0,
                     geom->width / 2, geom->height / 2);

    free(geom);
    
    xcb_flush(conn);
}

/* set border colour, width and event mask for window. */
void setupwin(xcb_window_t win)
{
    uint32_t mask = 0;    
    uint32_t values[2];

    if (conf.borders)
    {
        /* Set border color. */
        values[0] = UNFOCUSCOL;
        xcb_change_window_attributes(conn, win, XCB_CW_BORDER_PIXEL, values);

        /* Set border width. */
        values[0] = BORDERWIDTH;
        mask = XCB_CONFIG_WINDOW_BORDER_WIDTH;
        xcb_configure_window(conn, win, mask, values);
    }
    
    mask = XCB_CW_EVENT_MASK;
    values[0] = XCB_EVENT_MASK_ENTER_WINDOW;
    xcb_change_window_attributes_checked(conn, win, mask, values);
    
    /* FIXME: set properties. */

    xcb_flush(conn);
}

xcb_keycode_t keysymtokeycode(xcb_keysym_t keysym, xcb_key_symbols_t *keysyms)
{
    xcb_keycode_t *keyp;
    xcb_keycode_t key;

    /* We only use the first keysymbol, even if there are more. */
    keyp = xcb_key_symbols_get_keycode(keysyms, keysym);
    if (NULL == keyp)
    {
        fprintf(stderr, "mcwm: Couldn't look up key. Exiting.\n");
        exit(1);
        return 0;
    }

    key = *keyp;
    free(keyp);
    
    return key;
}

int setupkeys(void)
{
    xcb_key_symbols_t *keysyms;
    int i;
    
    /* Get all the keysymbols. */
    keysyms = xcb_key_symbols_alloc(conn);

    for (i = KEY_H; i < KEY_MAX; i ++)
    {
        keys[i].keycode = keysymtokeycode(keys[i].keysym, keysyms);        
        if (0 == keys[i].keycode)
        {
            /* Couldn't set up keys! */
    
            /* Get rid of key symbols. */
            free(keysyms);

            return -1;
        }
    }
    
    /* Get rid of the key symbols table. */
    free(keysyms);

    return 0;
}

/* Walk through all existing windows and set them up. */
int setupscreen(void)
{
    xcb_query_tree_reply_t *reply;
    xcb_query_pointer_reply_t *pointer;
    int i;
    int len;
    xcb_window_t *children;
    
    /* Get all children. */
    reply = xcb_query_tree_reply(conn,
                                 xcb_query_tree(conn, screen->root), 0);
    if (NULL == reply)
    {
        return -1;
    }

    len = xcb_query_tree_children_length(reply);    
    children = xcb_query_tree_children(reply);
    
    /* Set up all windows. */
    for (i = 0; i < len; i ++)
    {
        setupwin(children[i]);
    }

    /*
     * Get pointer position so we can set focus on any window which
     * might be under it.
     */
    pointer = xcb_query_pointer_reply(
        conn, xcb_query_pointer(conn, screen->root), 0);

    if (NULL == pointer)
    {
        focuswin = screen->root;
    }
    else
    {
        setfocus(pointer->child);
        free(pointer);
    }
    
    xcb_flush(conn);
    
    free(reply);

    return 0;
}

void raisewindow(xcb_drawable_t win)
{
    uint32_t values[] = { XCB_STACK_MODE_ABOVE };

    if (screen->root == win || 0 == win)
    {
        return;
    }
    
    xcb_configure_window(conn, win,
                         XCB_CONFIG_WINDOW_STACK_MODE,
                         values);
    xcb_flush(conn);
}

void raiseorlower(xcb_drawable_t win)
{
    uint32_t values[] = { XCB_STACK_MODE_OPPOSITE };

    if (screen->root == win || 0 == win)
    {
        return;
    }
    
    xcb_configure_window(conn, win,
                         XCB_CONFIG_WINDOW_STACK_MODE,
                         values);
    xcb_flush(conn);
}

void movewindow(xcb_drawable_t win, uint16_t x, uint16_t y)
{
    uint32_t values[2];

    if (screen->root == win || 0 == win)
    {
        /* Can't move root. */
        return;
    }
    
    values[0] = x;
    values[1] = y;

    xcb_configure_window(conn, win, XCB_CONFIG_WINDOW_X
                         | XCB_CONFIG_WINDOW_Y, values);
    
    xcb_flush(conn);

}

void setunfocus(xcb_drawable_t win)
{
    uint32_t values[1];
    
    if (focuswin == screen->root || !conf.borders)
    {
        return;
    }

    /* Set new border colour. */
    values[0] = UNFOCUSCOL;
    xcb_change_window_attributes(conn, win, XCB_CW_BORDER_PIXEL, values);

    xcb_flush(conn);
}

void setfocus(xcb_drawable_t win)
{
    uint32_t values[1];

    /*
     * Don't bother focusing on the root window or on the same window
     * that already has focus.
     */
    if (win == screen->root || win == focuswin)
    {
        return;
    }

    if (conf.borders)
    {
        /* Set new border colour. */
        values[0] = FOCUSCOL;
        xcb_change_window_attributes(conn, win, XCB_CW_BORDER_PIXEL, values);

        /* Unset last focus. */
        setunfocus(focuswin);
    }

    /* Set new input focus. */
    focuswin = win;
    xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, win,
                        XCB_CURRENT_TIME);

    xcb_flush(conn);
}

int start_terminal(void)
{
    pid_t pid;

    pid = fork();
    if (-1 == pid)
    {
        perror("fork");
        return -1;
    }
    else if (0 == pid)
    {
        char *argv[2];
        
        /* In the child. */
        
        argv[0] = terminal;
        argv[1] = NULL;
        
        /*
         * Create new process leader, otherwise the terminal will die
         * when wm dies.
         */
        if (-1 == setsid())
        {
            perror("setsid");
            exit(1);
        }

        if (-1 == execvp(terminal, argv))
        {
            perror("execve");            
            exit(1);
        }        
    }

    return 0;
}

void resize(xcb_drawable_t win, uint32_t width, uint32_t height)
{
    uint32_t values[2];

    if (screen->root == win || 0 == win)
    {
        /* Can't resize root. */
        return;
    }
    
    values[0] = width;
    values[1] = height;
                                        
    xcb_configure_window(conn, win,
                         XCB_CONFIG_WINDOW_WIDTH
                         | XCB_CONFIG_WINDOW_HEIGHT, values);
    xcb_flush(conn);
}

void resizestep(xcb_drawable_t win, char direction)
{
    xcb_get_geometry_reply_t *geom;
    int width;
    int height;
    xcb_size_hints_t hints;
    int step_x = MOVE_STEP;
    int step_y = MOVE_STEP;
    
    if (0 == win)
    {
        /* Can't resize root. */
        return;
    }

    raisewindow(win);

    /* Get window geometry. */
    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);
    if (NULL == geom)
    {
        return;
    }

    /*
     * Get the window's incremental size step, if any, and use that
     * when resizing.
     */
    if (!xcb_get_wm_normal_hints_reply(
            conn, xcb_get_wm_normal_hints_unchecked(
                conn, win), &hints, NULL))
    {
        PDEBUG("Couldn't get size hints.");
    }

    if (hints.flags & XCB_SIZE_HINT_P_RESIZE_INC)
    {
        if (0 == hints.width_inc || 0 == hints.height_inc)
        {
            PDEBUG("Client lied. No size inc hints.\n");
            step_x = 1;
            step_y = 1;
        }
        else
        {
            step_x = hints.width_inc;
            step_y = hints.height_inc;
        }
    }
    
    switch (direction)
    {
    case 'h':
        width = geom->width - step_x;
        height = geom->height;
        if (width < 0)
        {
            width = 0;
        }
        break;

    case 'j':
        width = geom->width;
        height = geom->height + step_y;
        if (height + geom->y > screen->height_in_pixels)
        {
            goto bad;
        }
        break;

    case 'k':
        width = geom->width;
        height = geom->height - step_y;
        if (height < 0)
        {
            goto bad;
        }
        break;

    case 'l':
        width = geom->width + step_x;
        height = geom->height;
        if (width + geom->x > screen->width_in_pixels)
        {
            goto bad;
        }
        break;

    default:
        PDEBUG("resizestep in unknown direction.\n");
        break;
    } /* switch direction */
           
    resize(win, width, height);

    /*
     * Move cursor into the middle of the window so we don't lose the
     * pointer to another window.
     */
    xcb_warp_pointer(conn, XCB_NONE, win, 0, 0, 0, 0,
                     width / 2, height / 2);
    
    xcb_flush(conn);
    
bad:
    free(geom);
}

void mousemove(xcb_drawable_t win, int rel_x, int rel_y)
{
    xcb_get_geometry_reply_t *geom;    
    int x;
    int y;
    
    /* Get window geometry. */

    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);
    if (NULL == geom)
    {
        return;
    }
    
    x = rel_x;
    y = rel_y;
    
    if (x < BORDERWIDTH)
    {
        x = BORDERWIDTH;
    }
    if (y < BORDERWIDTH)
    {
        y = BORDERWIDTH;
    }
    if (y + geom->height + BORDERWIDTH * 2 > screen->height_in_pixels)
    {
        y = screen->height_in_pixels - (geom->height + BORDERWIDTH * 2);
    }
    if (x + geom->width + BORDERWIDTH * 2 > screen->width_in_pixels)
    {
        x = screen->width_in_pixels - (geom->width + BORDERWIDTH * 2);
    }
    
    movewindow(win, x, y);

    free(geom);
}

void mouseresize(xcb_drawable_t win, int rel_x, int rel_y)
{
    xcb_get_geometry_reply_t *geom;
    xcb_size_hints_t hints;
    uint32_t width;
    uint32_t height;
    uint32_t width_inc = 1;
    uint32_t height_inc = 1;

    raisewindow(win);

    /* Get window geometry. */
    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);
    if (NULL == geom)
    {
        return;
    }
    
    if (rel_x - geom->x <= 1)
    {
        return;
    }

    if (rel_y - geom->y <= 1)
    {
        return;
    }

    width = rel_x - geom->x;
    height = rel_y - geom->y;

    /*
     * Get the window's incremental size step, if any, and use that
     * when resizing.
     *
     * FIXME: Do this right. ICCCM v2.0, 4.1.2.3. WM_NORMAL_HINTS
     * Property says:
     *
     *   The base_width and base_height elements in conjunction with
     *   width_inc and height_inc define an arithmetic progression of
     *   preferred window widths and heights for nonnegative integers
     *   i and j:
     *
     *   width = base_width + (i × width_inc)
     *   height = base_height + (j × height_inc)
     *
     *   Window managers are encouraged to use i and j instead of
     *   width and height in reporting window sizes to users. If a
     *   base size is not provided, the minimum size is to be used in
     *   its place and vice versa.
     */
    if (!xcb_get_wm_normal_hints_reply(
            conn, xcb_get_wm_normal_hints_unchecked(conn, win), &hints, NULL))
    {
        PDEBUG("Couldn't get size hints.");

    }
    if (hints.flags & XCB_SIZE_HINT_P_RESIZE_INC)
    {
        if (0 == hints.width_inc || 0 == hints.height_inc)
        {
            PDEBUG("The client lied. There is no resize inc here.\n");

            hints.width_inc = 1;
            hints.height_inc = 1;
        }
        else
        {
            width_inc = hints.width_inc;
            height_inc = hints.height_inc;

            if (0 != width % width_inc)
            {
                width -= width % width_inc;
            }

            if (0 != height % height_inc)
            {        
                height -= height % height_inc;
            }
        }
    }

    if (width > screen->width_in_pixels)
    {
        width = (screen->width_in_pixels - geom->x) / width_inc;
    }
        
    if (height > screen->height_in_pixels)
    {
        height = (screen->height_in_pixels - geom->y) / height_inc;
    }

    PDEBUG("Resizing to %dx%d (%dx%d)\n", width, height,
           width / width_inc,
           height / height_inc);

    resize(win, width, height);

    free(geom);
}
    
void movestep(xcb_drawable_t win, char direction)
{
    xcb_get_geometry_reply_t *geom;
    int x;
    int y;
    int width;
    int height;

    if (0 == win)
    {
        /* Can't move root. */
        return;
    }

    raisewindow(win);
    
    /* Get window geometry. */
    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);

    width = geom->width + BORDERWIDTH * 2;
    height = geom->height + BORDERWIDTH * 2;

    if (NULL == geom)
    {
        return;
    }
    
    switch (direction)
    {
    case 'h':
        x = geom->x - MOVE_STEP;
        if (x < 0)
        {
            x = 0;
        }

        movewindow(win, x, geom->y);
        break;

    case 'j':
        y = geom->y + MOVE_STEP;
        if (y + height > screen->height_in_pixels)
        {
            y = screen->height_in_pixels - height;
        }
        movewindow(win, geom->x, y);
        break;

    case 'k':
        y = geom->y - MOVE_STEP;
        if (y < 0)
        {
            y = 0;
        }
        
        movewindow(win, geom->x, y);
        break;

    case 'l':
        x = geom->x + MOVE_STEP;
        if (x + width > screen->width_in_pixels)
        {
            x = screen->width_in_pixels - width;
        }

        movewindow(win, x, geom->y);
        break;

    default:
        PDEBUG("movestep: Moving in unknown direction.\n");
        break;
    } /* switch direction */

    /* Move cursor into the middle of the window after moving. */
    xcb_warp_pointer(conn, XCB_NONE, win, 0, 0, 0, 0,
                     width / 2, height / 2);
    
    xcb_flush(conn);
    
    free(geom);
}

void maximize(xcb_drawable_t win)
{
    xcb_get_geometry_reply_t *geom;
    uint32_t values[2];
    uint32_t mask = 0;    

    if (screen->root == win || 0 == win)
    {
        return;
    }
    
    /* FIXME: Check if maximized already. If so, revert to stored geometry. */

    /* Get window geometry. */
    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);
    if (NULL == geom)
    {
        return;
    }

    /* Raise first. Pretty silly to maximize below something else. */
    raisewindow(win);
    
    /* FIXME: Store original geom in property. */

    /* Remove borders. */
    values[0] = 0;
    mask = XCB_CONFIG_WINDOW_BORDER_WIDTH;
    xcb_configure_window(conn, win, mask, values);
    
    /* Move to top left. */
    values[0] = 0;
    values[1] = 0;

    xcb_configure_window(conn, win, XCB_CONFIG_WINDOW_X
                         | XCB_CONFIG_WINDOW_Y, values);

    /* Then resize. */
    resize(win, screen->width_in_pixels,
           screen->height_in_pixels);

    free(geom);    
}

void maxvert(xcb_drawable_t win)
{
    xcb_get_geometry_reply_t *geom;
    uint32_t values[2];

    if (screen->root == win || 0 == win)
    {
        return;
    }
    
    /*
     * FIXME: Check if maximized already. If so, revert to stored
     * geometry.
     */

    /* Raise first. Pretty silly to maximize below something else. */
    raisewindow(win);

    /* Get window geometry. */
    geom = xcb_get_geometry_reply(conn,
                                  xcb_get_geometry(conn, win),
                                  NULL);
    if (NULL == geom)
    {
        return;
    }
    
    /* FIXME: Store original geom in property. */

    /* Move to top of screen. */
    values[0] = geom->x;
    values[1] = 0;

    xcb_configure_window(conn, win, XCB_CONFIG_WINDOW_X
                         | XCB_CONFIG_WINDOW_Y, values);

    /* Then resize. */
    resize(win, geom->width, screen->height_in_pixels - BORDERWIDTH * 2);

    free(geom);
}

void handle_keypress(xcb_drawable_t win, xcb_key_press_event_t *ev)
{
    int i;
    key_enum_t key;
    
    for (key = KEY_MAX, i = KEY_H; i < KEY_MAX; i ++)
    {
        if (ev->detail == keys[i].keycode)
        {
            key = i;
        }
    }
    if (key == KEY_MAX)
    {
        PDEBUG("Unknown key pressed.\n");
        return;
    }

    /* Is it shifted? */
    if (ev->state & XCB_MOD_MASK_SHIFT)
    {
        switch (key)
        {
        case KEY_H: /* h */
            resizestep(focuswin, 'h');
            break;

        case KEY_J: /* j */
            resizestep(focuswin, 'j');
            break;

        case KEY_K: /* k */
            resizestep(focuswin, 'k');
            break;

        case KEY_L: /* l */
            resizestep(focuswin, 'l');
            break;

        default:
            /* Ignore other shifted keys. */
            break;
        }
    }
    else
    {
        switch (key)
        {
        case KEY_RET: /* return */
            start_terminal();
            break;

        case KEY_H: /* h */
            movestep(focuswin, 'h');
            break;

        case KEY_J: /* j */
            movestep(focuswin, 'j');
            break;

        case KEY_K: /* k */
            movestep(focuswin, 'k');
            break;

        case KEY_L: /* l */
            movestep(focuswin, 'l');
            break;

        case KEY_TAB: /* tab */
            break;

        case KEY_M: /* m */
            maxvert(focuswin);
            break;

        case KEY_R: /* r*/
            raiseorlower(focuswin);
            break;
                    
        case KEY_X: /* x */
            maximize(focuswin);
            break;

        default:
            /* Ignore other keys. */
            break;            
        } /* switch unshifted */
    }
} /* handle_keypress() */

void events(void)
{
    xcb_generic_event_t *ev;
    xcb_drawable_t win;
    xcb_get_geometry_reply_t *geom;
    int mode = 0;
    uint16_t mode_x;
    uint16_t mode_y;
    
    for (;;)
    {
        ev = xcb_wait_for_event(conn);
        if (NULL == ev)
        {
            fprintf(stderr, "mcwm: Couldn't get event. Exiting...\n");
            exit(1);
        }
        
        PDEBUG("Event: %d\n", ev->response_type);

        switch (ev->response_type & ~0x80)
        {
        case XCB_MAP_REQUEST:
        {
            xcb_map_request_event_t *e;

            PDEBUG("event: Map request.\n");
            e = (xcb_map_request_event_t *) ev;
            newwin(e->window);
        }
        break;
        
        case XCB_DESTROY_NOTIFY:
        {
            xcb_destroy_notify_event_t *e;

            PDEBUG("event: Destroy notify.\n");
            e = (xcb_destroy_notify_event_t *) ev;

            /* FIXME: Find the window in list of clients. */
        }
        break;
            
        case XCB_BUTTON_PRESS:
        {
            xcb_button_press_event_t *e;
                
            e = ( xcb_button_press_event_t *) ev;
            PDEBUG ("Button %d pressed in window %ld, subwindow %d "
                    "coordinates (%d,%d)\n",
                    e->detail, e->event, e->child, e->event_x, e->event_y);

            if (e->child != 0)
            {
                win = e->child; 
                
                /*
                 * If middle button was pressed, raise window or lower
                 * it if it was already on top.
                 */
                if (2 == e->detail)
                {
                    raiseorlower(win);                    
                }
                else
                {
                    /* We're moving or resizing. */

                    /* Raise window. */
                    raisewindow(win);
                    
                    /* Save the pointer coordinates when starting. */
                    mode_x = e->event_x;
                    mode_y = e->event_y;

                    /* Get window geometry. */
                    geom = xcb_get_geometry_reply(conn, xcb_get_geometry(conn,
                                                                         win),
                                                  NULL);
                    if (NULL == geom)
                    {
                        break;
                    }

                    if (1 == e->detail)
                    {
                        mode = MCWM_MOVE;

                        /*
                         * Warp pointer to upper left of window before
                         * starting move.
                         */
                        xcb_warp_pointer(conn, XCB_NONE, win, 0, 0, 0, 0,
                                         1, 1);
                    }
                    else
                    {
                        mode = MCWM_RESIZE;

                        /* Warp pointer to lower right. */
                        xcb_warp_pointer(conn, XCB_NONE, win, 0, 0, 0, 0,
                                         geom->width, geom->height);
                    }

                    /*
                     * Take control of the pointer in the root window
                     * and confine it to root.
                     *
                     * Give us events when the button is released or
                     * if any motion occurs with the button held down,
                     * but give us only hints about movement. We ask
                     * for the position ourselves later.
                     *
                     * Keep updating everything else.
                     *
                     * Don't use any new cursor.
                     */
                    xcb_grab_pointer(conn, 0, screen->root,
                                     XCB_EVENT_MASK_BUTTON_RELEASE
                                     | XCB_EVENT_MASK_BUTTON_MOTION
                                     | XCB_EVENT_MASK_POINTER_MOTION_HINT, 
                                     XCB_GRAB_MODE_ASYNC,
                                     XCB_GRAB_MODE_ASYNC,
                                     screen->root,
                                     XCB_NONE,
                                     XCB_CURRENT_TIME);

                    xcb_flush(conn);

                    PDEBUG("mode now : %d\n", mode);
                }
            } /* subwindow */
            else
            {
                /*
                 * Do something on the root when mouse buttons are
                 * pressed?
                 */
            }
        }
        break;

        case XCB_MOTION_NOTIFY:
        {
            xcb_query_pointer_reply_t *pointer;
            
            /*
             * Our pointer is moving and since we even get this event
             * we're resizing or moving a window.
             */

            /* Get current pointer position. */
            pointer = xcb_query_pointer_reply(
                conn, xcb_query_pointer(conn, screen->root), 0);

            if (NULL == pointer)
            {
                PDEBUG("Couldn't get pointer position.\n");
                break;
            }

            if (mode == MCWM_MOVE)
            {
                mousemove(win, pointer->root_x, pointer->root_y);
            
            }
            else if (mode == MCWM_RESIZE)
            {
                /* Resize. */
                mouseresize(win, pointer->root_x, pointer->root_y);
            }
            else
            {
                PDEBUG("Motion event when we're not moving our resizing!\n");
            }

            free(pointer);
        }
        break;

        case XCB_BUTTON_RELEASE:
            PDEBUG("Mouse button released! mode = %d\n", mode);

            if (0 != mode)
            {
                xcb_button_release_event_t *e =
                    (xcb_button_release_event_t *)ev;
    
                /* We're finished moving or resizing. */

                xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
                xcb_flush(conn); /* Important! */
                
                mode = 0;
                free(geom);

                setfocus(e->event);
                
                PDEBUG("mode now = %d\n", mode);
                
            }
        break;
                
        case XCB_KEY_PRESS:
        {
            xcb_key_press_event_t *e = (xcb_key_press_event_t *)ev;
            
            win = e->child;
            
            PDEBUG("Key %d pressed in window %ld\n",
                    e->detail,
                    win);

            handle_keypress(win, e);
        }
        break;

        case XCB_ENTER_NOTIFY:
            PDEBUG("event: Enter notify.\n");
            if (0 == mode)
            {
                xcb_enter_notify_event_t *e = (xcb_enter_notify_event_t *)ev;
                
                /*
                 * If we're entering the same window we focus now,
                 * then don't bother focusing.
                 */
                if (e->event != focuswin)
                {
                    setfocus(e->event);
                }
            }
            break;        
        
        case XCB_CONFIGURE_NOTIFY:
        {
            xcb_configure_notify_event_t *e = (xcb_configure_notify_event_t *)ev;
            
            if (e->window == screen->root)
            {
                /*
                 * When using RANDR, the root can suddenly change
                 * geometry when the user adds a new screen, tilts
                 * their screen 90 degrees or whatnot.
                 *
                 * Since mcwm cares about the root edges, we need to
                 * update our view if this happens.
                 */
                PDEBUG("Notify event for root!\n");

                screen->width_in_pixels = e->width;
                screen->height_in_pixels = e->height;

                PDEBUG("New root geometry: %dx%d\n", e->width, e->height);

                /*
                 * FIXME: If the root suddenly got a lot smaller and
                 * some windows are outside of the root window, we
                 * need to rearrange them to fit the new geometry.
                 */
            }
        }
        break;
        
        case XCB_CONFIGURE_REQUEST:
        {
            xcb_configure_request_event_t *e
                = (xcb_configure_request_event_t *)ev;
            uint32_t mask = 0;
            uint32_t values[7];
            int i = -1;
            
            PDEBUG("event: Configure request. mask = %d\n", e->value_mask);

            /* Check if it's anything we care about, like a resize or move. */

            if (e->value_mask & XCB_CONFIG_WINDOW_X)
            {
                PDEBUG("Changing X coordinate to %d\n", e->x);
                mask |= XCB_CONFIG_WINDOW_X;
                i ++;                
                values[i] = e->x;

            }

            if (e->value_mask & XCB_CONFIG_WINDOW_Y)
            {
                PDEBUG("Changing Y coordinate to %d.\n", e->y);
                mask |= XCB_CONFIG_WINDOW_Y;
                i ++;                
                values[i] = e->y;

            }
            
            if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
            {
                PDEBUG("Changing width to %d.\n", e->width);
                mask |= XCB_CONFIG_WINDOW_WIDTH;
                i ++;                
                values[i] = e->width;
            }
            
            if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
            {
                PDEBUG("Changing height to %d.\n", e->height);
                mask |= XCB_CONFIG_WINDOW_HEIGHT;
                i ++;                
                values[i] = e->height;
            }

#if 0
            /* Unsure. Do we allow this? */
            if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE)
            {
                PDEBUG("Changing stack order.\n");
                mask |= XCB_CONFIG_WINDOW_STACK_MODE;
                i ++;                
                values[i] = e->stack_mode;
                break;
            }
#endif
            
            /*
             * Still left to decide about:
             *
             * XCB_CONFIG_WINDOW_SIBLING
             * XCB_CONFIG_WINDOW_BORDER_WIDTH
             */

            if (-1 != i)
            {
                xcb_configure_window(conn, e->window, mask, values);
                xcb_flush(conn);
            }
        }
        break;

        case XCB_CIRCULATE_REQUEST:
        {
            xcb_circulate_request_event_t *e
                = (xcb_circulate_request_event_t *)ev;

            /*
             * Subwindow e->window to parent e->event is about to be
             * restacked.
             *
             * Just do what was requested, e->place is either
             * XCB_PLACE_ON_TOP or _ON_BOTTOM. We don't care.
             */

            xcb_circulate_window(conn, e->window, e->place);
            
        }
        break;
        
        } /* switch */
        
        free(ev);
    }
}

int main(int argc, char **argv)
{
    uint32_t mask = 0;
    uint32_t values[2];
    char ch;                    /* Option character */
    xcb_void_cookie_t cookie;
    xcb_generic_error_t *error;
    xcb_drawable_t root;

    conf.borders = true;
    
    while (1)
    {
        ch = getopt(argc, argv, "bm");
        if (-1 == ch)
        {
                
            /* No more options, break out of while loop. */
            break;
        }
        
        switch (ch)
        {
        case 'b':
            /* No borders. */
            conf.borders = false;
            break;
        }
    }
    
    conn = xcb_connect(NULL, NULL);
    if (xcb_connection_has_error(conn))
    {
        perror("xcb_connect");
        exit(1);
    }
    
    /* Get the first screen */
    screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
    root = screen->root;
    
    PDEBUG("Screen size: %dx%d\nRoot window: %d\n", screen->width_in_pixels,
           screen->height_in_pixels, screen->root);

    /* FIXME: Get some colours. */
    
    /* Loop over all clients and set up stuff. */
    if (0 != setupscreen())
    {
        fprintf(stderr, "Failed to initialize windows. Exiting.\n");
        exit(1);
    }

    /* Set up key bindings. */
    if (0 != setupkeys())
    {
        fprintf(stderr, "mcwm: Couldn't set up keycodes. Exiting.");
        exit(1);
    }

    /* Grab some keys and mouse buttons. */

    xcb_grab_key(conn, 1, root, MODKEY, XCB_NO_SYMBOL,
                 XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);

    xcb_grab_button(conn, 0, root, XCB_EVENT_MASK_BUTTON_PRESS
                    | XCB_EVENT_MASK_BUTTON_RELEASE,
                    XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, root, XCB_NONE,
                    1 /* left mouse button */,
                    MOUSEMODKEY);

    xcb_grab_button(conn, 0, root, XCB_EVENT_MASK_BUTTON_PRESS
                    | XCB_EVENT_MASK_BUTTON_RELEASE,
                    XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, root, XCB_NONE,
                    2 /* middle mouse button */,
                    MOUSEMODKEY);

    xcb_grab_button(conn, 0, root, XCB_EVENT_MASK_BUTTON_PRESS
                    | XCB_EVENT_MASK_BUTTON_RELEASE,
                    XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, root, XCB_NONE,
                    3 /* right mouse button */,
                    MOUSEMODKEY);

    /* Subscribe to events. */
    mask = XCB_CW_EVENT_MASK;

    values[0] = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT
        | XCB_EVENT_MASK_STRUCTURE_NOTIFY
        | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY;

    cookie =
        xcb_change_window_attributes_checked(conn, root, mask, values);
    error = xcb_request_check(conn, cookie);

    xcb_flush(conn);
    
    if (NULL != error)
    {
        fprintf(stderr, "mcwm: Can't get SUBSTRUCTURE REDIRECT. "
                "Error code: %d\n"
                "Another window manager running? Exiting.\n",
                error->error_code);

        xcb_disconnect(conn);
        
        exit(1);
    }

    /* Loop over events. */
    events();

    xcb_disconnect(conn);
        
    exit(0);
}