aboutsummaryrefslogtreecommitdiff
path: root/src/fluxbox.cc
blob: d0069b9098283db69c11d362a249018941dac636 (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
// fluxbox.cc for Fluxbox Window Manager
// Copyright (c) 2001 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// blackbox.cc for blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net)
//
// 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.

#include "fluxbox.hh"

#include "Screen.hh"
#include "Window.hh"
#include "Workspace.hh"
#include "AtomHandler.hh"
#include "FbCommands.hh"
#include "WinClient.hh"
#include "Keys.hh"
#include "FbAtoms.hh"
#include "FocusControl.hh"
#include "Layer.hh"

#include "defaults.hh"
#include "Debug.hh"

#include "FbTk/I18n.hh"
#include "FbTk/Image.hh"
#include "FbTk/FileUtil.hh"
#include "FbTk/ImageControl.hh"
#include "FbTk/EventManager.hh"
#include "FbTk/LuaUtil.hh"
#include "FbTk/StringUtil.hh"
#include "FbTk/Util.hh"
#include "FbTk/LResource.hh"
#include "FbTk/SimpleCommand.hh"
#include "FbTk/XrmDatabaseHelper.hh"
#include "FbTk/Command.hh"
#include "FbTk/RefCount.hh"
#include "FbTk/CompareEqual.hh"
#include "FbTk/Transparent.hh"
#include "FbTk/Select2nd.hh"
#include "FbTk/Compose.hh"
#include "FbTk/KeyUtil.hh"
#include "FbTk/MemFun.hh"

//Use GNU extensions
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#ifdef USE_NEWWMSPEC
#include "Ewmh.hh"
#endif // USE_NEWWMSPEC
#ifdef REMEMBER
#include "Remember.hh"
#endif // REMEMBER

// X headers
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xresource.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>

// X extensions
#ifdef SHAPE
#include <X11/extensions/shape.h>
#endif // SHAPE
#ifdef HAVE_RANDR
#include <X11/extensions/Xrandr.h>
#endif // HAVE_RANDR

// system headers

#ifdef HAVE_CSTDIO
  #include <cstdio>
#else
  #include <stdio.h>
#endif
#ifdef HAVE_CSTDLIB
  #include <cstdlib>
#else
  #include <stdlib.h>
#endif
#ifdef HAVE_CSTRING
  #include <cstring>
#else
  #include <string.h>
#endif

#ifdef HAVE_UNISTD_H
#include <sys/types.h>
#include <unistd.h>
#endif // HAVE_UNISTD_H

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif // HAVE_SYS_PARAM_H

#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif // HAVE_SYS_SELECT_H

#ifdef HAVE_SYS_STAT_H
#include <sys/types.h>
#include <sys/stat.h>
#endif // HAVE_SYS_STAT_H

#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif // HAVE_SYS_WAIT_H

#include <iostream>
#include <memory>
#include <algorithm>
#include <typeinfo>

using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::bind2nd;
using std::mem_fun;
using std::equal_to;
using std::hex;
using std::dec;

using namespace FbTk;

namespace {

Window last_bad_window = None;

// *** NOTE: if you want to debug here the X errors are
//     coming from, you should turn on the XSynchronise call below
int handleXErrors(Display *d, XErrorEvent *e) {
    if (e->error_code == BadWindow)
        last_bad_window = e->resourceid;
#ifdef DEBUG
    else {
        // ignore bad window ones, they happen a lot
        // when windows close themselves
        char errtxt[128];

        XGetErrorText(d, e->error_code, errtxt, 128);
        cerr << "Fluxbox: X Error: " 
             << errtxt 
             << "(" <<(int)e->error_code << ") opcodes " 
             << (int)e->request_code 
             << "/" 
             << (int)e->minor_code 
             << " resource 0x" << hex <<(int)e->resourceid 
             << dec << endl;
//        if (e->error_code != 9 && e->error_code != 183)
//            kill(0, 2);
    }
#endif // !DEBUG

    return False;
}



/* functor to call a memberfunction with by a reference argument
   other places needs this helper as well it should be moved
   to FbTk/

   g++-4.1 does not like to work with:

      struct Bar;
      struct Foo {
          void foo(Bar&);
      };

      Bar bar;
      bind2nd(mem_fun(&F::foo), bar);

   it complaints about not beeing able to store a reference to
   a reference (Bar&&).

   'CallMemFunWithRefArg' makes g++-4.1 happy without
   having to consider switching over to boost::bind() or enforcing 
   a newer compiler.
 */
template <typename Type, typename ArgType, typename ResultType>
struct CallMemFunWithRefArg : std::unary_function<Type, ResultType> {

    explicit CallMemFunWithRefArg(ResultType (Type::*func)(ArgType), ArgType arg) :
        m_arg(arg),
        m_func(func) { }

    ResultType operator()(Type* p) const {
        (*p.*m_func)(m_arg);
    }

    ArgType m_arg;
    ResultType (Type::*m_func)(ArgType);
};


} // end anonymous

//static singleton var
Fluxbox *Fluxbox::s_singleton=0;

Fluxbox::Fluxbox(int argc, char **argv,
                 const std::string& dpy_name,
                 const std::string& rc_path, const std::string& rc_filename, bool xsync)
    : FbTk::App(dpy_name.c_str()),
      m_l(new Lua),
      m_fbatoms(FbAtoms::instance()),
      m_resourcemanager("session", *m_l, 5),

      m_RC_PATH(rc_path),
      m_RC_INIT_FILE("init"),
      m_rc_ignoreborder(m_resourcemanager, false, "ignoreBorder"),
      m_rc_pseudotrans(m_resourcemanager, false, "forcePseudoTransparency"),
      m_rc_colors_per_channel(m_resourcemanager, 4, "colorsPerChannel", RangedIntTraits(2, 6)),
      m_rc_double_click_interval(m_resourcemanager, 250, "doubleClickInterval"),
      m_rc_tabs_padding(m_resourcemanager, 0, "tabPadding"),
      m_rc_stylefile(m_resourcemanager, DEFAULTSTYLE, "styleFile"),
      m_rc_styleoverlayfile(m_resourcemanager, m_RC_PATH + "/overlay", "styleOverlay"),
      m_rc_menufile(m_resourcemanager, m_RC_PATH + "/menu.lua", "menuFile"),
      m_rc_keyfile(m_resourcemanager, m_RC_PATH + "/keys.lua", "keyFile"),
      m_rc_appsfile(m_resourcemanager, m_RC_PATH + "/apps", "appsFile"),
      m_rc_tabs_attach_area(m_resourcemanager, ATTACH_AREA_WINDOW, "tabsAttachArea"),
      m_rc_cache_life(m_resourcemanager, 5, "cacheLife"),
      m_rc_cache_max(m_resourcemanager, 200, "cacheMax"),
      m_rc_auto_raise_delay(m_resourcemanager, 250, "autoRaiseDelay"),
      m_masked_window(0),
      m_mousescreen(0),
      m_keyscreen(0),
      m_last_time(0),
      m_masked(0),
      m_rc_file(rc_filename),
      m_argv(argv), m_argc(argc),
      m_showing_dialog(false),
      m_starting(true),
      m_restarting(false),
      m_shutdown(false),
      m_server_grabs(0),
      m_randr_event_type(0) {

    _FB_USES_NLS;
    if (s_singleton != 0)
        throw _FB_CONSOLETEXT(Fluxbox, FatalSingleton, "Fatal! There can only one instance of fluxbox class.", "Error displayed on weird error where an instance of the Fluxbox class already exists!");

    if (display() == 0) {
        throw _FB_CONSOLETEXT(Fluxbox, NoDisplay,
                      "Can not connect to X server.\nMake sure you started X before you start Fluxbox.",
                      "Error message when no X display appears to exist");
    }

    Display *disp = FbTk::App::instance()->display();
    // For KDE dock applets
    // KDE v1.x
    m_kwm1_dockwindow = XInternAtom(disp,
                                    "KWM_DOCKWINDOW", False);
    // KDE v2.x
    m_kwm2_dockwindow = XInternAtom(disp,
                                    "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", False);
    // setup X error handler
    XSetErrorHandler((XErrorHandler) handleXErrors);

    //catch system signals
    SignalHandler &sigh = SignalHandler::instance();
    sigh.registerHandler(SIGSEGV, this);
    sigh.registerHandler(SIGFPE, this);
    sigh.registerHandler(SIGTERM, this);
    sigh.registerHandler(SIGINT, this);
#ifndef _WIN32
    sigh.registerHandler(SIGPIPE, this); // e.g. output sent to grep
    sigh.registerHandler(SIGCHLD, this);
    sigh.registerHandler(SIGHUP, this);
    sigh.registerHandler(SIGUSR1, this);
    sigh.registerHandler(SIGUSR2, this);
#endif

    //
    // setup timer
    // This timer is used to we can issue a safe reconfig command.
    // Because when the command is executed we shouldn't do reconfig directly
    // because it could affect ongoing menu stuff so we need to reconfig in
    // the next event "round".
    FbTk::RefCount<FbTk::Command<void> > reconfig_cmd(new FbTk::SimpleCommand<Fluxbox>(*this, &Fluxbox::reconfigure));
    m_reconfig_timer.setTimeout(0, 1);
    m_reconfig_timer.setCommand(reconfig_cmd);
    m_reconfig_timer.fireOnce(true);

    if (xsync)
        XSynchronize(disp, True);

    s_singleton = this;
    m_have_shape = false;
    m_shape_eventbase = 0;
#ifdef SHAPE
    int shape_err;
    m_have_shape = XShapeQueryExtension(disp, &m_shape_eventbase, &shape_err);
#endif // SHAPE

#ifdef HAVE_RANDR
    // get randr event type
    int randr_error_base;
    XRRQueryExtension(disp, &m_randr_event_type, &randr_error_base);
#endif // HAVE_RANDR

    join(m_rc_pseudotrans.modifiedSig(), &FbTk::Transparent::usePseudoTransparent);
    join(m_rc_stylefile.modifiedSig(), MemFunIgnoreArgs(*this, &Fluxbox::styleChanged));
    join(m_rc_styleoverlayfile.modifiedSig(), MemFunIgnoreArgs(*this, &Fluxbox::styleChanged));

    load_rc();

    grab();

    if (! XSupportsLocale())
        cerr<<_FB_CONSOLETEXT(Fluxbox, WarningLocale, 
                              "Warning: X server does not support locale", 
                              "XSupportsLocale returned false")<<endl;

    if (XSetLocaleModifiers("") == 0)
        cerr<<_FB_CONSOLETEXT(Fluxbox, WarningLocaleModifiers, 
                              "Warning: cannot set locale modifiers", 
                              "XSetLocaleModifiers returned false")<<endl;


#ifdef HAVE_GETPID
    m_fluxbox_pid = XInternAtom(disp, "_BLACKBOX_PID", False);
#endif // HAVE_GETPID


    // Create keybindings handler and load keys file
    // Note: this needs to be done before creating screens
    m_key.reset(new Keys);

    vector<int> screens;
    int i;

    // default is "use all screens"
    for (i = 0; i < ScreenCount(disp); i++)
        screens.push_back(i);

    // find out, on what "screens" fluxbox should run
    // FIXME(php-coder): maybe it worths moving this code to main.cc, where command line is parsed?
    for (i = 1; i < m_argc; i++) {
        if (! strcmp(m_argv[i], "-screen")) {
            if ((++i) >= m_argc) {
                cerr << _FB_CONSOLETEXT(main, ScreenRequiresArg, 
                                        "error, -screen requires argument", 
                                        "the -screen option requires a file argument") << endl;
                exit(EXIT_FAILURE);
            }

            // "all" is default
            if (! strcmp(m_argv[i], "all"))
                break;

            vector<string> vals;
            vector<int> scrtmp;
            int scrnr = 0;
            FbTk::StringUtil::stringtok(vals, m_argv[i], ",:");
            for (vector<string>::iterator scrit = vals.begin();
                 scrit != vals.end(); scrit++) {
                scrnr = atoi(scrit->c_str());
                if (scrnr >= 0 && scrnr < ScreenCount(disp))
                    scrtmp.push_back(scrnr);
            }

            if (!vals.empty())
                swap(scrtmp, screens);
        }
    }

    // create screens
    for (size_t s = 0; s < screens.size(); s++) {
        std::string sc_nr = FbTk::StringUtil::number2String(screens[s]);
        BScreen *screen = new BScreen(m_resourcemanager,
                                      std::string("screen") + sc_nr,
                                      screens[s], NUM_LAYERS);

        // already handled
        if (! screen->isScreenManaged()) {
            delete screen;
            continue;
        }

        // add to our list
        m_screen_list.push_back(screen);
    }

    if (m_screen_list.empty()) {
        throw _FB_CONSOLETEXT(Fluxbox, ErrorNoScreens,
                             "Couldn't find screens to manage.\nMake sure you don't have another window manager running.",
                             "Error message when no unmanaged screens found - usually means another window manager is running");
    }

    m_keyscreen = m_mousescreen = m_screen_list.front();

#ifdef USE_NEWWMSPEC
    addAtomHandler(new Ewmh()); // for Extended window manager atom support
#endif // USE_NEWWMSPEC
    // parse apps file after creating screens (so we can tell if it's a restart
    // for [startup] items) but before creating windows
    // this needs to be after ewmh and gnome, so state atoms don't get
    // overwritten before they're applied
#ifdef REMEMBER
    addAtomHandler(new Remember()); // for remembering window attribs
#endif // REMEMBER

    // init all "screens"
    STLUtil::forAll(m_screen_list, bind1st(mem_fun(&Fluxbox::initScreen), this));

    XAllowEvents(disp, ReplayPointer, CurrentTime);

    //XSynchronize(disp, False);
    sync(false);

    ungrab();

    m_starting = false;
    //
    // For dumping theme items
    // FbTk::ThemeManager::instance().listItems();
    //
}


Fluxbox::~Fluxbox() {

    // this needs to be destroyed before screens; otherwise, menus stored in
    // key commands cause a segfault when the LayerItem is destroyed
    m_key.reset(0);

    leaveAll(); // leave all connections

    // destroy screens (after others, as they may do screen things)
    FbTk::STLUtil::destroyAndClear(m_screen_list);

    FbTk::STLUtil::destroyAndClear(m_atomhandler);
}


void Fluxbox::initScreen(BScreen *screen) {

    // now we can create menus (which needs this screen to be in screen_list)
    screen->initMenus();
    screen->initWindows();

    // attach screen signals to this
    join(screen->workspaceAreaSig(),
         FbTk::MemFun(*this, &Fluxbox::workspaceAreaChanged));

    join(screen->focusedWindowSig(),
         FbTk::MemFun(*this, &Fluxbox::focusedWindowChanged));

    join(screen->clientListSig(),
         FbTk::MemFun(*this, &Fluxbox::clientListChanged));

    join(screen->workspaceNamesSig(), 
         FbTk::MemFun(*this, &Fluxbox::workspaceNamesChanged));
    join(screen->currentWorkspaceSig(), 
         FbTk::MemFun(*this, &Fluxbox::workspaceChanged));

    join(screen->workspaceCountSig(), 
         FbTk::MemFun(*this, &Fluxbox::workspaceCountChanged));

    // initiate atomhandler for screen specific stuff
    STLUtil::forAll(m_atomhandler, 
            CallMemFunWithRefArg<AtomHandler, BScreen&, void>(&AtomHandler::initForScreen, *screen));
    //STLUtil::forAll(m_atomhandler, bind2nd(mem_fun(&AtomHandler::initForScreen), *screen));

    FocusControl::revertFocus(*screen); // make sure focus style is correct

}


void Fluxbox::eventLoop() {
    Display *disp = display();
    while (!m_shutdown) {
        if (XPending(disp)) {
            XEvent e;
            XNextEvent(disp, &e);

            if (last_bad_window != None && e.xany.window == last_bad_window &&
                e.type != DestroyNotify) { // we must let the actual destroys through
                if (e.type == FocusOut)
                    revertFocus();
                else
                    fbdbg<<"Fluxbox::eventLoop(): removing bad window from event queue"<<endl;
            } else {
                last_bad_window = None;
                handleEvent(&e);
            }
        } else {
            FbTk::Timer::updateTimers(ConnectionNumber(disp)); //handle all timers
        }
    }
}

bool Fluxbox::validateWindow(Window window) const {
    XEvent event;
    if (XCheckTypedWindowEvent(display(), window, DestroyNotify, &event)) {
        XPutBackEvent(display(), &event);
        return false;
    }

    return true;
}

void Fluxbox::grab() {
    if (! m_server_grabs++)
       XGrabServer(display());
}

void Fluxbox::ungrab() {
    if (! --m_server_grabs)
        XUngrabServer(display());

    if (m_server_grabs < 0)
        m_server_grabs = 0;
}

void Fluxbox::handleEvent(XEvent * const e) {
    _FB_USES_NLS;
    m_last_event = *e;

    // it is possible (e.g. during moving) for a window
    // to mask all events to go to it
    if ((m_masked == e->xany.window) && m_masked_window) {
        if (e->type == MotionNotify) {
            m_last_time = e->xmotion.time;
            m_masked_window->motionNotifyEvent(e->xmotion);
            return;
        } else if (e->type == ButtonRelease) {
            e->xbutton.window = m_masked_window->fbWindow().window();
        }

    }

    // update key/mouse screen and last time before we enter other eventhandlers
    if (e->type == KeyPress ||
        e->type == KeyRelease) {
        m_keyscreen = searchScreen(e->xkey.root);
    } else if (e->type == ButtonPress ||
               e->type == ButtonRelease ||
               e->type == MotionNotify ) {
        if (e->type == MotionNotify)
            m_last_time = e->xmotion.time;
        else
            m_last_time = e->xbutton.time;

        m_mousescreen = searchScreen(e->xbutton.root);
    } else if (e->type == EnterNotify ||
               e->type == LeaveNotify) {
        m_last_time = e->xcrossing.time;
        m_mousescreen = searchScreen(e->xcrossing.root);
    } else if (e->type == PropertyNotify) {
        m_last_time = e->xproperty.time;
        // check transparency atoms if it's a root pm

        BScreen *screen = searchScreen(e->xproperty.window);
        if (screen) {
            screen->propertyNotify(e->xproperty.atom);
        }
    }

    // try FbTk::EventHandler first
    FbTk::EventManager::instance()->handleEvent(*e);

    switch (e->type) {
    case ButtonRelease:
    case ButtonPress:
        break;
    case ConfigureRequest: {

        if (!searchWindow(e->xconfigurerequest.window)) {

            grab();

            if (validateWindow(e->xconfigurerequest.window)) {
                XWindowChanges xwc;

                xwc.x = e->xconfigurerequest.x;
                xwc.y = e->xconfigurerequest.y;
                xwc.width = e->xconfigurerequest.width;
                xwc.height = e->xconfigurerequest.height;
                xwc.border_width = e->xconfigurerequest.border_width;
                xwc.sibling = e->xconfigurerequest.above;
                xwc.stack_mode = e->xconfigurerequest.detail;

                XConfigureWindow(FbTk::App::instance()->display(),
                                 e->xconfigurerequest.window,
                                 e->xconfigurerequest.value_mask, &xwc);
            }

            ungrab();
        } // else already handled in FluxboxWindow::handleEvent

    }
        break;
    case MapRequest: {

        fbdbg<<"MapRequest for 0x"<<hex<<e->xmaprequest.window<<dec<<endl;

        WinClient *winclient = searchWindow(e->xmaprequest.window);

        if (! winclient) {
            BScreen *screen = 0;
            int screen_num;
            XWindowAttributes attr;
            // find screen
            if (XGetWindowAttributes(display(),
                                     e->xmaprequest.window,
                                     &attr) && attr.screen != 0) {
                screen_num = XScreenNumberOfScreen(attr.screen);

                // find screen
                ScreenList::iterator screen_it = find_if(m_screen_list.begin(),
                                                         m_screen_list.end(),
                                                         FbTk::CompareEqual<BScreen>(&BScreen::screenNumber, screen_num));
                if (screen_it != m_screen_list.end())
                    screen = *screen_it;
            }
            // try with parent if we failed to find screen num
            if (screen == 0)
               screen = searchScreen(e->xmaprequest.parent);

            if (screen == 0) {
                cerr<<"Fluxbox "<<_FB_CONSOLETEXT(Fluxbox, CantMapWindow, "Warning! Could not find screen to map window on!", "")<<endl;
            } else
                screen->createWindow(e->xmaprequest.window);

        } else {
            // we don't handle MapRequest in FluxboxWindow::handleEvent
            if (winclient->fbwindow())
                winclient->fbwindow()->mapRequestEvent(e->xmaprequest);
        }

    }
        break;
    case MapNotify:
        // handled directly in FluxboxWindow::handleEvent
        break;
    case UnmapNotify:
        handleUnmapNotify(e->xunmap);
	break;
    case MappingNotify:
        // Update stored modifier mapping
        fbdbg<<"MappingNotify"<<endl;

        if (e->xmapping.request == MappingKeyboard
            || e->xmapping.request == MappingModifier) {
            XRefreshKeyboardMapping(&e->xmapping);
            FbTk::KeyUtil::instance().init(); // reinitialise the key utils
            // reconfigure keys (if the mapping changes, they don't otherwise update
            m_key->regrab();
        }
        break;
    case CreateNotify:
	break;
    case DestroyNotify: {
        WinClient *winclient = searchWindow(e->xdestroywindow.window);
        if (winclient != 0) {
            FluxboxWindow *win = winclient->fbwindow();
            if (win)
                win->destroyNotifyEvent(e->xdestroywindow);
        }

    }
        break;
    case MotionNotify:
        m_last_time = e->xmotion.time;
        break;
    case PropertyNotify: {
        m_last_time = e->xproperty.time;
        WinClient *winclient = searchWindow(e->xproperty.window);
        if (winclient == 0)
            break;
        // most of them are handled in FluxboxWindow::handleEvent
        // but some special cases like ewmh propertys needs to be checked
        for (AtomHandlerContainerIt it= m_atomhandler.begin();
             it != m_atomhandler.end(); it++) {
            if ( (*it)->propertyNotify(*winclient, e->xproperty.atom))
                break;
        }
    } break;
    case EnterNotify: {

        m_last_time = e->xcrossing.time;

        if (e->xcrossing.mode == NotifyGrab)
            break;

        BScreen *screen = 0;
        if ((e->xcrossing.window == e->xcrossing.root) &&
            (screen = searchScreen(e->xcrossing.window))) {
            screen->imageControl().installRootColormap();

        }

    } break;
    case LeaveNotify:
        m_last_time = e->xcrossing.time;
        break;
    case Expose:
        break;
    case KeyRelease:
    case KeyPress:
        break;
    case ColormapNotify: {
        BScreen *screen = searchScreen(e->xcolormap.window);

        if (screen != 0) {
            screen->setRootColormapInstalled((e->xcolormap.state ==
                                              ColormapInstalled) ? true : false);
        }
    } break;
    case FocusIn: {

        // a grab is something of a pseudo-focus event, so we ignore
        // them, here we ignore some window receiving it
        if (e->xfocus.mode == NotifyGrab ||
            e->xfocus.mode == NotifyUngrab ||
            e->xfocus.detail == NotifyPointer ||
            e->xfocus.detail == NotifyInferior)
            break;

        if (FbTk::Menu::focused() &&
            FbTk::Menu::focused()->window() == e->xfocus.window) {
            m_keyscreen = findScreen(FbTk::Menu::focused()->screenNumber());
            FocusControl::setFocusedWindow(0);
            break;
        }

        WinClient *winclient = searchWindow(e->xfocus.window);
        if (winclient)
            m_keyscreen = &winclient->screen();
        FocusControl::setFocusedWindow(winclient);

    } break;
    case FocusOut:{
        // and here we ignore some window losing the special grab focus
        if (e->xfocus.mode == NotifyGrab ||
            e->xfocus.detail == NotifyPointer ||
            e->xfocus.detail == NotifyInferior)
            break;

        WinClient *winclient = searchWindow(e->xfocus.window);
        if ((winclient == FocusControl::focusedWindow() ||
             FocusControl::focusedWindow() == 0) &&
            // we don't unfocus a moving window
            (!winclient || !winclient->fbwindow() ||
             !winclient->fbwindow()->isMoving()))
            revertFocus();
    }
        break;
    case ClientMessage:
        handleClientMessage(e->xclient);
        break;
    default: {

#ifdef HAVE_RANDR
        if (e->type == m_randr_event_type) {
#ifdef HAVE_RANDR1_2
            XRRUpdateConfiguration(e);
#endif
            // update root window size in screen
            BScreen *scr = searchScreen(e->xany.window);
            if (scr != 0)
                scr->updateSize();
        }
#endif // HAVE_RANDR

    }

    }
}

void Fluxbox::handleUnmapNotify(XUnmapEvent &ue) {

    BScreen *screen = searchScreen(ue.event);

    if (screen) {
        /* Ignore all EnterNotify events until the pointer actually moves */
        screen->focusControl().ignoreAtPointer();
    }

    if (ue.event != ue.window && (!screen || !ue.send_event)) {
        return;
    }

    WinClient *winclient = searchWindow(ue.window);

    if (winclient != 0) {

        FluxboxWindow *win = winclient->fbwindow();
        if (!win) {
            delete winclient;
            return;
        }

        // this should delete client and adjust m_focused_window if necessary
        win->unmapNotifyEvent(ue);

    // according to http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4
    // a XWithdrawWindow is
    //   1) unmapping the window (which leads to the upper branch
    //   2) sends an synthetic unampevent (which is handled below)
    } else if (screen && ue.send_event) {
        XDeleteProperty(display(), ue.window, FbAtoms::instance()->getWMStateAtom());
        XUngrabButton(display(), AnyButton, AnyModifier, ue.window);
    }

}

/**
 * Handles XClientMessageEvent
 */
void Fluxbox::handleClientMessage(XClientMessageEvent &ce) {

#ifdef DEBUG
    char * atom = 0;
    if (ce.message_type)
        atom = XGetAtomName(FbTk::App::instance()->display(), ce.message_type);

    fbdbg<<__FILE__<<"("<<__LINE__<<"): ClientMessage. data.l[0]=0x"<<hex<<ce.data.l[0]<<
	"  message_type=0x"<<ce.message_type<<dec<<" = \""<<atom<<"\""<<endl;

    if (ce.message_type && atom) XFree((char *) atom);
#endif // DEBUG


    if (ce.format != 32)
        return;

    if (ce.message_type == m_fbatoms->getWMChangeStateAtom()) {
        WinClient *winclient = searchWindow(ce.window);
        if (! winclient || !winclient->fbwindow() || ! winclient->validateClient())
            return;

        if (ce.data.l[0] == IconicState)
            winclient->fbwindow()->iconify();
        if (ce.data.l[0] == NormalState)
            winclient->fbwindow()->deiconify();
    } else {
        WinClient *winclient = searchWindow(ce.window);
        BScreen *screen = searchScreen(ce.window);
        // note: we dont need screen nor winclient to be non-null,
        // it's up to the atomhandler to check that
        for (AtomHandlerContainerIt it= m_atomhandler.begin();
             it != m_atomhandler.end(); it++) {
            (*it)->checkClientMessage(ce, screen, winclient);
        }

    }
}

/// handle system signals
void Fluxbox::handleSignal(int signum) {
    _FB_USES_NLS;

    static int re_enter = 0;

    switch (signum) {
#ifndef _WIN32
    case SIGCHLD: // we don't want the child process to kill us
        // more than one process may have terminated
        while (waitpid(-1, 0, WNOHANG | WUNTRACED) > 0);
        break;
    case SIGHUP:
        restart();
        break;
    case SIGUSR1:
        load_rc();
        break;
    case SIGUSR2:
        m_reconfig_timer.start();
        break;
#endif
    case SIGSEGV:
        abort();
        break;
    case SIGFPE:
    case SIGINT:
#ifndef _WIN32
    case SIGPIPE:
#endif
    case SIGTERM:
        shutdown();
        break;
    default:
        fprintf(stderr,
                _FB_CONSOLETEXT(BaseDisplay, SignalCaught, "%s:      signal %d caught\n", "signal catch debug message. Include %s for Command<void> and %d for signal number").c_str(),
                m_argv[0], signum);

        if (! m_starting && ! re_enter) {
            re_enter = 1;
            cerr<<_FB_CONSOLETEXT(BaseDisplay, ShuttingDown, "Shutting Down\n", "Quitting because of signal, end with newline");
            shutdown();
        }


        cerr<<_FB_CONSOLETEXT(BaseDisplay, Aborting, "Aborting... dumping core\n", "Aboring and dumping core, end with newline");
        abort();
        break;
    }
}


void Fluxbox::windowDied(Focusable &focusable) {
    FluxboxWindow *fbwin = focusable.fbwindow();

    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
        CallMemFunWithRefArg<AtomHandler, FluxboxWindow&, void>(&AtomHandler::updateFrameClose, *focusable.fbwindow()));

    // make sure each workspace get this
    BScreen &scr = focusable.screen();
    scr.removeWindow(fbwin);
    if (FocusControl::focusedFbWindow() == fbwin)
        FocusControl::setFocusedFbWindow(0);
}

