forked from albertz/music-player
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gui.py
405 lines (339 loc) · 11.3 KB
/
gui.py
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
# MusicPlayer, https://github.com/albertz/music-player
# Copyright (c) 2012, Albert Zeyer, www.az2000.de
# All rights reserved.
# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
import appinfo
import sys
from utils import safe_property, do_in_mainthread
# define fallback
def main(): raise NotImplementedError
def guiMain(): pass
def locateFile(filename):
print "locateFile", utils.convertToUnicode(filename).encode("utf-8")
def about():
import webbrowser
webbrowser.open("http://albertz.github.io/music-player/")
if not appinfo.args.nogui:
from _gui import *
try:
# Right now, we can only enable qtgui via cmdline and the only
# two implementations are Cocoa and Qt. And we always try to enable
# one of these implementations. That is why the selection looks like
# this.
# Later, it might sense to disable the GUI at all and there might be
# other GUI implementations. Also, maybe the design might change and
# we could enable multiple GUIs as different separate modules.
# E.g., the webinterface will in any case be a separate module.
if sys.platform == "darwin" and not appinfo.args.qtgui:
from guiCocoa import *
else:
# Use Qt as the generic fallback.
from guiQt import *
except Exception:
print "error in loading GUI implementation"
sys.excepthook(*sys.exc_info())
class _GuiObject:
def __repr__(self): return "<%s %r %r>" % (self.__class__.__name__, self.subjectObject, self.attr)
@safe_property
@property
def name(self):
name = ""
obj = self
while True:
if obj.parent:
name = "." + obj.attr.name + name
obj = obj.parent
else:
name = obj.subjectObject.__class__.__name__ + name
break
return name
def allParents(self):
obj = self
while obj:
yield obj
obj = obj.parent
def childIter(self): return self.childs.itervalues()
def updateSubjectObject(self):
if self.parent:
self.subjectObject = self.attr.__get__(self.parent.subjectObject)
if getattr(self.subjectObject, "_updateEvent", None):
self._updateHandler = lambda: do_in_mainthread(self.updateContent, wait=False)
getattr(self.subjectObject, "_updateEvent").register(self._updateHandler)
def updateChild(self, control):
if control.attr and control.attr.updateHandler:
try:
control.attr.updateHandler(self.subjectObject, control.attr)
except Exception:
sys.excepthook(*sys.exc_info())
control.updateContent()
def updateContent(self):
self.updateSubjectObject()
for control in self.childIter():
self.updateChild(control)
def guiObjectsInLine(self):
obj = self
while True:
if not getattr(obj, "leftGuiObject", None): break
obj = obj.leftGuiObject
while obj:
yield obj
obj = getattr(obj, "rightGuiObject", None)
def layoutLine(self):
line = list(self.guiObjectsInLine())
minY = min([control.pos[1] for control in line])
maxH = max([control.size[1] for control in line])
x = self.parent.OuterSpace[0]
for control in line:
spaceX = self.parent.DefaultSpace[0]
if control.attr.spaceX is not None: spaceX = control.attr.spaceX
w,h = control.size
y = minY + (maxH - h) / 2.
control.pos = (x,y)
x += w + spaceX
varWidthControl = None
for control in line:
if control.attr.variableWidth:
varWidthControl = control
break
if not varWidthControl:
varWidthControl = line[-1]
if varWidthControl.attr.variableWidth is False:
# It explicitly doesn't want to be of variable size.
return
x = self.parent.innerSize[0] - self.parent.OuterSpace[0]
for control in reversed(line):
w,h = control.size
y = control.pos[1]
if control is varWidthControl:
w = x - control.pos[0]
x = control.pos[0]
control.pos = (x,y)
control.size = (w,h)
control.autoresize = (False,False,True,False)
control.layout()
break
else:
x -= w
control.pos = (x,y)
control.size = (w,h)
control.autoresize = (True,False,False,False)
spaceX = self.parent.DefaultSpace[0]
if control.attr.spaceX is not None: spaceX = control.attr.spaceX
x -= spaceX
def childGuiObjectsInColumn(self):
obj = self.firstChildGuiObject
while obj:
yield obj
while getattr(obj, "rightGuiObject", None):
obj = obj.rightGuiObject
obj = getattr(obj, "bottomGuiObject", None)
def layout(self):
lastVertControls = list(self.childGuiObjectsInColumn())
if not lastVertControls: return
for control in lastVertControls:
control.layoutLine()
if not self.autoresize[3]:
w,h = self.size
lastCtr = lastVertControls[-1]
h = lastCtr.pos[1] + lastCtr.size[1]
self.size = (w,h)
return
varHeightControl = None
for control in lastVertControls:
if control.attr.variableHeight:
varHeightControl = control
break
if not varHeightControl:
varHeightControl = lastVertControls[-1]
if varHeightControl.attr.variableHeight is False:
# It explicitly doesn't want to be of variable size.
return
y = self.innerSize[1] - self.OuterSpace[1]
for control in reversed(lastVertControls):
w,h = control.size
x = control.pos[0]
if control is varHeightControl:
h = y - control.pos[1]
y = control.pos[1]
control.pos = (x,y)
control.size = (w,h)
control.autoresize = control.autoresize[0:3] + (True,)
control.layout()
break
else:
y -= h
for lineControl in control.guiObjectsInLine():
lineControl.pos = (lineControl.pos[0],y)
lineControl.autoresize = lineControl.autoresize[0:1] + (True,) + lineControl.autoresize[2:4]
y -= self.DefaultSpace[1]
firstChildGuiObject = None
childs = {} # (attrName -> guiObject) map. this might change...
def setupChilds(self):
"If this is a container (a generic object), this does the layouting of the childs"
self.updateSubjectObject()
self.firstChildGuiObject = None
self.childs = {}
x, y = self.OuterSpace
maxX, maxY = 0, 0
lastControl = None
from utils import iterUserAttribs
for attr in iterUserAttribs(self.subjectObject):
try:
control = buildControl(attr, self)
except NotImplementedError as e:
print e
# Skip this control and continue. The rest of the GUI might still be usable.
continue
if not self.firstChildGuiObject:
self.firstChildGuiObject = control
if attr.hasUpdateEvent():
def controlUpdateHandler(control=control):
do_in_mainthread(lambda: self.updateChild(control), wait=False)
control._updateHandler = controlUpdateHandler
attr.updateEvent(self.subjectObject).register(control._updateHandler)
self.addChild(control)
self.childs[attr.name] = control
spaceX, spaceY = self.DefaultSpace
if attr.spaceX is not None: spaceX = attr.spaceX
if attr.spaceY is not None: spaceY = attr.spaceY
if attr.alignRight and lastControl: # align next right
x = lastControl.pos[0] + lastControl.size[0] + spaceX
# y from before
control.leftGuiObject = lastControl
if lastControl:
lastControl.rightGuiObject = control
elif lastControl: # align next below
x = self.OuterSpace[0]
y = maxY + spaceY
control.topGuiObject = lastControl
if lastControl:
lastControl.bottomGuiObject = control
else: # very first
pass
control.pos = (x,y)
lastControl = control
maxX = max(maxX, control.pos[0] + control.size[0])
maxY = max(maxY, control.pos[1] + control.size[1])
control.updateContent()
# Handy for now. This return might change.
return (maxX + self.OuterSpace[0], maxY + self.OuterSpace[1])
def handleApplicationQuit():
"""
Depending on the environment, this might be called multiple times.
It should do some cleanup and save the DBs and such.
Once this get called, the app is not expected to be in a
functional state anymore.
"""
import utils
if utils.quit > 1: return # Already called before.
utils.quit = 1
# first set/send signals to all modules
from State import modules
for m in modules: m.stop(join=False)
try:
# in case there are any subprocesses, interrupt them
# maybe some modules are hanging and waiting for such
import sys, os, signal
os.kill(0, signal.SIGINT)
except KeyboardInterrupt: pass # well, we expect that...
except Exception: pass
# now join all
for m in modules: m.stop()
# Do some cleanup before we let Python do the final cleanup.
# E.g., it might happen that Python will not GC the player instance
# soon enough in its `Py_Finalize()`. In that situation, bad things
# will happen, because most probably, the player instances worker
# thread is still running in the background. This most probably
# leads to a crash.
RootObjs.clear()
try: ctx().rootObjs.clear()
except Exception: pass # might already be out of scope
import State
State.state = None
import songdb
songdb.flush()
import gc
for _ in range(3): gc.collect()
utils.quit = 2
print "Bye!"
# On Mac/Win/Linux, these are the windows.
RootObjs = {}
class RootObj(object):
obj = None
guiObj = None
name = "Object"
title = None
priority = -10
keyShortcut = None
def __init__(self, **kwargs):
for key, value in kwargs.items():
if not hasattr(self, key): raise AttributeError, "%s invalid" % key
if key.startswith("_"): raise AttributeError, "%s is read-only" % key
setattr(self, key, value)
if self.title is None: self.title = self.name
if self.__class__ is RootObj and self.obj is None:
raise AttributeError, "obj must be set"
def registerRootObj(**kwargs):
desc = RootObj(**kwargs)
RootObjs[desc.name] = desc
class CtxRootObj(RootObj):
clazz = None
@property
def _rootObj(self):
c = ctx()
if self.name in c.rootObjs:
return c.rootObjs[self.name]
obj = self.clazz(ctx=c)
attribs = dict([(key,getattr(self,key)) for key in dir(self) if not key.startswith("_")])
del attribs["obj"]
rootObj = RootObj(obj=obj, **attribs)
c.rootObjs[self.name] = rootObj
return rootObj
@property
def obj(self): return self._rootObj.obj
@property
def guiObj(self): return self._rootObj.guiObj
@guiObj.setter
def guiObj(self, value): self._rootObj.guiObj = value
def registerCtxRootObj(**kwargs):
desc = CtxRootObj(**kwargs)
RootObjs[desc.name] = desc
def iterRootObjs():
objs = list(RootObjs.values())
objs.sort(key=lambda o: o.priority, reverse=True)
return objs
# This function is later supposed to give the right gui context
# depending where we call it from. This can maybe be managed/set via
# contextlib or so.
# The context itself is supposed to provide objects like window list,
# current selected song (needed for SongEdit), etc.
# Right now, we just support a single context.
def ctx():
global _ctx
if _ctx: return _ctx
from utils import Event, initBy
class Ctx(object):
# context-based root objects. via registerCtxRootObj()
@initBy
def rootObjs(self): return {}
@property
def curSelectedSong(self):
song = getattr(self, "_curSelectedSong", None)
if song: return song
# otherwise fall back to current song.
# it's better to have always one so if the window is created,
# the layout is correct.
# this is actually a hack: better would be if the re-layouting
# would work correctly in that case. we really should work
# out some generic nice and clean update-handling...
import State
return State.state.curSong
@curSelectedSong.setter
def curSelectedSong(self, obj):
self._curSelectedSong = obj
self.curSelectedSong_updateEvent.push()
@initBy
def curSelectedSong_updateEvent(self): return Event()
_ctx = Ctx()
return _ctx
_ctx = None