forked from BurntSushi/pytyle1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pytyle
executable file
·298 lines (260 loc) · 11.9 KB
/
pytyle
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
#!/usr/bin/env python2
#===============================================================================
# PyTyle - A manual tiling manager
# Copyright (C) 2009 Andrew Gallant <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#===============================================================================
"""
pytyle
PyTyle is meant to be run as a daemon, that is, in the background. If you're
trying it out, feel free to run it in a terminal (especially if it isn't working
properly, it could be outputting some useful error messages). I personally
added PyTyle to my ~/.xinitrc like so:
pytyle &
The entire source code of PyTyle is *HEAVILY* documented. Why? Because there
aren't too many things I hate worse than undocumented code. I also love to
write about how clever I am :-)
Seriously though, I took extra care with this project because the documentation
for python-xlib is abysmal. I would help contribute to it myself, but this was
my first time using it (and python, incidentally), so my experience isn't up
to snuff with it. At some point, though, I would like to create a Python window
manager, and will probably use PyTyle (I like *manual* tiling) in it somewhere.
When and if that happens, I'll try to write up some better python-xlib
documentation. However, it looks like XCB is rising...
Anyway, if you're looking at PyTyle because it does something with python-xlib
that you want to know how to do (and I only say this because I did this myself
with many a different programs), then search no further than Probe.py and
possibly Event.py. No other files interface with python-xlib.
"""
# Some basics...
import time, sys, os, shutil, distutils.sysconfig, traceback
# What we need.
from PyTyle.Config import Config
from PyTyle.State import State
from PyTyle.Probe import PROBE
from PyTyle.Debug import DEBUG
from PyTyle.Desktop import Desktop
from PyTyle.Window import Window
from PyTyle.Event import Event
from PyTyle.Tile import Tile
# Before moving on, we must make sure the window
# manager is running. If not, wait for it.
if not PROBE.is_wm_running():
while True:
time.sleep(1)
if PROBE.is_wm_running():
time.sleep(1)
break
# load configuration
# Very easy to use Python as a config file...
# Should I change it to a more traditional config?
try:
config_path = os.getenv('XDG_CONFIG_HOME')
if not config_path:
config_path = os.getenv('HOME') + '/.config'
config_path += '/pytyle'
config_file = "%s/pytylerc" % config_path
if not os.access(config_file, os.F_OK | os.R_OK):
if not os.path.exists(config_path):
os.makedirs(config_path)
shutil.copyfile("%s/PyTyle/pytylerc" % (distutils.sysconfig.get_python_lib()), config_file)
if os.access(config_file, os.F_OK | os.R_OK):
execfile(config_file)
except:
DEBUG.write("Could not write configuration file to home directory and load it. Exiting!")
DEBUG.write(traceback.format_exc())
sys.exit(0)
try:
# initialize the tilers dynamically, so all we need to do
# is add a tiler to Tilers, and add it to the configuration
for module in Config.MISC['tilers']:
tmp = __import__('PyTyle.Tilers.' + module, fromlist=[''])
Config.TILERS[module] = tmp.CLASS
# Initialize hot keys...
# See also, grab_key in Event.py
State.register_hotkeys()
# Load all the desktops. This will fetch a list
# of desktops from the window manager, instantiate
# each of them (which also initializes the screens),
# and finally sets the tilers for each screen.
Desktop.load_desktops()
# Scan for new (this is init, so all) windows, and
# loads them up with Window.load_window.
# load_window queries for window information, decides
# which screen a window is on, etc. It may also *NOT*
# load the given window if it decides it's a popup.
Window.load_new_windows()
# Asks the window manager for the currently active
# desktop and window, and updates the State
# accordingly (current desktop, current screen,
# and current window).
State.reload_active()
# Stall and await orders...
while True:
if State.needs_reload():
try:
config_path = os.getenv('XDG_CONFIG_HOME')
if not config_path:
config_path = os.getenv('HOME') + '/.config'
config_path += '/pytyle'
config_file = "%s/pytylerc" % config_path
if os.access(config_file, os.F_OK | os.R_OK):
execfile(config_file)
except:
DEBUG.write("Could not write configuration file to home directory and load it. Exiting!")
DEBUG.write(traceback.format_exc())
sys.exit(0)
# Reload the tiling modules
for module in Config.MISC['tilers']:
tmp = __import__('PyTyle.Tilers.' + module, fromlist=[''])
Config.TILERS[module] = tmp.CLASS
# Reload our key bindings
#
# Note: It seems like X keeps our previous key bindings
# even though we "ungrab" them only after we attempt to
# regrab the rest of the keybindings. This will thus spit
# out an error if run from the command line, but otherwise
# full functionality is here. I suppose the only problem
# might arise if you were trying to "free up" a key. You
# might need to restart PyTyle for that.
State.unregister_hotkeys()
State.register_hotkeys()
# And now wipe everything...
Desktop.reload_desktops()
State.did_reload()
# This is our queue of tilings that we need to flush.
# Screens are queued for tiling when windows change,
# disappear, popup, etc. We almost never make direct
# calls to the Tile.tile method, and instead "tell"
# the screen that it needs to be retiled.
if State.queue_has_screens():
while State.queue_has_screens():
screen = State.dequeue_screen()
Tile.dispatch(screen.get_tiler(), 'tile')
time.sleep(Config.misc('timeout'))
# This loads up the next event.
e = Event()
# If the event is a key press, we need to call our
# dispatcher to run the proper tiling action.
if e.is_keypress():
try:
Tile.dispatch(State.get_desktop()._VIEWPORT._SCREEN.get_tiler(), None, e.get_keycode(), e.get_masks())
except:
DEBUG.write("Could not complete key press request")
DEBUG.write(traceback.format_exc())
# If a window receives focus or changes to another
# desktop, then we need to reload the State with
# the proper active window.
#elif e.is_focus_in() or e.is_desktop_change():
elif e.is_active_change():
State.reload_active()
elif e.is_desktop_change():
time.sleep(Config.misc('timeout'))
State.reload_active(None, True)
# If the window manager's client list changes, then
# we need to add or remove a window
elif e.is_windowlist_change():
time.sleep(Config.misc('timeout'))
try:
Window.load_new_windows()
except:
DEBUG.write("Could not tile new window - could be a popup that disappear")
DEBUG.write(traceback.format_exc())
continue
try:
newwins = State.scan_all_windows()
for win in State.get_windows().values():
if long(win.id, 0) not in newwins:
win.delete()
except:
DEBUG.write("Could not properly handle window destruction")
DEBUG.write(traceback.format_exc())
continue
# A window changes when it's resized/moved, or when its
# desktop property changes. In those cases, we want to
# "refresh" the window with its real and current state.
#
# Note: Window.refresh() will do only as much work as
# is needed. It is guaranteed to query X for the current
# window information, but from there, it will selectively
# determine if screen(s) need updating, or if we need
# to reload PyTyle's State.
elif e.is_window_change():
try:
if e.get_window_id() in State.get_windows():
print e._event
State.get_windows()[e.get_window_id()].refresh()
except:
DEBUG.write("Could not properly handle window changing event (moved/resized/desktop change)")
DEBUG.write(traceback.format_exc())
# If a window's state changes, we need to find it in PyTyle
# and refresh it. Refresh will handle whether or not the
# screen needs to be re-tiled.
elif e.is_state_change():
try:
if e.get_window_id() in State.get_windows():
State.get_windows()[e.get_window_id()].refresh()
except:
DEBUG.write("Could not properly handle window state event (iconified?)")
DEBUG.write(traceback.format_exc())
# Detects if the "_NET_WORKAREA" property changed. Meaning
# that the available workspace is changed.
#
# Note: Sometimes we get a property changed event when it
# hasn't really changed. So all we want to do here is update
# the workarea properties.
elif e.is_workarea_change():
time.sleep(Config.misc('timeout'))
try:
Desktop.refresh_desktops()
except:
DEBUG.write("Could not properly handle workarea change")
DEBUG.write(traceback.format_exc())
elif e.is_client_message():
callback = Config.callbacks(e.get_client_payload())
if callback:
Tile.dispatch(State.get_desktop()._VIEWPORT._SCREEN.get_tiler(), callback)
else:
DEBUG.write("Got unknown client message.")
DEBUG.write("payload: %s." % e.get_client_payload())
# Detects if the "_NET_DESKTOP_GEOMETRY" property changed.
# Meaning the number of screens changed probably, so
# we need to refresh our image of the current State.
elif e.is_screen_change():
DEBUG.write("Wiping the current state...")
# We should wait a little bit longer here...
time.sleep(3)
try:
State.wipe()
Desktop.load_desktops()
Window.load_new_windows()
State.reload_active()
except:
DEBUG.write("Could not properly handle screen change")
DEBUG.write(traceback.format_exc())
#TODO: for now, this doesn't untile, so you have to do it manually
#except KeyboardInterrupt:
DEBUG.write("Caught keyboard interrupt, untiling")
# for desktop in State.get_desktops().values():
# for viewport in desktop.viewports.values():
# for screen in viewport.screens.values():
# Tile.dispatch(screen.get_tiler(), 'add_decorations')
# time.sleep(Config.misc('timeout'))
# sys.exit(0)
except:
DEBUG.write("Fatal error")
DEBUG.write(traceback.format_exc())
sys.exit(0)