void Fluxbox::clientDied(Focusable &focusable) {
    WinClient &client = dynamic_cast<WinClient &>(focusable);

    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
            CallMemFunWithRefArg<AtomHandler, WinClient&, void>(&AtomHandler::updateClientClose, client));

    BScreen &screen = client.screen();

    // At this point, we trust that this client is no longer in the
    // client list of its frame (but it still has reference to the frame)
    // We also assume that any remaining active one is the last focused one

    // This is where we revert focus on window close
    // NOWHERE ELSE!!!
    if (FocusControl::focusedWindow() == &client) {
        FocusControl::unfocusWindow(client);
        // make sure nothing else uses this window before focus reverts
        FocusControl::setFocusedWindow(0);
    } else if (FocusControl::expectingFocus() == &client) {
        FocusControl::setExpectingFocus(0);
        revertFocus();
    }

    screen.removeClient(client);
}

void Fluxbox::windowWorkspaceChanged(FluxboxWindow &win) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
        CallMemFunWithRefArg<AtomHandler, FluxboxWindow&, void>(&AtomHandler::updateWorkspace, win));
}

void Fluxbox::windowStateChanged(FluxboxWindow &win) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
        CallMemFunWithRefArg<AtomHandler, FluxboxWindow&, void>(&AtomHandler::updateState, win));

    // if window changed to iconic state
    // add to icon list
    if (win.isIconic()) {
        win.screen().addIcon(&win);
        Workspace *space = win.screen().getWorkspace(win.workspaceNumber());
        if (space != 0)
            space->removeWindow(&win, true);
    }

    if (win.isStuck()) {
        // if we're sticky then reassociate window
        // to all workspaces
        BScreen &scr = win.screen();
        if (scr.currentWorkspaceID() != win.workspaceNumber())
            scr.reassociateWindow(&win, scr.currentWorkspaceID(), true);
    }
}

