forked from albertz/music-player
/
guiCocoa.py
1170 lines (994 loc) · 38.2 KB
/
guiCocoa.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
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
# 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 sys, os
if sys.platform != "darwin":
print "GUI: your platform is probably not supported yet"
from guiCocoaCommon import *
from utils import *
from weakref import ref
import Traits
try:
app
except NameError: # only declare if not yet declared
app = None
def setupAppleMenu():
# http://www.cocoabuilder.com/archive/cocoa/192181-initializing-the-menubar-without-interface-builder.html
# By Robert Nikander
mainMenu = NSMenu.alloc().initWithTitle_("MainMenu")
mi = mainMenu.addItemWithTitle_action_keyEquivalent_("Apple", None, "")
m = NSMenu.alloc().initWithTitle_("Apple")
# strange hack
app.setAppleMenu_(m)
mainMenu.setSubmenu_forItem_(m, mi)
m.addItemWithTitle_action_keyEquivalent_('About MusicPlayer', 'about:', '')
m.addItem_(NSMenuItem.separatorItem())
m.addItemWithTitle_action_keyEquivalent_('Hide MusicPlayer', 'hide:', 'h')
mii = m.addItemWithTitle_action_keyEquivalent_('Hide Others', 'hideOtherApplications:', 'h')
mii.setKeyEquivalentModifierMask_(NSAlternateKeyMask|NSCommandKeyMask)
m.addItemWithTitle_action_keyEquivalent_('Show All', 'unhideAllApplications:', '')
m.addItem_(NSMenuItem.separatorItem())
m.addItemWithTitle_action_keyEquivalent_('Quit', 'terminate:', 'q')
# new supermenu
mi = mainMenu.addItemWithTitle_action_keyEquivalent_("Edit", None, "")
m = NSMenu.alloc().initWithTitle_("Edit")
mainMenu.setSubmenu_forItem_(m, mi)
m.addItemWithTitle_action_keyEquivalent_('Cut', 'cut:', 'x')
m.addItemWithTitle_action_keyEquivalent_('Copy', 'copy:', 'c')
m.addItemWithTitle_action_keyEquivalent_('Paste', 'paste:', 'v')
m.addItemWithTitle_action_keyEquivalent_('Select all', 'selectText:', 'a')
# new supermenu
mi = mainMenu.addItemWithTitle_action_keyEquivalent_("Window", None, "")
m = NSMenu.alloc().initWithTitle_("Window")
mainMenu.setSubmenu_forItem_(m, mi)
m.addItemWithTitle_action_keyEquivalent_('Main window', 'openMainWindow:', '1')
m.addItemWithTitle_action_keyEquivalent_('Search window', 'openSearchWindow:', '2')
m.addItemWithTitle_action_keyEquivalent_('Song edit window', 'openSongEditWindow:', 'i')
m.addItem_(NSMenuItem.separatorItem())
m.addItemWithTitle_action_keyEquivalent_('Minimize window', 'miniaturize:', 'm')
m.addItemWithTitle_action_keyEquivalent_('Close window', 'performClose:', 'w')
# new supermenu
mi = mainMenu.addItemWithTitle_action_keyEquivalent_("Control", None, "")
m = NSMenu.alloc().initWithTitle_("Control")
mainMenu.setSubmenu_forItem_(m, mi)
m.addItemWithTitle_action_keyEquivalent_('no song yet', '', '')
m.addItemWithTitle_action_keyEquivalent_('Play', 'playPause:', '')
m.addItemWithTitle_action_keyEquivalent_('Next song', 'nextSong:', '')
app.delegate().dockMenu = m
app.setDockMenu_(m)
app.setMainMenu_(mainMenu)
def updateControlMenu():
if not app: return
menu = getattr(app.delegate(), "dockMenu", None)
if not menu: return
from State import state
if not state: return
songEntry = menu.itemAtIndex_(0)
playPauseEntry = menu.itemAtIndex_(1)
songEntry.setTitle_(convertToUnicode(state.curSong.userString))
if state.player.playing:
playPauseEntry.setTitle_("Pause")
else:
playPauseEntry.setTitle_("Play")
def setupAfterAppFinishedLaunching(delegate):
setupAppleMenu()
setupMainWindow()
app.updateWindows()
print "setupAfterAppFinishedLaunching ready"
class PyAppDelegate(NSObject):
__metaclass__ = ObjCClassAutorenamer
# Doc for AppDelegate protocol:
# https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSApplicationDelegate_Protocol/Reference/Reference.html
def applicationDidFinishLaunching_(self, notification):
print "AppDelegate didFinishLaunching"
try:
from State import modules
for m in modules: m.start()
setupAfterAppFinishedLaunching(self)
except:
sys.excepthook(*sys.exc_info())
def applicationShouldTerminate_(self, app):
print "AppDelegate quit"
from State import modules
utils.quit = True
# first set/send signals to all 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: pass
# now join all
for m in modules: m.stop()
return NSTerminateNow
def applicationOpenUntitledFile_(self, app):
if not getWindow("mainWindow"):
setupMainWindow()
else:
app.activateIgnoringOtherApps_(True)
return True
def userNotificationCenter_shouldPresentNotification_(self, notifCenter, notif):
return True
def openMainWindow_(self, app):
setupMainWindow()
def openSearchWindow_(self, app):
setupSearchWindow()
def openSongEditWindow_(self, app):
setupSongEditWindow()
def about_(self, app):
import webbrowser
webbrowser.open("http://albertz.github.com/music-player/")
def playPause_(self, app):
from State import state
state.playPause()
def nextSong_(self, app):
from State import state
state.nextSong()
def getWindow(name):
global windows
if windows.get(name, None):
return windows[name].nativeGuiObject.window()
return None
def quit():
app.terminate_(None)
def setup():
# Note: not needed when bundled...
mydir = os.path.dirname(__file__)
icon = NSImage.alloc().initWithContentsOfFile_(mydir + "/icon.icns")
if not icon:
print "icon.icns not found"
else:
app.setApplicationIconImage_(icon)
appDelegate = PyAppDelegate.alloc().init()
app.setDelegate_(appDelegate)
appDelegate.retain()
app.finishLaunching()
def buildControlAction(control):
button = NSButton.alloc().initWithFrame_(((0,0), (50.0, 25.0)))
button.setBezelStyle_(NSRoundedBezelStyle)
actionTarget = ButtonActionHandler.alloc().initWithArgs(control.attr, control.parent.subjectObject)
control.buttonActionHandler = actionTarget # keep ref here. button.target() is only a weakref
button.setTarget_(actionTarget)
button.setAction_("click")
def do_update(): button.setTitle_(control.attr.name.decode("utf-8"))
do_update()
button.sizeToFit() # to get height
#button.setFrameSize_((50, button.frame().size.height))
def update(ev=None, args=None, kwargs=None):
do_in_mainthread(do_update, wait=False)
control.nativeGuiObject = button
control.updateContent = update
return control
def backgroundColor(control):
if any([(c.attr and c.attr.highlight) for c in control.allParents()]):
return NSColor.blueColor()
return None
def foregroundColor(control):
if any([(c.attr and c.attr.lowlight) for c in control.allParents()]):
return NSColor.disabledControlTextColor()
return NSColor.blackColor()
def buildControlOneLineText(control):
label = NSExtendedTextField.alloc().initWithFrame_(((0, 0), (30.0, 22.0)))
label.setBordered_(False)
if control.attr.withBorder:
label.setBezeled_(True)
label.setBezelStyle_(NSTextFieldRoundedBezel)
label.setDrawsBackground_(False)
label.setEditable_(False)
label.cell().setUsesSingleLineMode_(True)
label.cell().setLineBreakMode_(NSLineBreakByTruncatingTail)
control.nativeGuiObject = label
control.getTextObj = lambda: control.subjectObject
def getTextColor():
if any([(c.attr and c.attr.lowlight) for c in control.allParents()]):
return NSColor.disabledControlTextColor()
return NSColor.blackColor()
control.getTextColor = getTextColor
def update(ev=None, args=None, kwargs=None):
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
s = "???"
try:
labelContent = control.getTextObj()
s = convertToUnicode(labelContent)
except Exception:
sys.excepthook(*sys.exc_info())
def do_update():
label.setStringValue_(s)
if backgroundColor(control):
label.setDrawsBackground_(True)
label.setBackgroundColor_(backgroundColor(control))
label.setTextColor_(foregroundColor(control))
if control.attr.autosizeWidth:
label.sizeToFit()
control.layoutLine()
if label.onMouseEntered or label.onMouseExited:
if getattr(label, "trackingRect", None):
label.removeTrackingRect_(label.trackingRect)
label.trackingRect = label.addTrackingRect_owner_userData_assumeInside_(label.bounds(), label, None, False)
do_in_mainthread(do_update, wait=False)
control.updateContent = update
return control
def buildControlClickableLabel(control):
buildControlOneLineText(control)
control.getTextObj = lambda: control.subjectObject(handleClick=False)
label = control.nativeGuiObject
def onMouseEntered(ev):
if label.backgroundColor() == NSColor.blueColor():
label.setTextColor_(NSColor.grayColor())
else:
label.setTextColor_(NSColor.blueColor())
label.onMouseEntered = onMouseEntered
label.onMouseExited = lambda ev: label.setTextColor_(foregroundColor(control))
def onMouseDown(ev):
try:
control.subjectObject(handleClick=True)
except Exception:
sys.excepthook(*sys.exc_info())
control.parent.updateContent(None,None,None)
label.onMouseDown = onMouseDown
return control
def buildControlEditableText(control):
label = NSExtendedTextField.alloc().initWithFrame_(((0, 0), (30.0, 22.0)))
if control.attr.searchLook:
label.setCell_(NSSearchFieldCell.alloc().init())
label.setBordered_(False)
label.setBezeled_(True)
label.setBezelStyle_(NSTextFieldRoundedBezel)
label.setDrawsBackground_(True)
label.setEditable_(True)
label.cell().setUsesSingleLineMode_(True)
#label.cell().setLineBreakMode_(NSLineBreakByTruncatingTail)
control.nativeGuiObject = label
control.getTextObj = lambda: control.subjectObject()
def update(ev=None, args=None, kwargs=None):
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
s = "???"
try:
labelContent = control.getTextObj()
s = convertToUnicode(labelContent)
except Exception:
sys.excepthook(*sys.exc_info())
def do_update():
label.setStringValue_(s)
do_in_mainthread(do_update, wait=False)
control.updateContent = update
def onTextChange():
try:
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
newText = unicode(label.stringValue())
control.subjectObject(updateText = newText)
except Exception:
sys.excepthook(*sys.exc_info())
label.onTextChange = onTextChange
return control
def buildControlList(control):
list = control.subjectObject
scrollview = NSScrollView.alloc().initWithFrame_(((0.0, 0.0), (80.0, 80.0)))
scrollview.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
scrollview.contentView().setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
scrollview.setDocumentView_(NSFlippedView.alloc().initWithFrame_(((0,0),scrollview.contentSize())))
scrollview.documentView().setAutoresizingMask_(NSViewWidthSizable)
scrollview.setHasVerticalScroller_(True)
scrollview.setDrawsBackground_(False)
scrollview.setBorderType_(NSBezelBorder)
#scrollview.setBorderType_(NSGrooveBorder)
view = NSFlippedView.alloc().initWithFrame_(scrollview.frame())
view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
view.addSubview_(scrollview)
view.control = ref(control)
control.nativeGuiObject = view
control.guiObjectList = [] # all access on this list is done in the main thread
control.OuterSpace = (0,0)
# Hm, why did i needed this again? This makes everything slow and because of
# the generic GuiControl.layout(), it also makes it wrong.
#control.childIter = lambda: control.guiObjectList
#control.childGuiObjectsInColumn = lambda: control.guiObjectList
class Updater:
def __init__(self):
from threading import Lock
self.lock = Lock()
self.outstandingUpdate = False
def doUpdate(self):
with self.lock:
if not self.outstandingUpdate: return
x,y = 0,0
for subCtr in control.guiObjectList:
w = scrollview.contentSize().width
h = subCtr.size[1]
subCtr.pos = (x,y)
subCtr.size = (w,h)
y += subCtr.size[1]
scrollview.documentView().setFrameSize_((scrollview.contentSize().width, y))
if control.attr.autoScrolldown:
scrollview.verticalScroller().setFloatValue_(1)
scrollview.contentView().scrollToPoint_(
(0, scrollview.documentView().frame().size.height -
scrollview.contentSize().height))
with self.lock:
self.outstandingUpdate = False
def update(self):
with self.lock:
if self.outstandingUpdate: return
self.outstandingUpdate = True
do_in_mainthread(self.doUpdate, wait=False)
updater = Updater()
class AttrWrapper(UserAttrib):
def __init__(self, index, value, parent):
UserAttrib.__init__(self)
self.index = index
self.value = value
def __get__(self, inst):
return self.value
def buildControlForIndex(index, value):
subCtr = CocoaGuiObject()
subCtr.subjectObject = value
subCtr.root = control.root
subCtr.parent = control
subCtr.attr = AttrWrapper(index, value, control)
presetSize = (scrollview.contentSize().width, 80)
if len(control.guiObjectList) > 0:
presetSize = (presetSize[0], control.guiObjectList[0].size[1])
subCtr.presetSize = presetSize
_buildControlObject_pre(subCtr)
subCtr.autoresize = (False,False,True,False)
subCtr.pos = (0,-subCtr.size[1]) # so that there isn't any flickering
subCtr.nativeGuiObject.setDrawsBackground_(True)
def delayedBuild():
if control.root.nativeGuiObject.window() is None: return # window was closed
if getattr(subCtr, "obsolete", False): return # can happen in the meanwhile
w,h = subCtr.setupChilds()
def setSize():
w = scrollview.contentSize().width
subCtr.size = (w, h)
do_in_mainthread(setSize, wait=False)
do_in_mainthread(lambda: _buildControlObject_post(subCtr), wait=False)
do_in_mainthread(lambda: subCtr.updateContent(None,None,None), wait=False)
def addView():
if getattr(subCtr, "obsolete", False): return # can happen in the meanwhile
scrollview.documentView().addSubview_(subCtr.nativeGuiObject)
if h != presetSize[1]:
updater.update()
do_in_mainthread(addView, wait=False)
utils.daemonThreadCall(
delayedBuild, name="GUI list item delayed build",
queue="GUI-list-item-delayed-build-%i" % (index % 5)
)
return subCtr
control.select = None
if control.attr.canHaveFocus:
class SelectionHandling:
# for now, a single index. later maybe a range
index = None
def onInsert(self, index, value):
if index <= self.index: self.index += 1
def onRemove(self, index):
if index < self.index: self.index -= 1
elif index == self.index: self.deselect()
def onClear(self):
self.index = None
@ExceptionCatcherDecorator
def deselect(self):
if self.index is not None:
control.guiObjectList[self.index].nativeGuiObject.setBackgroundColor_(NSColor.textBackgroundColor())
self.index = None
@ExceptionCatcherDecorator
def select(self, index=None):
self.deselect()
if index is None:
if len(control.guiObjectList) == 0: return
index = 0
self.index = index
guiObj = control.guiObjectList[index].nativeGuiObject
guiObj.setBackgroundColor_(NSColor.selectedTextBackgroundColor())
# special handling for gui.ctx().curSelectedSong
if control.guiObjectList[index].subjectObject.__class__.__name__ == "Song":
import gui
gui.ctx().curSelectedSong = control.guiObjectList[index].subjectObject
def doScrollUpdate():
if not guiObj.window(): return # window closed or removed from window in the meantime
objFrame = guiObj.frame()
visibleFrame = scrollview.contentView().documentVisibleRect()
if objFrame.origin.y < visibleFrame.origin.y:
scrollview.contentView().scrollToPoint_((0, objFrame.origin.y))
elif objFrame.origin.y + objFrame.size.height > visibleFrame.origin.y + visibleFrame.size.height:
scrollview.contentView().scrollToPoint_((0, objFrame.origin.y + objFrame.size.height - scrollview.contentSize().height))
scrollview.reflectScrolledClipView_(scrollview.contentView())
do_in_mainthread(doScrollUpdate, wait=False)
def onFocus(self):
if self.index is None:
self.select()
view.setDrawsFocusRing_(True)
def onLostFocus(self):
view.setDrawsFocusRing_(False)
@ExceptionCatcherDecorator
def onKeyDown(self, ev):
# see HIToolbox/Events.h for keycodes
if ev.keyCode() == 125: # down
if self.index is None:
self.select()
elif self.index < len(control.guiObjectList) - 1:
self.select(self.index + 1)
return True
elif ev.keyCode() == 126: # up
if self.index is None:
self.select()
elif self.index > 0:
self.select(self.index - 1)
return True
elif ev.keyCode() == 0x33: # delete
if self.index is not None:
index = self.index
if self.index > 0:
self.select(self.index - 1)
list.remove(index)
return True
elif ev.keyCode() == 0x75: # forward delete
if self.index is not None:
index = self.index
if self.index < len(control.guiObjectList) - 1:
self.select(self.index + 1)
list.remove(index)
return True
@ExceptionCatcherDecorator
def onMouseDown(self, ev):
view.window().makeFirstResponder_(view)
mouseLoc = scrollview.documentView().convertPoint_toView_(ev.locationInWindow(), None)
for index,obj in enumerate(control.guiObjectList):
if NSPointInRect(mouseLoc, obj.nativeGuiObject.frame()):
self.select(index)
return True
@ExceptionCatcherDecorator
def onInternalDrag(self, sourceControl, index, filenames):
if sourceControl.parent is control: # internal drag to myself
oldIndex = self.index
# check if the index is still correct
if control.guiObjectList[oldIndex] is sourceControl:
self.select(index)
list.remove(oldIndex)
control.select = SelectionHandling()
view.onBecomeFirstResponder = control.select.onFocus
view.onResignFirstResponder = control.select.onLostFocus
view.onKeyDown = control.select.onKeyDown
view.onMouseDown = control.select.onMouseDown
control.dragHandler = None
if control.attr.dragHandler:
view.registerForDraggedTypes_([NSFilenamesPboardType])
class DragHandler:
index = None
def __init__(self):
view = NSFlippedView.alloc().initWithFrame_(((0,0),(scrollview.contentSize().width,2)))
view.setAutoresizingMask_(NSViewWidthSizable)
view.setBackgroundColor_(NSColor.blackColor())
self.guiCursor = view
scrollview.documentView().addSubview_(view)
@ExceptionCatcherDecorator
def onDraggingUpdated(self, sender):
self.guiCursor.setDrawsBackground_(True)
scrollview.documentView().addSubview_positioned_relativeTo_(self.guiCursor, NSWindowAbove, None)
dragLoc = scrollview.documentView().convertPoint_toView_(sender.draggingLocation(), None)
self.index = 0
y = 0
for index,obj in enumerate(control.guiObjectList):
frame = obj.nativeGuiObject.frame()
if dragLoc.y > frame.origin.y + frame.size.height / 2:
self.index = index + 1
y = frame.origin.y + frame.size.height
else:
break
self.guiCursor.setFrameOrigin_((0,y - 1))
visibleFrame = scrollview.contentView().documentVisibleRect()
mouseLoc = NSPoint(dragLoc.x - visibleFrame.origin.x, dragLoc.y - visibleFrame.origin.y)
ScrollLimit = 30
Limit = 15
y = None
if mouseLoc.y < Limit:
scrollBy = Limit - mouseLoc.y
y = visibleFrame.origin.y - scrollBy
y = max(y, -ScrollLimit)
elif mouseLoc.y > visibleFrame.size.height - Limit:
scrollBy = mouseLoc.y - visibleFrame.size.height + Limit
y = visibleFrame.origin.y + scrollBy
y = min(y, scrollview.documentView().frame().size.height - visibleFrame.size.height + ScrollLimit)
if y is not None:
scrollview.contentView().scrollToPoint_((0, y))
scrollview.reflectScrolledClipView_(scrollview.contentView())
def onDraggingExited(self, sender):
self.guiCursor.setDrawsBackground_(False)
self.index = None
@ExceptionCatcherDecorator
def onPerformDragOperation(self, sender):
self.guiCursor.setDrawsBackground_(False)
import __builtin__
try:
filenames = __builtin__.list(sender.draggingPasteboard().propertyListForType_(NSFilenamesPboardType))
filenames = map(convertToUnicode, filenames)
index = self.index
internalDragCallback = getattr(sender.draggingSource(), "onInternalDrag", None)
def doDragHandler():
control.attr.dragHandler(
control.parent.subjectObject,
control.subjectObject,
index,
filenames)
if internalDragCallback:
do_in_mainthread(lambda:
internalDragCallback(
control,
index,
filenames),
wait=False)
utils.daemonThreadCall(doDragHandler, name="DragHandler")
return True
except:
sys.excepthook(*sys.exc_info())
return False
@ExceptionCatcherDecorator
def onInternalDrag(self, *args):
# Note: This doesn't work if we don't have attr.canHaveFocus. Should be fixed later...
control.select.onInternalDrag(*args)
control.dragHandler = DragHandler()
view.onDraggingUpdated = control.dragHandler.onDraggingUpdated
view.onDraggingExited = control.dragHandler.onDraggingExited
view.onPerformDragOperation = control.dragHandler.onPerformDragOperation
def doInitialFill():
with list.lock:
import __builtin__
listCopy = __builtin__.list(list)
control.guiObjectList = []
Step = 5
def doInitialAddSome(iStart):
for i in range(iStart, min(len(listCopy), iStart+Step)):
control.guiObjectList += [buildControlForIndex(i, listCopy[i])]
updater.update()
for i in xrange(0, len(listCopy), Step):
do_in_mainthread(lambda: doInitialAddSome(i), wait=True)
def list_onInsert(index, value):
control.guiObjectList.insert(index, buildControlForIndex(index, value))
updater.update()
def list_onRemove(index):
control.guiObjectList[index].obsolete = True
control.guiObjectList[index].nativeGuiObject.removeFromSuperview()
del control.guiObjectList[index]
updater.update()
def list_onClear():
for subCtr in control.guiObjectList:
subCtr.nativeGuiObject.removeFromSuperview()
subCtr.obsolete = True
del control.guiObjectList[:]
updater.update()
for ev in ["onInsert","onRemove","onClear"]:
f = locals()["list_" + ev]
def wrap(f=f, ev=ev):
def handler(*args):
if control.select: getattr(control.select, ev)(*args)
f(*args)
return lambda *args: do_in_mainthread(lambda: handler(*args), wait=False)
setattr(list, ev, wrap())
utils.daemonThreadCall(doInitialFill, name="List initial fill")
return control
def buildControlTable(control):
scrollview = NSScrollView.alloc().initWithFrame_(((0.0, 0.0), (80.0, 80.0)))
scrollview.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
scrollview.contentView().setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
scrollview.setHasVerticalScroller_(True)
scrollview.setDrawsBackground_(False)
scrollview.setBorderType_(NSBezelBorder)
view = NSFlippedView.alloc().initWithFrame_(scrollview.frame())
view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
view.addSubview_(scrollview)
view.control = ref(control)
control.nativeGuiObject = view
table = NSTableView.alloc().initWithFrame_(((0,0),(80,80)))
scrollview.setDocumentView_(table)
scrollview.documentView().setAutoresizingMask_(NSViewWidthSizable)
#array = NSArrayController.alloc().init()
dataSource = TableViewDataSource.alloc().init()
dataSource.data = []
dataSource.formaters = control.attr.type.formaters
control.tableDataSource = dataSource # save ref here because table.dataSource() is only a weakref
table.setDataSource_(dataSource)
if control.attr.selectionChangeHandler:
delegate = TableViewDelegate.alloc().init()
delegate.onSelectionChange = lambda sel: control.attr.selectionChangeHandler(control.parent.subjectObject, sel)
control.tableDelegate = delegate
table.setDelegate_(delegate)
table.setColumnAutoresizingStyle_(NSTableViewUniformColumnAutoresizingStyle)
for key in control.attr.type.keys:
column = NSTableColumn.alloc().initWithIdentifier_(key)
column.headerCell().setStringValue_(convertToUnicode(key.capitalize())) # title
column.setEditable_(False)
column.setMinWidth_(30)
column.setSortDescriptorPrototype_(NSSortDescriptor.sortDescriptorWithKey_ascending_(key, True))
table.addTableColumn_(column)
table.setAllowsMultipleSelection_(True)
table.setAutosaveName_(control.name)
table.setAutosaveTableColumns_(True)
def update(ev=None, args=None, kwargs=None):
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
value = control.subjectObject
def setData():
with dataSource.lock:
# Do this in main thread to workaround the problem that
# the tableView knows the wrong number of rows. This could
# happen otherwise because it checks the number of rows in
# its redrawing code and that is not covered by this lock.
# See also the related comment in TableViewDataSource.
dataSource.data = value
dataSource.resort(table) # initial sort
table.reloadData()
do_in_mainthread(setData, wait=False)
control.updateContent = update
update() # initial fill
return control
def buildControlReal(control):
w,h = control.attr.width, control.attr.height
if not w: w = 70
if not h: h = 20
slider = NSExtendedSlider.alloc().initWithFrame_(((0.0, 0.0), (w, h)))
slider.setMinValue_(control.attr.type.min)
slider.setMaxValue_(control.attr.type.max)
slider.setNumberOfTickMarks_(3)
control.nativeGuiObject = slider
def update(ev=None, args=None, kwargs=None):
control.subjectObject = control.attr.__get__(control.parent.subjectObject)
value = control.subjectObject
do_in_mainthread(lambda: slider.setDoubleValue_(value), wait=False)
control.updateContent = update
def onValueChange(newValue):
control.attr.__set__(control.parent.subjectObject, newValue)
slider.onValueChange = onValueChange
return control
def buildControlObject(control):
_buildControlObject_pre(control)
w,h = control.setupChilds()
control.size = (w,h)
_buildControlObject_post(control)
return control
def _buildControlObject_pre(control):
presetSize = getattr(control, "presetSize", (80.0,80.0))
subview = NSFlippedView.alloc().initWithFrame_(((10.0, 10.0), presetSize))
subview.control = ref(control)
control.nativeGuiObject = subview
control.OuterSpace = (0,0)
def _buildControlObject_post(control):
subview = control.nativeGuiObject
if control.attr.canHaveFocus:
subview.setDrawsBackground_(True)
subview.onResignFirstResponder = lambda: subview.setBackgroundColor_(NSColor.textBackgroundColor())
subview.onBecomeFirstResponder = lambda: subview.setBackgroundColor_(NSColor.selectedTextBackgroundColor())
if backgroundColor(control):
subview.setDrawsBackground_(True)
subview.setBackgroundColor_(backgroundColor(control))
@ExceptionCatcherDecorator
def onInternalDrag(target, listindex, filenames):
attrChain(target, "dragHandler", "onInternalDrag")(control, listindex, filenames)
@ExceptionCatcherDecorator
def onMouseDragged(ev):
guiObj = control
subjectObj = guiObj.subjectObject
filename = getattr(subjectObj, "url", None)
if not filename: return False
filename = convertToUnicode(filename)
pboard = NSPasteboard.pasteboardWithName_(NSDragPboard)
pboard.declareTypes_owner_([NSFilenamesPboardType], None)
pboard.setPropertyList_forType_([filename], NSFilenamesPboardType)
dragImage = NSWorkspace.sharedWorkspace().iconForFile_(filename)
dragPosition = subview.convertPoint_toView_(ev.locationInWindow(), None)
dragPosition.x -= 16
dragPosition.y += 32
dragSource = DragSource.alloc().init()
dragSource.onInternalDrag = onInternalDrag
subview.dragImage_at_offset_event_pasteboard_source_slideBack_(
dragImage,
dragPosition,
NSZeroSize,
ev,
pboard,
dragSource,
False
)
return True
subview.onMouseDragged = onMouseDragged
@ExceptionCatcherDecorator
def onMouseDown(ev):
subjectObj = control.subjectObject
# special handling for gui.ctx().curSelectedSong
if subjectObj.__class__.__name__ == "Song":
import gui
gui.ctx().curSelectedSong = subjectObj
subview.onMouseDown = onMouseDown
def SongDisplayView_MouseClickCallback(x):
from State import state
song = state.player.curSong
if not song: return
if not song.duration: return
if song.duration < 0: return
state.player.seekAbs(x * song.duration)
def buildControlSongDisplay(control):
userAttr = control.attr
inst = control.parent.subjectObject
try:
class SongDisplayView(NSBox):
def mouseDown_(self, event):
location = self.convertPoint_fromView_(event.locationInWindow(), None)
if NSPointInRect(location, self.bounds()):
x = float(location.x) / self.bounds().size.width
if x < 0 or x > 1: return
SongDisplayView_MouseClickCallback(x)
except Exception:
SongDisplayView = objc.lookUpClass("SongDisplayView") # already defined earlier
subview = SongDisplayView.alloc().initWithFrame_(((10.0, 10.0), (80.0, 80.0)))
subview.setTitlePosition_(NSNoTitle)
#subview.setContentViewMargins_((0,0))
imgview = NSImageView.alloc().initWithFrame_(subview.contentView().bounds())
imgview.setImageScaling_(NSScaleToFit)
imgview2 = NSImageView.alloc().initWithFrame_(((0,0), (10, subview.contentView().bounds().size.height)))
imgview2.setImageScaling_(NSScaleToFit)
subview.contentView().addSubview_(imgview)
subview.contentView().addSubview_(imgview2)
imgview.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)
imgview2.setAutoresizingMask_(NSViewHeightSizable|NSViewMinXMargin|NSViewMaxXMargin)
from threading import Lock
from State import state
class SongDisplay:
def __init__(self):
self.lock = Lock()
self.curSong = None
def initSongCursorImg(self):
img2 = NSImage.alloc().initWithSize_((5,1))
img2.lockFocus()
for i in range(5):
a = 100 - abs(i - 2) * 50
NSColor.colorWithDeviceRed_green_blue_alpha_(0.0,0.0,0.0,a).setFill()
NSBezierPath.fillRect_(((i,0),(1,1)))
img2.unlockFocus()
do_in_mainthread(lambda: imgview2.setImage_(img2))
def setSongBitmap(self, bmpData, wait=True):
with self.lock:
if state.player.curSong is not self.curSong: return None
data = NSData.alloc().initWithBytes_length_(bmpData, len(bmpData))
img = NSImage.alloc().initWithData_(data)
do_in_mainthread(lambda: imgview.setImage_(img), wait=wait)
def getBmpData(self):
better_exchook.install()
pool = NSAutoreleasePool.alloc().init() # for setSongBitmap
bmpData = None
with self.lock:
if state.player.curSong is not self.curSong: return None
if getattr(self.curSong, "bmpThumbnail", None):
bmpData = self.curSong.bmpThumbnail
else:
# create song copy for calcBitmapThumbnail
from Song import Song
song = Song(url=self.curSong.url)
if bmpData:
self.setSongBitmap(bmpData)
del pool
return
do_in_mainthread(lambda: imgview.setImage_(None), wait=False)
def doBmpCalc(queue):
try:
def calcBmpCallback(song, completion, duration, bmpData):
if subview.window() is None: return False # window was closed
with self.lock:
if song != self.curSong: return False
queue.put((duration, bmpData))
return True
song._useDb = False
song.openFile()
import ffmpeg
bmpThumbRet = ffmpeg.calcBitmapThumbnail(song, 600, 81, procCallback = calcBmpCallback)
if bmpThumbRet:
queue.put(bmpThumbRet)
except:
print "doBmpCalc raised exception"
sys.excepthook(*sys.exc_info())
queue.put(None)
queue = AsyncTask(func=doBmpCalc, name="doBmpCalc for Cocoa")
while True:
bmpThumbRet = queue.get()
if bmpThumbRet is None: break
duration, bmpData = bmpThumbRet
with self.lock:
self.curSong.duration = duration
self.curSong.bmpThumbnail = bmpData
self.setSongBitmap(bmpData, wait=False)
del pool
def playCursorUpdater(self):
better_exchook.install()
pool = NSAutoreleasePool.alloc().init()
def updateCursor():
with self.lock:
if self.curSong is None: return
if state.player.curSong is not self.curSong: return
w = imgview2.frame().size.width
h = imgview2.frame().size.height
x = subview.contentView().bounds().size.width * state.player.curSongPos / self.curSong.duration - w / 2
y = imgview2.frame().origin.y
imgview2.setFrame_(((x,y),(w,h)))
import time
i = 0
while True:
i += 1
time.sleep(0.1)
if subview.window() is None: return # window was closed
with self.lock:
if self.curSong is None: continue
if self.curSong is not state.player.curSong: continue
do_in_mainthread(updateCursor, wait=False)
# another hack: update time
control.parent.childs["curSongPos"].updateContent(None,None,None)
del pool
def update(self, ev=None, args=None, kwargs=None):
#if ev is PlayerEventCallbacks.onSongChange:
with self.lock:
if self.curSong is state.player.curSong: return # song not changed
self.curSong = state.player.curSong
if not self.curSong:
do_in_mainthread(lambda: imgview.setImage_(None), wait=False)
return
utils.daemonThreadCall(self.getBmpData, name="GUI song bitmap loader")
songDisplay = SongDisplay()
songDisplay.initSongCursorImg()
utils.daemonThreadCall(songDisplay.playCursorUpdater, name="GUI play cursor updater")
control.nativeGuiObject = subview
control.updateContent = songDisplay.update
return control
@DoInMainthreadDecorator
def buildControl(userAttr, parent):
control = CocoaGuiObject()
control.root = parent.root
control.parent = parent
control.attr = userAttr
control.subjectObject = userAttr.__get__(parent.subjectObject)
typeName = userAttr.getTypeClass().__name__
assert userAttr.getTypeClass() is getattr(Traits, typeName)
buildFuncName = "buildControl" + typeName
buildFunc = globals().get(buildFuncName, None)
if buildFunc:
return buildFunc(control)
else:
raise NotImplementedError, "%r not handled yet" % userAttr.type
try:
windows
except NameError:
windows = {}