-
Notifications
You must be signed in to change notification settings - Fork 7
/
VideoWindowController.py
1596 lines (1303 loc) · 59.9 KB
/
VideoWindowController.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
# Copyright (C) 2014 AG Projects. See LICENSE for details.
#
from AppKit import (NSApp,
NSRectFillUsingOperation,
NSCompositeSourceOver,
NSApplication,
NSGraphicsContext,
NSCalibratedRGBColorSpace,
NSAlphaFirstBitmapFormat,
NSWindow,
NSView,
NSOpenGLView,
NSOnState,
NSOffState,
NSMenu,
NSMenuItem,
NSWindowController,
NSEventTrackingRunLoopMode,
NSFloatingWindowLevel,
NSNormalWindowLevel,
NSTrackingMouseEnteredAndExited,
NSTrackingMouseMoved,
NSTrackingActiveAlways,
NSFilenamesPboardType,
NSDragOperationNone,
NSDragOperationCopy,
NSDeviceIsScreen,
NSZeroPoint,
NSRectFill,
NSRightMouseUp,
NSSound,
NSViewMinXMargin,
NSViewMaxXMargin,
NSViewMinYMargin,
NSViewMaxYMargin,
NSViewHeightSizable,
NSViewMaxXMargin,
NSViewMaxYMargin,
NSViewMinXMargin,
NSViewMinYMargin,
NSViewWidthSizable,
NSWindowDocumentIconButton
)
from Foundation import (NSAttributedString,
NSBundle,
NSURL,
NSBezierPath,
NSUserDefaults,
NSData,
NSObject,
NSColor,
NSDictionary,
NSArray,
NSImage,
NSDate,
NSEvent,
NSRunLoop,
NSRunLoopCommonModes,
NSTimer,
NSNotificationCenter,
NSLocalizedString,
NSTrackingArea,
NSZeroRect,
NSScreen,
NSMakeSize,
NSMakeRect,
NSPopUpButton,
NSTextField,
NSTask,
NSTaskDidTerminateNotification,
NSMakePoint,
NSWidth,
NSHeight,
NSDownloadsDirectory,
NSSearchPathForDirectoriesInDomains,
NSUserDomainMask,
NSWorkspace
)
from Foundation import mbFlipWindow
import datetime
import os
import objc
import time
import unicodedata
from math import floor
from dateutil.tz import tzlocal
from application.notification import NotificationCenter
from resources import ApplicationData
from sipsimple.application import SIPApplication
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.core import VideoCamera, Engine, FrameBufferVideoRenderer
from sipsimple.threading import run_in_thread
from util import allocate_autorelease_pool, format_identity_to_string, call_in_gui_thread
from Quartz import CIImage, CIContext, kCIFormatARGB8, NSOpenGLPFAWindow, NSOpenGLPFAAccelerated, NSOpenGLPFADoubleBuffer, NSOpenGLPixelFormat, kCGEventMouseMoved, kCGEventSourceStateHIDSystemState, CGColorCreateGenericRGB
from MediaStream import STREAM_CONNECTED, STREAM_IDLE, STREAM_FAILED
from VideoLocalWindowController import VideoLocalWindowController
from SIPManager import SIPManager
from ZRTPAuthentication import ZRTPAuthentication
from util import run_in_gui_thread
from application.notification import IObserver, NotificationCenter
from application.python import Null
from zope.interface import implementer
from BlinkLogger import BlinkLogger
bundle = NSBundle.bundleWithPath_(objc.pathForFramework('ApplicationServices.framework'))
objc.loadBundleFunctions(bundle, globals(), [('CGEventSourceSecondsSinceLastEventType', b'diI')])
IDLE_TIME = 5
RecordingImages = []
def loadRecordingImages():
if not RecordingImages:
RecordingImages.append(NSImage.imageNamed_("recording1"))
RecordingImages.append(NSImage.imageNamed_("recording2"))
RecordingImages.append(NSImage.imageNamed_("recording3"))
class VideoWidget(NSView):
_frame = None
renderer = None
aspect_ratio = None
def awakeFromNib(self):
self.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
def acceptsFirstResponder(self):
return True
def acceptsFirstMouse(self):
return True
def canBecomeKeyView(self):
return True
@objc.python_method
def setProducer(self, producer):
#BlinkLogger().log_debug("%s setProducer %s" % (self, producer))
if producer is None:
if self.renderer is not None:
self.renderer.close()
self.renderer = None
return True
else:
if self.renderer is None:
self.renderer = FrameBufferVideoRenderer(self.handle_frame)
if self.renderer is not None and self.renderer.producer != producer:
self.renderer.producer = producer
return True
return False
def close(self):
BlinkLogger().log_debug("Close %s" % self)
self.setProducer(None)
if self.renderer is not None:
self.renderer.close()
self.renderer = None
self.removeFromSuperview()
def dealloc(self):
BlinkLogger().log_debug("Dealloc %s" % self)
objc.super(VideoWidget, self).dealloc()
def mouseDown_(self, event):
if hasattr(self.delegate, "mouseDown_"):
self.delegate.mouseDown_(event)
@property
def delegate(self):
if NSApp.delegate().contactsWindowController.drawer.contentView().window() == self.window():
delegate = NSApp.delegate().contactsWindowController.drawer.parentWindow().delegate()
elif NSApp.delegate().chatWindowController.drawer.contentView().window() == self.window():
delegate = NSApp.delegate().chatWindowController.drawer.parentWindow().delegate()
else:
delegate = self.window().delegate()
return delegate
def rightMouseDown_(self, event):
if hasattr(self.delegate, "rightMouseDown_"):
self.delegate.rightMouseDown_(event)
def keyDown_(self, event):
if hasattr(self.delegate, "keyDown_"):
self.delegate.keyDown_(event)
def mouseUp_(self, event):
if hasattr(self.delegate, "mouseUp_"):
self.delegate.mouseUp_(event)
def mouseDragged_(self, event):
if hasattr(self.delegate, "mouseDraggedView_"):
self.delegate.mouseDraggedView_(event)
@objc.python_method
@run_in_gui_thread
def handle_frame(self, frame):
if self.isHidden():
return
self._frame = frame
aspect_ratio = floor((float(frame.width) / frame.height) * 100)/100
if self.aspect_ratio != aspect_ratio:
self.aspect_ratio = aspect_ratio
self.delegate.init_aspect_ratio(*frame.size)
self.setNeedsDisplay_(True)
def drawRect_(self, rect):
if self.delegate and self.delegate.full_screen_in_progress:
return
frame = self._frame
if frame is None:
return
data = NSData.dataWithBytesNoCopy_length_freeWhenDone_(frame.data, len(frame.data), False)
image = CIImage.imageWithBitmapData_bytesPerRow_size_format_colorSpace_(data,
frame.width * 4,
frame.size,
kCIFormatARGB8,
None)
context = NSGraphicsContext.currentContext().CIContext()
context.drawImage_inRect_fromRect_(image, rect, image.extent())
@objc.python_method
def show(self):
BlinkLogger().log_debug('Show %s' % self)
self.setHidden_(False)
@objc.python_method
def toggle(self):
if not self.isHidden():
self.hide()
else:
self.show()
@objc.python_method
def hide(self):
BlinkLogger().log_debug('Hide %s' % self)
self.setHidden_(True)
class remoteVideoWidget(VideoWidget):
def draggingEntered_(self, sender):
pboard = sender.draggingPasteboard()
if pboard.types().containsObject_(NSFilenamesPboardType):
pboard = sender.draggingPasteboard()
fnames = pboard.propertyListForType_(NSFilenamesPboardType)
for f in fnames:
if not os.path.isfile(f) and not os.path.isdir(f):
return NSDragOperationNone
return NSDragOperationCopy
return NSDragOperationNone
def prepareForDragOperation_(self, sender):
pboard = sender.draggingPasteboard()
if pboard.types().containsObject_(NSFilenamesPboardType):
fnames = pboard.propertyListForType_(NSFilenamesPboardType)
for f in fnames:
if not os.path.isfile(f) and not os.path.isdir(f):
return False
return True
return False
def performDragOperation_(self, sender):
pboard = sender.draggingPasteboard()
if pboard.types().containsObject_(NSFilenamesPboardType):
filenames = pboard.propertyListForType_(NSFilenamesPboardType)
return self.sendFiles(filenames)
return False
@objc.python_method
def sendFiles(self, fnames):
filenames = [unicodedata.normalize('NFC', file) for file in fnames if os.path.isfile(file) or os.path.isdir(file)]
if filenames and hasattr(self.delegate, "sessionController"):
self.delegate.sessionController.sessionControllersManager.send_files_to_contact(self.delegate.sessionController.account, self.delegate.sessionController.target_uri, filenames)
return True
return False
class myVideoWidget(VideoWidget):
initialLocation = None
initialOrigin = None
auto_rotate_menu_enabled = True
start_origin = None
final_origin = None
temp_origin = None
is_dragging = False
allow_drag = True
def rightMouseDown_(self, event):
if self.isHidden():
return
point = self.window().convertScreenToBase_(NSEvent.mouseLocation())
event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
NSRightMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(), self.window().windowNumber(),
self.window().graphicsContext(), 0, 1, 0)
videoDevicesMenu = NSMenu.alloc().init()
lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Select Video Camera", "Menu item"), "", "")
lastItem.setEnabled_(False)
videoDevicesMenu.addItem_(NSMenuItem.separatorItem())
i = 0
for item in NSApp.delegate().video_devices:
if item not in (None, 'system_default'):
i += 1
lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(item, "changeVideoDevice:", "")
lastItem.setRepresentedObject_(item)
if SIPApplication.video_device.real_name == item:
lastItem.setState_(NSOnState)
if i > 1 and self.auto_rotate_menu_enabled:
videoDevicesMenu.addItem_(NSMenuItem.separatorItem())
settings = SIPSimpleSettings()
lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Auto Rotate Cameras", "Menu item"), "toggleAutoRotate:", "")
lastItem.setState_(NSOnState if settings.video.auto_rotate_cameras else NSOffState)
NSMenu.popUpContextMenu_withEvent_forView_(videoDevicesMenu, event, self)
def toggleAutoRotate_(self, sender):
settings = SIPSimpleSettings()
settings.video.auto_rotate_cameras = not settings.video.auto_rotate_cameras
settings.save()
def changeVideoDevice_(self, sender):
settings = SIPSimpleSettings()
BlinkLogger().log_info('Switching to %s video camera' % sender.representedObject())
settings.video.device = sender.representedObject()
settings.save()
def mouseDown_(self, event):
if not self.allow_drag:
return
self.initialLocation = event.locationInWindow()
self.initialOrigin = self.frame().origin
self.final_origin = None
def mouseUp_(self, event):
if not self.allow_drag:
return
self.is_dragging = False
self.goToFinalOrigin()
@objc.python_method
def goToFinalOrigin(self):
if not self.allow_drag:
return
self.setFrameOrigin_(self.final_origin)
self.start_origin = None
self.final_origin = None
def performDrag(self):
if not self.allow_drag:
return
if not self.currentLocation:
return
newOrigin = self.frame().origin
offset_x = self.initialLocation.x - self.initialOrigin.x
offset_y = self.initialLocation.y - self.initialOrigin.y
newOrigin.x = self.currentLocation.x - offset_x
newOrigin.y = self.currentLocation.y - offset_y
if newOrigin.x < 10:
newOrigin.x = 10
if newOrigin.y < 10:
newOrigin.y = 10
if self.window().delegate().full_screen:
parentFrame = NSScreen.mainScreen().visibleFrame()
else:
parentFrame = self.window().frame()
if newOrigin.x > parentFrame.size.width - 10 - self.frame().size.width:
newOrigin.x = parentFrame.size.width - 10 - self.frame().size.width
if newOrigin.y > parentFrame.size.height - 30 - self.frame().size.height:
newOrigin.y = parentFrame.size.height - 30 - self.frame().size.height
if ((newOrigin.y + self.frame().size.height) > (parentFrame.origin.y + parentFrame.size.height)):
newOrigin.y = parentFrame.origin.y + (parentFrame.size.height - self.frame().size.height)
if abs(newOrigin.x - self.window().delegate().myVideoViewTL.frame().origin.x) > abs(newOrigin.x - self.window().delegate().myVideoViewTR.frame().origin.x):
letter2 = "R"
else:
letter2 = "L"
if abs(newOrigin.y - self.window().delegate().myVideoViewTL.frame().origin.y) > abs(newOrigin.y - self.window().delegate().myVideoViewBL.frame().origin.y):
letter1 = "B"
else:
letter1 = "T"
finalFrame = "myVideoView" + letter1 + letter2
self.start_origin = newOrigin
self.final_origin = getattr(self.window().delegate(), finalFrame).frame().origin
NSUserDefaults.standardUserDefaults().setValue_forKey_(letter1 + letter2, "MyVideoCorner")
self.setFrameOrigin_(newOrigin)
@objc.python_method
def snapToCorner(self):
newOrigin = self.frame().origin
if abs(newOrigin.x - self.window().delegate().myVideoViewTL.frame().origin.x) > abs(newOrigin.x - self.window().delegate().myVideoViewTR.frame().origin.x):
letter2 = "R"
else:
letter2 = "L"
if abs(newOrigin.y - self.window().delegate().myVideoViewTL.frame().origin.y) > abs(newOrigin.y - self.window().delegate().myVideoViewBL.frame().origin.y):
letter1 = "B"
else:
letter1 = "T"
finalFrame = "myVideoView" + letter1 + letter2
self.setFrameOrigin_(getattr(self.window().delegate(), finalFrame).frame().origin)
NSUserDefaults.standardUserDefaults().setValue_forKey_(letter1 + letter2, "MyVideoCorner")
def mouseDragged_(self, event):
self.is_dragging = True
self.currentLocation = event.locationInWindow()
self.performDrag()
@implementer(IObserver)
class VideoWindowController(NSWindowController):
valid_aspect_ratios = [None, 1.33, 1.77]
aspect_ratio_descriptions = {1.33: '4/3', 1.77: '16/9'}
initial_aspect_ratio = None
full_screen = False
initialLocation = None
always_on_top = False
localVideoWindow = None
full_screen_in_progress = False
mouse_in_window = True
mouse_timer = None
title = None
disconnectedPanel = None
show_window_after_full_screen_ends = None
tracking_area = None
flipped = False
aspect_ratio = None
titleBarView = None
initialLocation = None
is_key_window = False
updating_aspect_ratio = False
dragMyVideoViewWithinWindow = True
closed = False
window_too_small = False
zrtp_controller = None
local_video_hidden = False
holdButton = objc.IBOutlet()
hangupButton = objc.IBOutlet()
chatButton = objc.IBOutlet()
infoButton = objc.IBOutlet()
muteButton = objc.IBOutlet()
fullScreenButton = objc.IBOutlet()
aspectButton = objc.IBOutlet()
screenshotButton = objc.IBOutlet()
recordButton = objc.IBOutlet()
buttonsView = objc.IBOutlet()
videoView = objc.IBOutlet()
myVideoView = objc.IBOutlet()
myVideoViewTL = objc.IBOutlet()
myVideoViewTR = objc.IBOutlet()
myVideoViewBL = objc.IBOutlet()
myVideoViewBR = objc.IBOutlet()
disconnectLabel = objc.IBOutlet()
last_label = None
screenshot_task = None
screencapture_file = None
recordingImage = 0
recording_timer = 0
idle_timer = None
is_idle = False
show_time = None
mouse_in_window = False
is_key_window = False
visible_buttons = True
recording_timer = None
must_hide_after_exit_full_screen = False
will_close = False
def __new__(cls, *args, **kwargs):
return cls.alloc().init()
def __init__(self, streamController):
self.streamController = streamController
self.sessionController.log_debug('Init %s' % self)
self.title = self.sessionController.titleShort
self.flipWnd = mbFlipWindow.alloc().init()
self.flipWnd.setFlipRight_(True)
self.flipWnd.setDuration_(2.4)
self.notification_center = NotificationCenter()
loadRecordingImages()
@objc.python_method
def initLocalVideoWindow(self):
if self.sessionController.video_consumer == "standalone":
sessionControllers = self.sessionController.sessionControllersManager.sessionControllers
other_video_sessions = any(sess for sess in sessionControllers if sess.hasStreamOfType("video") and sess.streamHandlerOfType("video") != self.streamController)
if not other_video_sessions:
self.localVideoWindow = VideoLocalWindowController(self)
@objc.python_method
def _NH_BlinkMuteChangedState(self, sender, data):
self.updateMuteButton()
@objc.python_method
def _NH_BlinkAudioStreamChangedHoldState(self, sender, data):
self.updateHoldButton()
@objc.python_method
def _NH_VideoDeviceDidChangeCamera(self, sender, data):
self.myVideoView.setProducer(data.new_camera)
@property
def media_received(self):
return self.streamController.media_received
@objc.python_method
def updateMuteButton(self):
self.muteButton.setImage_(NSImage.imageNamed_("muted" if SIPManager().is_muted() else "mute-white"))
@objc.python_method
def updateHoldButton(self):
audio_stream = self.sessionController.streamHandlerOfType("audio")
if audio_stream:
if audio_stream.status == STREAM_CONNECTED:
if audio_stream.holdByLocal:
self.holdButton.setToolTip_(NSLocalizedString("Unhold", "Label"))
else:
self.holdButton.setToolTip_(NSLocalizedString("Hold", "Label"))
if audio_stream.holdByLocal or audio_stream.holdByRemote:
self.holdButton.setImage_(NSImage.imageNamed_("paused-red"))
else:
self.holdButton.setImage_(NSImage.imageNamed_("pause-white"))
else:
self.holdButton.setImage_(NSImage.imageNamed_("pause-white"))
else:
self.holdButton.setImage_(NSImage.imageNamed_("pause-white"))
@objc.python_method
@run_in_gui_thread
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification.sender, notification.data)
def awakeFromNib(self):
self.notification_center.add_observer(self,sender=self.streamController.videoRecorder)
self.notification_center.add_observer(self, name='BlinkMuteChangedState')
self.notification_center.add_observer(self, name='BlinkAudioStreamChangedHoldState')
self.notification_center.add_observer(self, name='VideoDeviceDidChangeCamera')
self.hangupButton.setToolTip_(NSLocalizedString("Hangup", "Label"))
self.chatButton.setToolTip_(NSLocalizedString("Chat", "Label"))
self.infoButton.setToolTip_(NSLocalizedString("Show Session Information", "Label"))
self.muteButton.setToolTip_(NSLocalizedString("Mute", "Label"))
self.aspectButton.setToolTip_(NSLocalizedString("Aspect", "Label"))
self.screenshotButton.setToolTip_(NSLocalizedString("Screenshot", "Label"))
self.recordButton.setToolTip_(NSLocalizedString("Start Recording", "Label"))
self.fullScreenButton.setToolTip_(NSLocalizedString("Full Screen", "Label"))
self.disconnectLabel.superview().hide()
self.recordButton.setEnabled_(False)
self.updateMuteButton()
self.updateHoldButton()
self.recording_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(0.5, self, "updateRecordingTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.recording_timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.recording_timer, NSEventTrackingRunLoopMode)
@property
def sessionController(self):
if self.streamController:
return self.streamController.sessionController
else:
return None
@objc.python_method
def init_aspect_ratio(self, width, height):
self.sessionController.log_info('Remote video stream at %0.fx%0.f resolution' % (width, height))
self.aspect_ratio = floor((float(width) / height) * 100)/100
self.sessionController.log_info('Remote aspect ratio is %s' % self.aspect_ratio)
found = False
for ratio in self.valid_aspect_ratios:
if ratio is None:
continue
diff = ratio - self.aspect_ratio
if diff < 0:
diff = diff * -1
if self.aspect_ratio > 0.95 * ratio and self.aspect_ratio < 1.05 * ratio:
found = True
break
if self.aspect_ratio == 1:
self.aspect_ratio = 1.77
found = True
if not found:
self.valid_aspect_ratios.append(self.aspect_ratio)
frame = self.window().frame()
frame.size.height = frame.size.width / self.aspect_ratio
self.window().setFrame_display_(frame, True)
self.window().center()
if self.initial_aspect_ratio is None:
self.initial_aspect_ratio = self.aspect_ratio
@objc.python_method
def init_window(self):
if self.window() is not None:
return
if self.streamController.stream is None:
return
NSBundle.loadNibNamed_owner_("VideoWindow", self)
title = NSLocalizedString("Video with %s", "Window title") % self.title
NSApplication.sharedApplication().addWindowsItem_title_filename_(self.window(), title, False)
self.window().center()
self.window().setDelegate_(self)
self.sessionController.log_debug('Init %s in %s' % (self.window(), self))
self.window().makeFirstResponder_(self.videoView)
self.window().setAcceptsMouseMovedEvents_(True)
self.window().setTitle_(title)
self.updateTrackingAreas()
self.showTitleBar()
if SIPSimpleSettings().video.keep_window_on_top:
self.toogleAlwaysOnTop()
self.startIdleTimer()
@objc.python_method
def showTitleBar(self):
if self.streamController.ended:
return
if self.titleBarView is None:
self.titleBarView = TitleBarView.alloc().initWithWindowController_(self)
themeFrame = self.window().contentView().superview()
topmenu_frame = self.titleBarView.view.frame()
newFrame = NSMakeRect(
0,
themeFrame.frame().size.height - topmenu_frame.size.height,
themeFrame.frame().size.width,
topmenu_frame.size.height)
self.titleBarView.view.setFrame_(newFrame)
themeFrame.addSubview_(self.titleBarView.view)
@objc.python_method
def hideTitleBar(self):
self.titleBarView.view.removeFromSuperview()
def rightMouseDown_(self, event):
if self.closed:
return
point = self.window().convertScreenToBase_(NSEvent.mouseLocation())
event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
NSRightMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(), self.window().windowNumber(),
self.window().graphicsContext(), 0, 1, 0)
menu = NSMenu.alloc().init()
if self.streamController.zrtp_active:
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Encrypted using ZRTP", "Menu item"), "", "")
lastItem.setEnabled_(False)
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Verify Peer...", "Menu item"), "userClickedVerifyPeer:", "")
lastItem.setIndentationLevel_(1)
menu.addItem_(NSMenuItem.separatorItem())
menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Remove Video", "Menu item"), "removeVideo:", "")
menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Hangup", "Menu item"), "hangup:", "")
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Hold", "Menu item"), "userClickedHoldButton:", "")
if self.sessionController.hasStreamOfType("audio"):
audio_stream = self.sessionController.streamHandlerOfType("audio")
if audio_stream and audio_stream.status == STREAM_CONNECTED and not self.sessionController.inProposal:
if audio_stream.holdByLocal:
lastItem.setTitle_(NSLocalizedString("Unhold", "Label"))
else:
lastItem.setTitle_(NSLocalizedString("Hold", "Label"))
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Mute", "Menu item"), "userClickedMuteButton:", "")
lastItem.setState_(NSOnState if SIPManager().is_muted() else NSOffState)
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Always On Top", "Menu item"), "toogleAlwaysOnTop:", "")
lastItem.setEnabled_(not self.full_screen)
lastItem.setState_(NSOnState if self.always_on_top else NSOffState)
if self.sessionController.hasStreamOfType("chat"):
menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Attach To Chat Drawer", "Menu item"), "userClickedAttachToChatMenuItem:", "")
if self.sessionController.hasStreamOfType("audio"):
menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Attach To Audio Drawer", "Menu item"), "userClickedAttachToAudioMenuItem:", "")
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Full Screen", "Menu item"), "userClickedFullScreenButton:", "")
menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Aspect", "Menu item"), "userClickedAspectButton:", "")
menu.addItem_(NSMenuItem.separatorItem())
menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Screenshot", "Menu item"), "userClickedScreenshotButton:", "")
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Send Screenshot", "Menu item"), "userClickedSendScreenshotButton:", "")
lastItem.setEnabled_(not bool(self.screencapture_file))
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Open Screenshots Folder", "Menu item"), "userClickedOpenScreenshotFolder:", "")
lastItem.setRepresentedObject_(ApplicationData.get('screenshots'))
lastItem.setEnabled_(True)
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Info", "Menu item"), "userClickedInfoButton:", "")
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Local Video", "Menu item"), "userClickedLocalVideo:", "")
lastItem.setState_(NSOffState if self.local_video_hidden else NSOnState)
NSMenu.popUpContextMenu_withEvent_forView_(menu, event, self.window().contentView())
def removeVideo_(self, sender):
self.will_close = True
self.removeVideo()
def hangup_(self, sender):
if self.sessionController:
self.sessionController.end()
def mouseDown_(self, event):
if self.closed:
return
if self.streamController.ended:
return
self.initialLocation = event.locationInWindow()
def mouseUp_(self, event):
if self.closed:
return
if self.streamController.ended:
return
if self.myVideoView and self.myVideoView.is_dragging:
self.myVideoView.goToFinalOrigin()
def mouseDragged_(self, event):
if self.closed:
return
if self.streamController.ended:
return
if self.myVideoView and self.myVideoView.is_dragging:
self.myVideoView.mouseDragged_(event)
def mouseDraggedView_(self, event):
if self.closed:
return
if self.streamController.ended:
return
if not self.initialLocation:
return
if self.full_screen or self.full_screen_in_progress:
return
screenVisibleFrame = NSScreen.mainScreen().visibleFrame()
windowFrame = self.window().frame()
newOrigin = windowFrame.origin
currentLocation = event.locationInWindow()
newOrigin.x += (currentLocation.x - self.initialLocation.x)
newOrigin.y += (currentLocation.y - self.initialLocation.y)
if ((newOrigin.y + windowFrame.size.height) > (screenVisibleFrame.origin.y + screenVisibleFrame.size.height)):
newOrigin.y = screenVisibleFrame.origin.y + (screenVisibleFrame.size.height - windowFrame.size.height)
self.window().setFrameOrigin_(newOrigin)
def updateTrackingAreas(self):
if self.closed:
return
self.closeTrackingAreas()
rect = NSZeroRect
rect.size = self.window().contentView().frame().size
self.tracking_area = NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(rect,
NSTrackingMouseEnteredAndExited|NSTrackingActiveAlways, self, None)
self.window().contentView().addTrackingArea_(self.tracking_area)
def closeTrackingAreas(self):
if self.tracking_area is not None:
self.window().contentView().removeTrackingArea_(self.tracking_area)
self.tracking_area = None
@property
def sessionController(self):
if self.streamController:
return self.streamController.sessionController
else:
return None
def windowDidResignKey_(self, notification):
self.is_key_window = False
def windowDidBecomeKey_(self, notification):
self.is_key_window = True
def keyDown_(self, event):
if self.closed:
return
if event.keyCode() == 53:
if self.full_screen:
self.toggleFullScreen()
else:
if self.sessionController:
self.sessionController.removeVideoFromSession()
def mouseEntered_(self, event):
if self.closed:
return
if self.streamController.ended:
return
self.mouse_in_window = True
self.stopMouseOutTimer()
self.showButtons()
def mouseExited_(self, event):
if self.closed:
return
if self.streamController.ended:
return
if self.full_screen or self.full_screen_in_progress:
return
self.mouse_in_window = False
self.startMouseOutTimer()
@objc.python_method
def hideStatusLabel(self):
if self.disconnectLabel:
self.disconnectLabel.setStringValue_("")
self.disconnectLabel.superview().hide()
@objc.python_method
def showStatusLabel(self, label):
self.last_label = label
if self.window():
self.disconnectLabel.superview().show()
self.disconnectLabel.setStringValue_(label)
self.disconnectLabel.setHidden_(False)
if self.localVideoWindow and self.localVideoWindow.window():
self.localVideoWindow.window().delegate().disconnectLabel.setStringValue_(label)
self.localVideoWindow.window().delegate().disconnectLabel.superview().show()
self.localVideoWindow.window().delegate().disconnectLabel.setHidden_(False)
@objc.python_method
def startIdleTimer(self):
if self.idle_timer is None:
self.idle_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(0.5, self, "updateIdleTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.idle_timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.idle_timer, NSEventTrackingRunLoopMode)
@objc.python_method
def stopIdleTimer(self):
if self.idle_timer is not None and self.idle_timer.isValid():
self.idle_timer.invalidate()
self.idle_timer = None
@objc.python_method
def changeAspectRatio(self):
try:
idx = self.valid_aspect_ratios.index(self.aspect_ratio)
except ValueError:
self.aspect_ratio = None
else:
try:
self.aspect_ratio = self.valid_aspect_ratios[idx+1]
except IndexError:
self.aspect_ratio = self.valid_aspect_ratios[1]
if self.aspect_ratio:
try:
desc = self.aspect_ratio_descriptions[self.aspect_ratio]
except KeyError:
desc = "%.2f" % self.aspect_ratio
self.sessionController.log_info("Aspect ratio set to %s" % desc)
self.updateAspectRatio()
@objc.python_method
def updateAspectRatio(self):
if self.closed:
return
if not self.window():
return
if self.aspect_ratio is not None:
self.updating_aspect_ratio = True
frame = self.window().frame()
currentSize = frame.size
scaledSize = currentSize
scaledSize.height = scaledSize.width / self.aspect_ratio
frame.size = scaledSize
self.window().setFrame_display_animate_(frame, True, False)
mask = self.videoView.autoresizingMask()
frame = self.videoView.superview().frame()
currentSize = frame.size
scaledSize = currentSize
scaledSize.height = scaledSize.width / self.aspect_ratio
if abs(scaledSize.height - self.window().frame().size.height) < 1:
scaledSize.height = self.window().frame().size.height
if scaledSize.height > self.window().frame().size.height:
scaledSize.height = self.window().frame().size.height
scaledSize.width = scaledSize.height * self.aspect_ratio
frame.size = scaledSize
self.videoView.setFrame_(frame)
origin = NSMakePoint(
(NSWidth(self.videoView.superview().bounds()) - NSWidth(self.videoView.frame())) / 2,
(NSHeight(self.videoView.superview().bounds()) - NSHeight(self.videoView.frame())) / 2)
self.videoView.setFrameOrigin_(origin)
self.videoView.setAutoresizingMask_(mask)
self.updating_aspect_ratio = False
@objc.python_method
@run_in_gui_thread
def show(self):
if self.closed:
return
if self.will_close:
return
self.sessionController.log_debug("Show %s" % self)
self.init_window()
if self.sessionController.video_consumer == "standalone":
self.videoView.setProducer(self.streamController.stream.producer)
self.myVideoView.setProducer(SIPApplication.video_device.producer)
self.updateAspectRatio()
self.showButtons()
self.repositionMyVideo()
if self.sessionController.video_consumer == "standalone":
if self.streamController.status == STREAM_CONNECTED:
if self.localVideoWindow and not self.flipped:
self.localVideoWindow.window().orderOut_(None)
if self.streamController.media_received:
self.hideStatusLabel()
self.window().orderOut_(None)
self.flipWnd.flip_to_(self.localVideoWindow.window(), self.window())
self.flipped = True
else:
self.window().makeKeyAndOrderFront_(self)
else:
show_last_label = False
if not self.localVideoWindow:
self.localVideoWindow = VideoLocalWindowController(self)
show_last_label = True
self.localVideoWindow.show()
if show_last_label and self.last_label:
self.showStatusLabel(self.last_label)
else:
self.flipped = True