void Fluxbox::windowLayerChanged(FluxboxWindow &win) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
        CallMemFunWithRefArg<AtomHandler, FluxboxWindow&, void>(&AtomHandler::updateLayer, win));
}

void Fluxbox::styleChanged() {
    FbTk::ThemeManager::instance().load(*getStyleResource(), getStyleOverlayFilename());
}

void Fluxbox::attachSignals(FluxboxWindow &win) {
    join(win.stateSig(), FbTk::MemFun(*this, &Fluxbox::windowStateChanged));
    join(win.workspaceSig(), FbTk::MemFun(*this, &Fluxbox::windowWorkspaceChanged));
    join(win.layerSig(), FbTk::MemFun(*this, &Fluxbox::windowLayerChanged));
    join(win.dieSig(), FbTk::MemFun(*this, &Fluxbox::windowDied));
    STLUtil::forAll(m_atomhandler,
            CallMemFunWithRefArg<AtomHandler, FluxboxWindow&, void>(&AtomHandler::setupFrame, win));
}

void Fluxbox::attachSignals(WinClient &winclient) {
    join(winclient.dieSig(), FbTk::MemFun(*this, &Fluxbox::clientDied));
    STLUtil::forAll(m_atomhandler,
            CallMemFunWithRefArg<AtomHandler, WinClient&, void>(&AtomHandler::setupClient, winclient));
}

BScreen *Fluxbox::searchScreen(Window window) {

    ScreenList::iterator it = m_screen_list.begin();
    ScreenList::iterator it_end = m_screen_list.end();
    for (; it != it_end; ++it) {
        if (*it && (*it)->rootWindow() == window)
            return *it;
    }

    return 0;
}


AtomHandler* Fluxbox::getAtomHandler(const string &name) {
    if ( name != "" ) {

        AtomHandlerContainerIt it;
        for (it = m_atomhandler.begin(); it != m_atomhandler.end(); it++) {
            if (name == (*it)->getName())
                return *it;
        }
    }
    return 0;
}
void Fluxbox::addAtomHandler(AtomHandler *atomh) {
    m_atomhandler.insert(atomh);
}

void Fluxbox::removeAtomHandler(AtomHandler *atomh) {
    m_atomhandler.erase(atomh);
}

WinClient *Fluxbox::searchWindow(Window window) {
    WinClientMap::iterator it = m_window_search.find(window);
    if (it != m_window_search.end())
        return it->second;

    WindowMap::iterator git = m_window_search_group.find(window);
    return git == m_window_search_group.end() ? 0 : &git->second->winClient();
}


/* Not implemented until we know how it'll be used
 * Recall that this refers to ICCCM groups, not fluxbox tabgroups
 * See ICCCM 4.1.11 for details
 */
/*
WinClient *Fluxbox::searchGroup(Window window) {
}
*/

void Fluxbox::saveWindowSearch(Window window, WinClient *data) {
    m_window_search[window] = data;
}

/* some windows relate to the whole group */
void Fluxbox::saveWindowSearchGroup(Window window, FluxboxWindow *data) {
    m_window_search_group[window] = data;
}

void Fluxbox::saveGroupSearch(Window window, WinClient *data) {
    m_group_search.insert(pair<const Window, WinClient *>(window, data));
}


void Fluxbox::removeWindowSearch(Window window) {
    m_window_search.erase(window);
}

void Fluxbox::removeWindowSearchGroup(Window window) {
    m_window_search_group.erase(window);
}

void Fluxbox::removeGroupSearch(Window window) {
    m_group_search.erase(window);
}

/// restarts fluxbox
void Fluxbox::restart(const char *prog) {
    shutdown();

    m_restarting = true;

    if (prog && *prog != '\0') {
        m_restart_argument = prog;
    }
}

/// prepares fluxbox for a shutdown
void Fluxbox::shutdown() {
    if (m_shutdown)
        return;

    m_shutdown = true;

    XSetInputFocus(FbTk::App::instance()->display(), PointerRoot, None, CurrentTime);

    STLUtil::forAll(m_screen_list, mem_fun(&BScreen::shutdown));

    sync(false);
}

/// saves resources
void Fluxbox::save_rc() {
    _FB_USES_NLS;

    string dbfile(getRcFilename());

    if (!dbfile.empty()) {
        m_resourcemanager.save(dbfile.c_str(), dbfile.c_str());
    } else
        cerr<<_FB_CONSOLETEXT(Fluxbox, BadRCFile, "rc filename is invalid!", "Bad settings file")<<endl;


    fbdbg<<__FILE__<<"("<<__LINE__<<"): ------------ SAVING DONE"<<endl;

}

/// @return filename of resource file
string Fluxbox::getRcFilename() {
    if (m_rc_file.empty())
        return getDefaultDataFilename(m_RC_INIT_FILE);
    return m_rc_file;
}

/// Provides default filename of data file
string Fluxbox::getDefaultDataFilename(const char *name) const {
    return m_RC_PATH + string("/") + name;
}

/// loads resources
void Fluxbox::load_rc() {

    try {
        m_resourcemanager.load(getRcFilename(), DEFAULT_INITFILE);
    }
    catch(std::runtime_error &) {
        // This should only happen if system-wide init file is broken.
        // Not much we can do about that, so we just ignore it
    }

    if (m_rc_menufile->empty())
        m_rc_menufile.setDefaultValue();

    if (m_rc_stylefile->empty())
        *m_rc_stylefile = DEFAULTSTYLE;
}

BScreen *Fluxbox::findScreen(int id) {

    BScreen* result = 0;
    ScreenList::iterator it = find_if(m_screen_list.begin(), m_screen_list.end(),
            FbTk::CompareEqual<BScreen>(&BScreen::screenNumber, id));

    if (it != m_screen_list.end())
        result = *it;

    return result;
}

void Fluxbox::reconfigure() {
    load_rc();
    STLUtil::forAll(m_screen_list, mem_fun(&BScreen::reconfigure));
}

void Fluxbox::revertFocus() {
    bool revert = m_keyscreen && !m_showing_dialog;

    if (revert) {
        // see if there are any more focus events in the queue
        XEvent ev;
        while (XCheckMaskEvent(display(), FocusChangeMask, &ev))
            handleEvent(&ev);
        if (FocusControl::focusedWindow() || FocusControl::expectingFocus())
            return; // already handled

        Window win;
        int blah;
        XGetInputFocus(display(), &win, &blah);

        // we only want to revert focus if it's left dangling, as some other
        // application may have set the focus to an unmanaged window
        if (win != None && win != PointerRoot && !searchWindow(win) &&
            win != m_keyscreen->rootWindow().window())
            revert = false;
    }

    if (revert)
        FocusControl::revertFocus(*m_keyscreen);
    else
        FocusControl::setFocusedWindow(0);
}

bool Fluxbox::validateClient(const WinClient *client) const {
    WinClientMap::const_iterator it =
        find_if(m_window_search.begin(),
                m_window_search.end(),
                Compose(bind2nd(equal_to<WinClient *>(), client),
                        Select2nd<WinClientMap::value_type>()));
    return it != m_window_search.end();
}

void Fluxbox::updateFrameExtents(FluxboxWindow &win) {
    STLUtil::forAll(m_atomhandler, 
            CallMemFunWithRefArg<AtomHandler, FluxboxWindow&, void>(&AtomHandler::updateFrameExtents, win));
}

void Fluxbox::workspaceCountChanged( BScreen& screen ) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
            CallMemFunWithRefArg<AtomHandler, BScreen&, void>(&AtomHandler::updateWorkspaceCount, screen));
}

void Fluxbox::workspaceChanged( BScreen& screen ) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
            CallMemFunWithRefArg<AtomHandler, BScreen&, void>(&AtomHandler::updateCurrentWorkspace, screen));
}

void Fluxbox::workspaceNamesChanged(BScreen &screen) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
            CallMemFunWithRefArg<AtomHandler, BScreen&, void>(&AtomHandler::updateWorkspaceNames, screen));
}

void Fluxbox::clientListChanged(BScreen &screen) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
            CallMemFunWithRefArg<AtomHandler, BScreen&, void>(&AtomHandler::updateClientList, screen));
}

void Fluxbox::focusedWindowChanged(BScreen &screen, 
                                   FluxboxWindow* win, 
                                   WinClient* client) {

    for (AtomHandlerContainerIt it= m_atomhandler.begin();
         it != m_atomhandler.end(); it++) {
        (*it)->updateFocusedWindow(screen, client ? client->window() : 0 );
    }
}

void Fluxbox::workspaceAreaChanged(BScreen &screen) {
    STLUtil::forAllIf(m_atomhandler, mem_fun(&AtomHandler::update),
            CallMemFunWithRefArg<AtomHandler, BScreen&, void>(&AtomHandler::updateWorkarea, screen));
}